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 namespace App\AdminBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="User") * @ORM\Entity(repositoryClass="App\AdminBundle\Entity\UserRepository") */ class User { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string") * @Assert\NotBlank() */ private $nombre; /** * @ORM\Column(type="string") * @Assert\NotBlank() */ private $apellido; /** * @ORM\Column(type="string") */ private $sexo; /** * @ORM\Column(type="integer") * @Assert\Max(limit = 99, message = "No puedes tener más de 99 años.") * @Assert\Min(limit = 14, message = "No puedes tener menos de 14 años.") */ private $edad; /** * @ORM\Column(type="string",name="fecha_nacimiento") */ private $fechaNacimiento; /** * @ORM\Column(type="string",name="lugar_nacimiento") */ private $lugarNacimiento; /** * @ORM\Column(type="string",name="documento_id") */ private $documentoId; /** * @ORM\Column(type="string") */ private $departamento; /** * @ORM\Column(type="string") */ private $ciudad; /** * @ORM\Column(type="string") */ private $direccion; /** * @ORM\Column(type="integer") * @Assert\NotNull() * @Assert\Max(limit = 3, message = "Lo sentimos, está beca solo aplica para estratos de 1 a 3.") * @Assert\Min(limit = 1, message = "Lo sentimos, está beca solo aplica para estratos de 1 a 3.") */ private $estrato; /** * @ORM\Column(type="string") */ private $telefono; /** * @ORM\Column(type="string") */ private $correo; /** * @ORM\Column(type="string") */ private $acudiente; /** * @ORM\Column(type="string") */ private $parentesco; /** * @ORM\Column(type="string",name="estado_civil") */ private $estadoCivil; /** * @ORM\Column(type="integer",name="numeros_hermanos") */ private $numerosHermanos; /** * @ORM\Column(type="string",name="carrera_del_aspirante") */ private $carreraDelAspirante; /** * @ORM\Column(type="string",name="nombre_colegio") */ private $nombreColegio; /** * @ORM\Column(type="string",name="municipio_colegio") */ private $municipioColegio; /** * @ORM\Column(type="string",name="telefono_colegio") */ private $telefonoColegio; /** * @ORM\Column(type="string",name="nombre_rector_colegio") */ private $nombreRectorColegio; /** * @ORM\Column(type="string",name="fecha_graduacion") */ private $fechaGraduacion; /** * @ORM\Column(type="string",name="tipo_documento_icfes") */ private $tipoDocumentoIcfes; /** * @ORM\Column(type="string",name="documento_id_icfes") */ private $documentoIdIcfes; /** * @ORM\Column(type="decimal",name="promedio_icfes") */ private $promedioIcfes; /** * @ORM\Column(type="decimal",name="punt_matem_icfes") */ private $puntMatemIcfes; /** * @ORM\Column(type="decimal",name="punt_lengu_icfes") */ private $puntLenguIcfes; /** * @ORM\Column(type="decimal",name="punt_fisica_icfes") */ private $puntFisicaIcfes; /** * @ORM\Column(type="decimal",name="punt_filos_icfes") */ private $puntFilosIcfes; /** * @ORM\Column(type="decimal",name="punt_min_nucleo") */ private $puntMinNucleo; /** * @ORM\Column(type="string",name="nombre_padre") */ private $nombrePadre; /** * @ORM\Column(type="string",name="estado_trabajo_padre") */ private $estadoTrabajoPadre; /** * @ORM\Column(type="string",name="trabajo_padre") */ private $trabajoPadre; /** * @ORM\Column(type="string",name="ocupacion_padre") */ private $ocupacionPadre; /** * @ORM\Column(type="string",name="telefono_padre") */ private $telefonoPadre; /** * @ORM\Column(type="string",name="nombre_madre") */ private $nombreMadre; /** * @ORM\Column(type="string",name="estado_trabajo_madre") */ private $estadoTrabajoMadre; /** * @ORM\Column(type="string",name="trabajo_madre") */ private $trabajoMadre; /** * @ORM\Column(type="string",name="ocupacion_madre") */ private $ocupacionMadre; /** * @ORM\Column(type="string",name="telefono_madre") */ private $telefonoMadre; /** * @ORM\Column(type="string",name="estado_civil_padres") */ private $estadoCivilPadres; /** * @ORM\Column(type="string",name="responsable_del_sostenimiento_del_hogar") */ private $responsableDelSostenimientoDelHogar; /** * @ORM\Column(type="string",name="dirrecion_familiar") */ private $dirrecionFamiliar; /** * @ORM\Column(type="string",name="tipo_de_vivienda") */ private $tipoDeVivienda; /** * @ORM\Column(type="integer",name="numero_de_habitantes_en_vivienda") */ private $numeroDeHabitantesEnVivienda; /** * @ORM\Column(type="string",name="creado") */ private $creado; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre */ public function setNombre($nombre) { $this->nombre = $nombre; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set apellido * * @param string $apellido */ public function setApellido($apellido) { $this->apellido = $apellido; } /** * Get apellidoe * * @return string */ public function getApellido() { return $this->apellido; } /** * Set sexo * * @param string $sexo */ public function setSexo($sexo) { $this->sexo = $sexo; } /** * Get sexo * * @return string */ public function getSexo() { return $this->sexo; } /** * Set edad * * @param integer $edad */ public function setEdad($edad) { $this->edad = $edad; } /** * Get edad * * @return integer */ public function getEdad() { return $this->edad; } /** * Set fechaNacimiento * * @param string $fechaNacimiento */ public function setFechaNacimiento($fn) { $this->fechaNacimiento = $fn ; } /** * Get fechaNacimiento * * @return string */ public function getFechaNacimiento() { return $this->fechaNacimiento; } /** * Set lugarNacimiento * * @param string $lugarNacimiento */ public function setLugarNacimiento($lugarNacimiento) { $this->lugarNacimiento = $lugarNacimiento; } /** * Get lugarNacimiento * * @return string */ public function getLugarNacimiento() { return $this->lugarNacimiento; } /** * Set documentoId * * @param string $documentoId */ public function setDocumentoId($documentoId) { $this->creado = \time(); $this->documentoId = $documentoId; } /** * Get documentoId * * @return string */ public function getDocumentoId() { return $this->documentoId; } /** * Set departamento * * @param string $departamento */ public function setDepartamento($departamento) { $this->departamento = $departamento; } /** * Get departamento * * @return string */ public function getDepartamento() { return $this->departamento; } /** * Set ciudad * * @param string $ciudad */ public function setCiudad($ciudad) { $this->ciudad = $ciudad; } /** * Get ciudad * * @return string */ public function getCiudad() { return $this->ciudad; } /** * Set direccion * * @param string $direccion */ public function setDireccion($direccion) { $this->direccion = $direccion; } /** * Get direccion * * @return string */ public function getDireccion() { return $this->direccion; } /** * Set estrato * * @param string $estrato */ public function setEstrato($estrato) { $this->estrato = $estrato; } /** * Get estrato * * @return string */ public function getEstrato() { return $this->estrato; } /** * Set telefono * * @param string $telefono */ public function setTelefono($telefono) { $this->telefono = $telefono; } /** * Get telefono * * @return string */ public function getTelefono() { return $this->telefono; } /** * Set correo * * @param string $correo */ public function setCorreo($correo) { $this->correo = $correo; } /** * Get correo * * @return string */ public function getCorreo() { return $this->correo; } /** * Set acudiente * * @param string $acudiente */ public function setAcudiente($acudiente) { $this->acudiente = $acudiente; } /** * Get acudiente * * @return string */ public function getAcudiente() { return $this->acudiente; } /** * Set parentesco * * @param string $parentesco */ public function setParentesco($parentesco) { $this->parentesco = $parentesco; } /** * Get parentesco * * @return string */ public function getParentesco() { return $this->parentesco; } /** * Set estadoCivil * * @param string $estadoCivil */ public function setEstadoCivil($estadoCivil) { $this->estadoCivil = $estadoCivil; } /** * Get estadoCivil * * @return string */ public function getEstadoCivil() { return $this->estadoCivil; } /** * Set numerosHermanos * * @param integer $numerosHermanos */ public function setNumerosHermanos($numerosHermanos) { $this->numerosHermanos = $numerosHermanos; } /** * Get numerosHermanos * * @return integer */ public function getNumerosHermanos() { return $this->numerosHermanos; } /** * Set carreraDelAspirante * * @param integer $carreraDelAspirante */ public function setCarreraDelAspirante($carreraDelAspirante) { $this->carreraDelAspirante = $carreraDelAspirante; } /** * Get carreraDelAspirante * * @return integer */ public function getCarreraDelAspirante() { return $this->carreraDelAspirante; } /** * Set nombreColegio * * @param string $nombreColegio */ public function setNombreColegio($nombreColegio) { $this->nombreColegio = $nombreColegio; } /** * Get nombreColegio * * @return string */ public function getNombreColegio() { return $this->nombreColegio; } /** * Set municipioColegio * * @param string $municipioColegio */ public function setMunicipioColegio($municipioColegio) { $this->municipioColegio = $municipioColegio; } /** * Get municipioColegio * * @return string */ public function getMunicipioColegio() { return $this->municipioColegio; } /** * Set telefonoColegio * * @param string $telefonoColegio */ public function setTelefonoColegio($telefonoColegio) { $this->telefonoColegio = $telefonoColegio; } /** * Get telefonoColegio * * @return string */ public function getTelefonoColegio() { return $this->telefonoColegio; } /** * Set nombreRectorColegio * * @param string $nombreRectorColegio */ public function setNombreRectorColegio($nombreRectorColegio) { $this->nombreRectorColegio = $nombreRectorColegio; } /** * Get nombreRectorColegio * * @return string */ public function getNombreRectorColegio() { return $this->nombreRectorColegio; } /** * Set fechaGraduacion * * @param string $fechaGraduacion */ public function setFechaGraduacion($fechaGraduacion) { $this->fechaGraduacion = $fechaGraduacion; } /** * Get fechaGraduacion * * @return string */ public function getFechaGraduacion() { return $this->fechaGraduacion; } /** * Set tipoDocumentoIcfes * * @param string $tipoDocumentoIcfes */ public function setTipoDocumentoIcfes($tipoDocumentoIcfes) { $this->tipoDocumentoIcfes = $tipoDocumentoIcfes; } /** * Get tipoDocumentoIcfes * * @return string */ public function getTipoDocumentoIcfes() { return $this->tipoDocumentoIcfes; } /** * Set documentoIdIcfes * * @param string $documentoIdIcfes */ public function setDocumentoIdIcfes($documentoIdIcfes) { $this->documentoIdIcfes = $documentoIdIcfes; } /** * Get documentoIdIcfess * * @return string */ public function getDocumentoIdIcfes() { return $this->documentoIdIcfes; } /** * Set promedioIcfes * * @param decimal $promedioIcfes */ public function setPromedioIcfes($promedioIcfes) { $this->promedioIcfes = $promedioIcfes; } /** * Get promedioIcfes * * @return decimal */ public function getPromedioIcfes() { return $this->promedioIcfes; } /** * Set puntMatemIcfes * * @param decimal $puntMatemIcfes */ public function setPuntMatemIcfes($puntMatemIcfes) { $this->puntMatemIcfes = $puntMatemIcfes; } /** * Get puntMatemIcfes * * @return decimal */ public function getPuntMatemIcfes() { return $this->puntMatemIcfes; } /** * Set puntLenguIcfes * * @param decimal $puntLenguIcfes */ public function setPuntLenguIcfes($puntLenguIcfes) { $this->puntLenguIcfes = $puntLenguIcfes; } /** * Get puntLenguIcfes * * @return decimal */ public function getPuntLenguIcfes() { return $this->puntLenguIcfes; } /** * Set puntFisicaIcfes * * @param decimal $puntFisicaIcfes */ public function setPuntFisicaIcfes($puntFisicaIcfes) { $this->puntFisicaIcfes = $puntFisicaIcfes; } /** * Get puntFisicaIcfes * * @return decimal */ public function getPuntFisicaIcfes() { return $this->puntFisicaIcfes; } /** * Set puntFilosIcfes * * @param decimal $puntFilosIcfes */ public function setPuntFilosIcfes($puntFilosIcfes) { $this->puntFilosIcfes = $puntFilosIcfes; } /** * Get puntFilosIcfes * * @return decimal */ public function getPuntFilosIcfes() { return $this->puntFilosIcfes; } /** * Set puntMinNucleo * * @param decimal $puntMinNucleo */ public function setPuntMinNucleo($puntMinNucleo) { $this->puntMinNucleo = $puntMinNucleo; } /** * Get puntMinNucleo * * @return decimal */ public function getPuntMinNucleo() { return $this->puntMinNucleo; } /** * Set nombrePadre * * @param string $nombrePadre */ public function setNombrePadre($nombrePadre) { $this->nombrePadre = $nombrePadre; } /** * Get nombrePadre * * @return string */ public function getNombrePadre() { return $this->nombrePadre; } /** * Set estadoTrabajoPadre * * @param string $estadoTrabajoPadre */ public function setEstadoTrabajoPadre($estadoTrabajoPadre) { $this->estadoTrabajoPadre = $estadoTrabajoPadre; } /** * Get estadoTrabajoPadre * * @return string */ public function getEstadoTrabajoPadre() { return $this->estadoTrabajoPadre; } /** * Set trabajoPadre * * @param string $trabajoPadre */ public function setTrabajoPadre($trabajoPadre) { $this->trabajoPadre = $trabajoPadre; } /** * Get trabajoPadre * * @return string */ public function getTrabajoPadre() { return $this->trabajoPadre; } /** * Set ocupacionPadre * * @param string $ocupacionPadre */ public function setOcupacionPadre($ocupacionPadre) { $this->ocupacionPadre = $ocupacionPadre; } /** * Get ocupacionPadre * * @return string */ public function getOcupacionPadre() { return $this->ocupacionPadre; } /** * Set telefonoPadre * * @param string $telefonoPadre */ public function setTelefonoPadre($telefonoPadre) { $this->telefonoPadre = $telefonoPadre; } /** * Get telefonoPadre * * @return string */ public function getTelefonoPadre() { return $this->telefonoPadre; } /** * Set nombreMadre * * @param string $nombreMadre */ public function setNombreMadre($nombreMadre) { $this->nombreMadre = $nombreMadre; } /** * Get nombreMadre * * @return string */ public function getNombreMadre() { return $this->nombreMadre; } /** * Set estadoTrabajoMadre * * @param string $estadoTrabajoMadre */ public function setEstadoTrabajoMadre($estadoTrabajoMadre) { $this->estadoTrabajoMadre = $estadoTrabajoMadre; } /** * Get estadoTrabajoMadre * * @return string */ public function getEstadoTrabajoMadre() { return $this->estadoTrabajoMadre; } /** * Set trabajoMadre * * @param string $trabajoMadre */ public function setTrabajoMadre($trabajoMadre) { $this->trabajoMadre = $trabajoMadre; } /** * Get trabajoMadre * * @return string */ public function getTrabajoMadre() { return $this->trabajoMadre; } /** * Set ocupacionMadre * * @param string $ocupacionMadre */ public function setOcupacionMadre($ocupacionMadre) { $this->ocupacionMadre = $ocupacionMadre; } /** * Get ocupacionMadre * * @return string */ public function getOcupacionMadre() { return $this->ocupacionMadre; } /** * Set telefonoMadre * * @param integer $telefonoMadre */ public function setTelefonoMadre($telefonoMadre) { $this->telefonoMadre = $telefonoMadre; } /** * Get telefonoMadre * * @return integer */ public function getTelefonoMadre() { return $this->telefonoMadre; } /** * Set estadoCivilPadres * * @param string $estadoCivilPadres */ public function setEstadoCivilPadres($estadoCivilPadres) { $this->estadoCivilPadres = $estadoCivilPadres; } /** * Get estadoCivilPadres * * @return string */ public function getEstadoCivilPadres() { return $this->estadoCivilPadres; } /** * Set responsableDelSostenimientoDelHogar * * @param string $responsableDelSostenimientoDelHogar */ public function setResponsableDelSostenimientoDelHogar($responsableDelSostenimientoDelHogar) { $this->responsableDelSostenimientoDelHogar = $responsableDelSostenimientoDelHogar; } /** * Get responsableDelSostenimientoDelHogar * * @return string */ public function getResponsableDelSostenimientoDelHogar() { return $this->responsableDelSostenimientoDelHogar; } /** * Set dirrecionFamiliar * * @param string $dirrecionFamiliar */ public function setDirrecionFamiliar($dirrecionFamiliar) { $this->dirrecionFamiliar = $dirrecionFamiliar; } /** * Get dirrecionFamiliar * * @return string */ public function getDirrecionFamiliar() { return $this->dirrecionFamiliar; } /** * Set tipoDeVivienda * * @param string $tipoDeVivienda */ public function setTipoDeVivienda($tipoDeVivienda) { $this->tipoDeVivienda = $tipoDeVivienda; } /** * Get tipoDeVivienda * * @return string */ public function getTipoDeVivienda() { return $this->tipoDeVivienda; } /** * Set numeroDeHabitantesEnVivienda * * @param integer $numeroDeHabitantesEnVivienda */ public function setNumeroDeHabitantesEnVivienda($numeroDeHabitantesEnVivienda) { $this->numeroDeHabitantesEnVivienda = $numeroDeHabitantesEnVivienda; } /** * Get numeroDeHabitantesEnVivienda * * @return integer */ public function getNumeroDeHabitantesEnVivienda() { return $this->numeroDeHabitantesEnVivienda; } }
jairoserrano/becasUTB
src/App/AdminBundle/Entity/User.php
PHP
agpl-3.0
22,224
import factory from .models import User USER_PASSWORD = "2fast2furious" class UserFactory(factory.DjangoModelFactory): name = "John Doe" email = factory.Sequence(lambda n: "john{}@example.com".format(n)) password = factory.PostGenerationMethodCall('set_password', USER_PASSWORD) gender = "male" class Meta: model = User
ballotify/django-backend
ballotify/apps/accounts/factories.py
Python
agpl-3.0
353
// ----------> GENERATED FILE - DON'T TOUCH! <---------- // generator: ilarkesto.mda.legacy.generator.DaoGenerator package scrum.server.admin; import java.util.*; import ilarkesto.persistence.*; import ilarkesto.core.logging.Log; import ilarkesto.base.*; import ilarkesto.base.time.*; import ilarkesto.auth.*; import ilarkesto.fp.*; public abstract class GUserDao extends ilarkesto.auth.AUserDao<User> { public final String getEntityName() { return User.TYPE; } public final Class getEntityClass() { return User.class; } public Set<User> getEntitiesVisibleForUser(final scrum.server.admin.User user) { return getEntities(new Predicate<User>() { public boolean test(User e) { return Auth.isVisible(e, user); } }); } // --- clear caches --- public void clearCaches() { namesCache = null; usersByAdminCache.clear(); usersByEmailVerifiedCache.clear(); emailsCache = null; usersByCurrentProjectCache.clear(); currentProjectsCache = null; usersByColorCache.clear(); colorsCache = null; usersByLastLoginDateAndTimeCache.clear(); lastLoginDateAndTimesCache = null; usersByRegistrationDateAndTimeCache.clear(); registrationDateAndTimesCache = null; usersByDisabledCache.clear(); usersByHideUserGuideBlogCache.clear(); usersByHideUserGuideCalendarCache.clear(); usersByHideUserGuideFilesCache.clear(); usersByHideUserGuideForumCache.clear(); usersByHideUserGuideImpedimentsCache.clear(); usersByHideUserGuideIssuesCache.clear(); usersByHideUserGuideJournalCache.clear(); usersByHideUserGuideNextSprintCache.clear(); usersByHideUserGuideProductBacklogCache.clear(); usersByHideUserGuideCourtroomCache.clear(); usersByHideUserGuideQualityBacklogCache.clear(); usersByHideUserGuideReleasesCache.clear(); usersByHideUserGuideRisksCache.clear(); usersByHideUserGuideSprintBacklogCache.clear(); usersByHideUserGuideWhiteboardCache.clear(); loginTokensCache = null; openIdsCache = null; } @Override public void entityDeleted(EntityEvent event) { super.entityDeleted(event); if (event.getEntity() instanceof User) { clearCaches(); } } @Override public void entitySaved(EntityEvent event) { super.entitySaved(event); if (event.getEntity() instanceof User) { clearCaches(); } } // ----------------------------------------------------------- // - name // ----------------------------------------------------------- public final User getUserByName(java.lang.String name) { return getEntity(new IsName(name)); } private Set<java.lang.String> namesCache; public final Set<java.lang.String> getNames() { if (namesCache == null) { namesCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isNameSet()) namesCache.add(e.getName()); } } return namesCache; } private static class IsName implements Predicate<User> { private java.lang.String value; public IsName(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isName(value); } } // ----------------------------------------------------------- // - admin // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByAdminCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean admin) { return getEntities(new IsAdmin(admin)); } }); public final Set<User> getUsersByAdmin(boolean admin) { return usersByAdminCache.get(admin); } private static class IsAdmin implements Predicate<User> { private boolean value; public IsAdmin(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isAdmin(); } } // ----------------------------------------------------------- // - emailVerified // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByEmailVerifiedCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean emailVerified) { return getEntities(new IsEmailVerified(emailVerified)); } }); public final Set<User> getUsersByEmailVerified(boolean emailVerified) { return usersByEmailVerifiedCache.get(emailVerified); } private static class IsEmailVerified implements Predicate<User> { private boolean value; public IsEmailVerified(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isEmailVerified(); } } // ----------------------------------------------------------- // - email // ----------------------------------------------------------- public final User getUserByEmail(java.lang.String email) { return getEntity(new IsEmail(email)); } private Set<java.lang.String> emailsCache; public final Set<java.lang.String> getEmails() { if (emailsCache == null) { emailsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isEmailSet()) emailsCache.add(e.getEmail()); } } return emailsCache; } private static class IsEmail implements Predicate<User> { private java.lang.String value; public IsEmail(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isEmail(value); } } // ----------------------------------------------------------- // - currentProject // ----------------------------------------------------------- private final Cache<scrum.server.project.Project,Set<User>> usersByCurrentProjectCache = new Cache<scrum.server.project.Project,Set<User>>( new Cache.Factory<scrum.server.project.Project,Set<User>>() { public Set<User> create(scrum.server.project.Project currentProject) { return getEntities(new IsCurrentProject(currentProject)); } }); public final Set<User> getUsersByCurrentProject(scrum.server.project.Project currentProject) { return usersByCurrentProjectCache.get(currentProject); } private Set<scrum.server.project.Project> currentProjectsCache; public final Set<scrum.server.project.Project> getCurrentProjects() { if (currentProjectsCache == null) { currentProjectsCache = new HashSet<scrum.server.project.Project>(); for (User e : getEntities()) { if (e.isCurrentProjectSet()) currentProjectsCache.add(e.getCurrentProject()); } } return currentProjectsCache; } private static class IsCurrentProject implements Predicate<User> { private scrum.server.project.Project value; public IsCurrentProject(scrum.server.project.Project value) { this.value = value; } public boolean test(User e) { return e.isCurrentProject(value); } } // ----------------------------------------------------------- // - color // ----------------------------------------------------------- private final Cache<java.lang.String,Set<User>> usersByColorCache = new Cache<java.lang.String,Set<User>>( new Cache.Factory<java.lang.String,Set<User>>() { public Set<User> create(java.lang.String color) { return getEntities(new IsColor(color)); } }); public final Set<User> getUsersByColor(java.lang.String color) { return usersByColorCache.get(color); } private Set<java.lang.String> colorsCache; public final Set<java.lang.String> getColors() { if (colorsCache == null) { colorsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isColorSet()) colorsCache.add(e.getColor()); } } return colorsCache; } private static class IsColor implements Predicate<User> { private java.lang.String value; public IsColor(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isColor(value); } } // ----------------------------------------------------------- // - lastLoginDateAndTime // ----------------------------------------------------------- private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> usersByLastLoginDateAndTimeCache = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>( new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() { public Set<User> create(ilarkesto.base.time.DateAndTime lastLoginDateAndTime) { return getEntities(new IsLastLoginDateAndTime(lastLoginDateAndTime)); } }); public final Set<User> getUsersByLastLoginDateAndTime(ilarkesto.base.time.DateAndTime lastLoginDateAndTime) { return usersByLastLoginDateAndTimeCache.get(lastLoginDateAndTime); } private Set<ilarkesto.base.time.DateAndTime> lastLoginDateAndTimesCache; public final Set<ilarkesto.base.time.DateAndTime> getLastLoginDateAndTimes() { if (lastLoginDateAndTimesCache == null) { lastLoginDateAndTimesCache = new HashSet<ilarkesto.base.time.DateAndTime>(); for (User e : getEntities()) { if (e.isLastLoginDateAndTimeSet()) lastLoginDateAndTimesCache.add(e.getLastLoginDateAndTime()); } } return lastLoginDateAndTimesCache; } private static class IsLastLoginDateAndTime implements Predicate<User> { private ilarkesto.base.time.DateAndTime value; public IsLastLoginDateAndTime(ilarkesto.base.time.DateAndTime value) { this.value = value; } public boolean test(User e) { return e.isLastLoginDateAndTime(value); } } // ----------------------------------------------------------- // - registrationDateAndTime // ----------------------------------------------------------- private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> usersByRegistrationDateAndTimeCache = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>( new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() { public Set<User> create(ilarkesto.base.time.DateAndTime registrationDateAndTime) { return getEntities(new IsRegistrationDateAndTime(registrationDateAndTime)); } }); public final Set<User> getUsersByRegistrationDateAndTime(ilarkesto.base.time.DateAndTime registrationDateAndTime) { return usersByRegistrationDateAndTimeCache.get(registrationDateAndTime); } private Set<ilarkesto.base.time.DateAndTime> registrationDateAndTimesCache; public final Set<ilarkesto.base.time.DateAndTime> getRegistrationDateAndTimes() { if (registrationDateAndTimesCache == null) { registrationDateAndTimesCache = new HashSet<ilarkesto.base.time.DateAndTime>(); for (User e : getEntities()) { if (e.isRegistrationDateAndTimeSet()) registrationDateAndTimesCache.add(e.getRegistrationDateAndTime()); } } return registrationDateAndTimesCache; } private static class IsRegistrationDateAndTime implements Predicate<User> { private ilarkesto.base.time.DateAndTime value; public IsRegistrationDateAndTime(ilarkesto.base.time.DateAndTime value) { this.value = value; } public boolean test(User e) { return e.isRegistrationDateAndTime(value); } } // ----------------------------------------------------------- // - disabled // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByDisabledCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean disabled) { return getEntities(new IsDisabled(disabled)); } }); public final Set<User> getUsersByDisabled(boolean disabled) { return usersByDisabledCache.get(disabled); } private static class IsDisabled implements Predicate<User> { private boolean value; public IsDisabled(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isDisabled(); } } // ----------------------------------------------------------- // - hideUserGuideBlog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideBlogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideBlog) { return getEntities(new IsHideUserGuideBlog(hideUserGuideBlog)); } }); public final Set<User> getUsersByHideUserGuideBlog(boolean hideUserGuideBlog) { return usersByHideUserGuideBlogCache.get(hideUserGuideBlog); } private static class IsHideUserGuideBlog implements Predicate<User> { private boolean value; public IsHideUserGuideBlog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideBlog(); } } // ----------------------------------------------------------- // - hideUserGuideCalendar // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideCalendarCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideCalendar) { return getEntities(new IsHideUserGuideCalendar(hideUserGuideCalendar)); } }); public final Set<User> getUsersByHideUserGuideCalendar(boolean hideUserGuideCalendar) { return usersByHideUserGuideCalendarCache.get(hideUserGuideCalendar); } private static class IsHideUserGuideCalendar implements Predicate<User> { private boolean value; public IsHideUserGuideCalendar(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideCalendar(); } } // ----------------------------------------------------------- // - hideUserGuideFiles // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideFilesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideFiles) { return getEntities(new IsHideUserGuideFiles(hideUserGuideFiles)); } }); public final Set<User> getUsersByHideUserGuideFiles(boolean hideUserGuideFiles) { return usersByHideUserGuideFilesCache.get(hideUserGuideFiles); } private static class IsHideUserGuideFiles implements Predicate<User> { private boolean value; public IsHideUserGuideFiles(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideFiles(); } } // ----------------------------------------------------------- // - hideUserGuideForum // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideForumCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideForum) { return getEntities(new IsHideUserGuideForum(hideUserGuideForum)); } }); public final Set<User> getUsersByHideUserGuideForum(boolean hideUserGuideForum) { return usersByHideUserGuideForumCache.get(hideUserGuideForum); } private static class IsHideUserGuideForum implements Predicate<User> { private boolean value; public IsHideUserGuideForum(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideForum(); } } // ----------------------------------------------------------- // - hideUserGuideImpediments // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideImpedimentsCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideImpediments) { return getEntities(new IsHideUserGuideImpediments(hideUserGuideImpediments)); } }); public final Set<User> getUsersByHideUserGuideImpediments(boolean hideUserGuideImpediments) { return usersByHideUserGuideImpedimentsCache.get(hideUserGuideImpediments); } private static class IsHideUserGuideImpediments implements Predicate<User> { private boolean value; public IsHideUserGuideImpediments(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideImpediments(); } } // ----------------------------------------------------------- // - hideUserGuideIssues // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideIssuesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideIssues) { return getEntities(new IsHideUserGuideIssues(hideUserGuideIssues)); } }); public final Set<User> getUsersByHideUserGuideIssues(boolean hideUserGuideIssues) { return usersByHideUserGuideIssuesCache.get(hideUserGuideIssues); } private static class IsHideUserGuideIssues implements Predicate<User> { private boolean value; public IsHideUserGuideIssues(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideIssues(); } } // ----------------------------------------------------------- // - hideUserGuideJournal // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideJournalCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideJournal) { return getEntities(new IsHideUserGuideJournal(hideUserGuideJournal)); } }); public final Set<User> getUsersByHideUserGuideJournal(boolean hideUserGuideJournal) { return usersByHideUserGuideJournalCache.get(hideUserGuideJournal); } private static class IsHideUserGuideJournal implements Predicate<User> { private boolean value; public IsHideUserGuideJournal(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideJournal(); } } // ----------------------------------------------------------- // - hideUserGuideNextSprint // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideNextSprintCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideNextSprint) { return getEntities(new IsHideUserGuideNextSprint(hideUserGuideNextSprint)); } }); public final Set<User> getUsersByHideUserGuideNextSprint(boolean hideUserGuideNextSprint) { return usersByHideUserGuideNextSprintCache.get(hideUserGuideNextSprint); } private static class IsHideUserGuideNextSprint implements Predicate<User> { private boolean value; public IsHideUserGuideNextSprint(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideNextSprint(); } } // ----------------------------------------------------------- // - hideUserGuideProductBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideProductBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideProductBacklog) { return getEntities(new IsHideUserGuideProductBacklog(hideUserGuideProductBacklog)); } }); public final Set<User> getUsersByHideUserGuideProductBacklog(boolean hideUserGuideProductBacklog) { return usersByHideUserGuideProductBacklogCache.get(hideUserGuideProductBacklog); } private static class IsHideUserGuideProductBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideProductBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideProductBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideCourtroom // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideCourtroomCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideCourtroom) { return getEntities(new IsHideUserGuideCourtroom(hideUserGuideCourtroom)); } }); public final Set<User> getUsersByHideUserGuideCourtroom(boolean hideUserGuideCourtroom) { return usersByHideUserGuideCourtroomCache.get(hideUserGuideCourtroom); } private static class IsHideUserGuideCourtroom implements Predicate<User> { private boolean value; public IsHideUserGuideCourtroom(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideCourtroom(); } } // ----------------------------------------------------------- // - hideUserGuideQualityBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideQualityBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideQualityBacklog) { return getEntities(new IsHideUserGuideQualityBacklog(hideUserGuideQualityBacklog)); } }); public final Set<User> getUsersByHideUserGuideQualityBacklog(boolean hideUserGuideQualityBacklog) { return usersByHideUserGuideQualityBacklogCache.get(hideUserGuideQualityBacklog); } private static class IsHideUserGuideQualityBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideQualityBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideQualityBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideReleases // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideReleasesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideReleases) { return getEntities(new IsHideUserGuideReleases(hideUserGuideReleases)); } }); public final Set<User> getUsersByHideUserGuideReleases(boolean hideUserGuideReleases) { return usersByHideUserGuideReleasesCache.get(hideUserGuideReleases); } private static class IsHideUserGuideReleases implements Predicate<User> { private boolean value; public IsHideUserGuideReleases(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideReleases(); } } // ----------------------------------------------------------- // - hideUserGuideRisks // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideRisksCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideRisks) { return getEntities(new IsHideUserGuideRisks(hideUserGuideRisks)); } }); public final Set<User> getUsersByHideUserGuideRisks(boolean hideUserGuideRisks) { return usersByHideUserGuideRisksCache.get(hideUserGuideRisks); } private static class IsHideUserGuideRisks implements Predicate<User> { private boolean value; public IsHideUserGuideRisks(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideRisks(); } } // ----------------------------------------------------------- // - hideUserGuideSprintBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideSprintBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideSprintBacklog) { return getEntities(new IsHideUserGuideSprintBacklog(hideUserGuideSprintBacklog)); } }); public final Set<User> getUsersByHideUserGuideSprintBacklog(boolean hideUserGuideSprintBacklog) { return usersByHideUserGuideSprintBacklogCache.get(hideUserGuideSprintBacklog); } private static class IsHideUserGuideSprintBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideSprintBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideSprintBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideWhiteboard // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideWhiteboardCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideWhiteboard) { return getEntities(new IsHideUserGuideWhiteboard(hideUserGuideWhiteboard)); } }); public final Set<User> getUsersByHideUserGuideWhiteboard(boolean hideUserGuideWhiteboard) { return usersByHideUserGuideWhiteboardCache.get(hideUserGuideWhiteboard); } private static class IsHideUserGuideWhiteboard implements Predicate<User> { private boolean value; public IsHideUserGuideWhiteboard(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideWhiteboard(); } } // ----------------------------------------------------------- // - loginToken // ----------------------------------------------------------- public final User getUserByLoginToken(java.lang.String loginToken) { return getEntity(new IsLoginToken(loginToken)); } private Set<java.lang.String> loginTokensCache; public final Set<java.lang.String> getLoginTokens() { if (loginTokensCache == null) { loginTokensCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isLoginTokenSet()) loginTokensCache.add(e.getLoginToken()); } } return loginTokensCache; } private static class IsLoginToken implements Predicate<User> { private java.lang.String value; public IsLoginToken(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isLoginToken(value); } } // ----------------------------------------------------------- // - openId // ----------------------------------------------------------- public final User getUserByOpenId(java.lang.String openId) { return getEntity(new IsOpenId(openId)); } private Set<java.lang.String> openIdsCache; public final Set<java.lang.String> getOpenIds() { if (openIdsCache == null) { openIdsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isOpenIdSet()) openIdsCache.add(e.getOpenId()); } } return openIdsCache; } private static class IsOpenId implements Predicate<User> { private java.lang.String value; public IsOpenId(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isOpenId(value); } } // --- valueObject classes --- @Override protected Set<Class> getValueObjectClasses() { Set<Class> ret = new HashSet<Class>(super.getValueObjectClasses()); return ret; } @Override public Map<String, Class> getAliases() { Map<String, Class> aliases = new HashMap<String, Class>(super.getAliases()); return aliases; } // --- dependencies --- scrum.server.project.ProjectDao projectDao; public void setProjectDao(scrum.server.project.ProjectDao projectDao) { this.projectDao = projectDao; } }
hogi/kunagi
src/generated/java/scrum/server/admin/GUserDao.java
Java
agpl-3.0
31,402
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator; /** * These listeners will be notified after a new operator was added to a chain. * * @author Ingo Mierswa */ public interface AddListener { public void operatorAdded(Operator newChild); }
aborg0/rapidminer-vega
src/com/rapidminer/operator/AddListener.java
Java
agpl-3.0
1,124
package info.nightscout.androidaps.plugins.SmsCommunicator; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Comparator; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.utils.DateUtil; /** * A simple {@link Fragment} subclass. */ public class SmsCommunicatorFragment extends SubscriberFragment { private static Logger log = LoggerFactory.getLogger(SmsCommunicatorFragment.class); private static SmsCommunicatorPlugin smsCommunicatorPlugin; public static SmsCommunicatorPlugin getPlugin() { if(smsCommunicatorPlugin==null){ smsCommunicatorPlugin = new SmsCommunicatorPlugin(); } return smsCommunicatorPlugin; } TextView logView; public SmsCommunicatorFragment() { super(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false); logView = (TextView) view.findViewById(R.id.smscommunicator_log); updateGUI(); return view; } @Subscribe public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) { updateGUI(); } @Override protected void updateGUI() { Activity activity = getActivity(); if (activity != null) activity.runOnUiThread(new Runnable() { @Override public void run() { class CustomComparator implements Comparator<SmsCommunicatorPlugin.Sms> { public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) { return (int) (object1.date.getTime() - object2.date.getTime()); } } Collections.sort(getPlugin().messages, new CustomComparator()); int messagesToShow = 40; int start = Math.max(0, getPlugin().messages.size() - messagesToShow); String logText = ""; for (int x = start; x < getPlugin().messages.size(); x++) { SmsCommunicatorPlugin.Sms sms = getPlugin().messages.get(x); if (sms.received) { logText += DateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>"; } else if (sms.sent) { logText += DateUtil.timeString(sms.date) + " &gt;&gt;&gt; " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>"; } } logView.setText(Html.fromHtml(logText)); } }); } }
RoumenGeorgiev/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorFragment.java
Java
agpl-3.0
3,402
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> <title>ByteJudge</title> </head> <body> <div id="wrapper"> <?php require('./scripts/determineidentityfunc.php'); if(!(isloggedin("admin")==true)) { header('Location: ./home.php'); } else { include("./includes/header.php"); include("includes/nav.php"); echo ' <div id="content"> '; include("./includes/view_facultygroups_form.php"); echo ' </div> <!-- end #content --> '; include("./includes/sidebar.php"); include("./includes/footer.php"); } ?> </div> <!-- End #wrapper --> </body> </html>
jdramani/Judge
ByteJudge/view_facultygroups.php
PHP
agpl-3.0
954
/* * ADL2-core * Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com) * * This file is part of ADL2-core. * * ADL2-core is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openehr.adl.am.mixin; import com.google.common.collect.ImmutableMap; import org.openehr.jaxb.am.CAttribute; import org.openehr.jaxb.am.Cardinality; import org.openehr.jaxb.rm.*; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author markopi */ class AmMixinsInternal { private static final Map<Class<?>, Class<? extends AmMixin>> configuration; private static final Map<Class<?>, Constructor<? extends AmMixin>> constructors; static { Map<Class<?>, Class<? extends AmMixin>> conf = ImmutableMap.<Class<?>, Class<? extends AmMixin>>builder() .put(IntervalOfDate.class, IntervalOfDateMixin.class) .put(IntervalOfTime.class, IntervalOfTimeMixin.class) .put(IntervalOfDateTime.class, IntervalOfDateTimeMixin.class) .put(IntervalOfInteger.class, IntervalOfIntegerMixin.class) .put(IntervalOfReal.class, IntervalOfRealMixin.class) .put(MultiplicityInterval.class, MultiplicityIntervalMixin.class) .put(CAttribute.class, CAttributeMixin.class) .put(IntervalOfDuration.class, IntervalOfDurationMixin.class) .put(Cardinality.class, CardinalityMixin.class) .build(); configuration = ImmutableMap.copyOf(conf); constructors = new ConcurrentHashMap<>(); } static <T, M extends AmMixin<?>> M create(T from) { Constructor<? extends AmMixin> mixinConstructor = getMixinClass(from.getClass()); try { return (M) mixinConstructor.newInstance(from); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException( "Error constructing mixin class " + mixinConstructor.getDeclaringClass() + " for class " + from.getClass()); } } private static Constructor<? extends AmMixin> getMixinClass(Class<?> fromClass) { Constructor<? extends AmMixin> result = constructors.get(fromClass); if (result == null) { Class<?> cls = fromClass; while (cls != null) { Class<? extends AmMixin> mixinClass = configuration.get(cls); if (mixinClass != null) { try { result = mixinClass.getConstructor(fromClass); } catch (NoSuchMethodException e) { throw new IllegalStateException( "Missing mixin " + mixinClass.getName() + " constructor for " + fromClass.getName()); } constructors.put(fromClass, result); return result; } cls = cls.getSuperclass(); } throw new IllegalArgumentException("No mixin defined for class " + fromClass); } return result; } }
lonangel/adl2-core
adl-parser/src/main/java/org/openehr/adl/am/mixin/AmMixinsInternal.java
Java
agpl-3.0
3,715
#!/usr/bin/env python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- # # NetProfile: Authentication routines # © Copyright 2013-2014 Alex 'Unik' Unigovsky # # This file is part of NetProfile. # NetProfile is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later # version. # # NetProfile 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General # Public License along with NetProfile. If not, see # <http://www.gnu.org/licenses/>. from __future__ import ( unicode_literals, print_function, absolute_import, division ) import hashlib import random import string import time from zope.interface import implementer from pyramid.interfaces import IAuthenticationPolicy from pyramid.security import ( Authenticated, Everyone ) class PluginPolicySelected(object): def __init__(self, request, policy): self.request = request self.policy = policy @implementer(IAuthenticationPolicy) class PluginAuthenticationPolicy(object): def __init__(self, default, routes=None): self._default = default if routes is None: routes = {} self._routes = routes def add_plugin(self, route, policy): self._routes[route] = policy def match(self, request): if hasattr(request, 'auth_policy'): return request.auth_policy cur = None cur_len = 0 for route, plug in self._routes.items(): r_len = len(route) if r_len <= cur_len: continue path = request.path if route == path[:r_len]: if len(path) > r_len: if path[r_len:r_len + 1] != '/': continue cur = plug cur_len = r_len if cur: request.auth_policy = cur else: request.auth_policy = self._default request.registry.notify(PluginPolicySelected(request, request.auth_policy)) return request.auth_policy def authenticated_userid(self, request): return self.match(request).authenticated_userid(request) def unauthenticated_userid(self, request): return self.match(request).unauthenticated_userid(request) def effective_principals(self, request): return self.match(request).effective_principals(request) def remember(self, request, principal, **kw): return self.match(request).remember(request, principal, **kw) def forget(self, request): return self.match(request).forget(request) _TOKEN_FILTER_MAP = ( [chr(n) for n in range(32)] + [chr(127), '\\', '"'] ) _TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None) def _filter_token(tok): return str(tok).translate(_TOKEN_FILTER_MAP) def _format_kvpairs(**kwargs): return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items()) def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()): # TODO: Add IP-address to nonce if not salt: try: rng = random.SystemRandom() except NotImplementedError: rng = random salt = ''.join(rng.choice(chars) for i in range(16)) ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode()) return ('%s:%s:%s' % (ts, salt, ctx.hexdigest())) def _is_valid_nonce(nonce, secret): comp = nonce.split(':') if len(comp) != 3: return False calc_nonce = _generate_nonce(comp[0], secret, comp[1]) if nonce == calc_nonce: return True return False def _generate_digest_challenge(ts, secret, realm, opaque, stale=False): nonce = _generate_nonce(ts, secret) return 'Digest %s' % (_format_kvpairs( realm=realm, qop='auth', nonce=nonce, opaque=opaque, algorithm='MD5', stale='true' if stale else 'false' ),) def _add_www_authenticate(request, secret, realm): resp = request.response if not resp.www_authenticate: resp.www_authenticate = _generate_digest_challenge( round(time.time()), secret, realm, 'NPDIGEST' ) def _parse_authorization(request, secret, realm): authz = request.authorization if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'): _add_www_authenticate(request, secret, realm) return None params = authz[1] if 'algorithm' not in params: params['algorithm'] = 'MD5' for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'): if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')): _add_www_authenticate(request, secret, realm) return None return params @implementer(IAuthenticationPolicy) class DigestAuthenticationPolicy(object): def __init__(self, secret, callback, realm='Realm'): self.secret = secret self.callback = callback self.realm = realm def authenticated_userid(self, request): params = _parse_authorization(request, self.secret, self.realm) if params is None: return None if not _is_valid_nonce(params['nonce'], self.secret): _add_www_authenticate(request, self.secret, self.realm) return None userid = params['username'] if self.callback(params, request) is not None: return 'u:%s' % userid _add_www_authenticate(request, self.secret, self.realm) def unauthenticated_userid(self, request): params = _parse_authorization(request, self.secret, self.realm) if params is None: return None if not _is_valid_nonce(params['nonce'], self.secret): _add_www_authenticate(request, self.secret, self.realm) return None return 'u:%s' % params['username'] def effective_principals(self, request): creds = [Everyone] params = _parse_authorization(request, self.secret, self.realm) if params is None: return creds if not _is_valid_nonce(params['nonce'], self.secret): _add_www_authenticate(request, self.secret, self.realm) return creds groups = self.callback(params, request) if groups is None: return creds creds.append(Authenticated) creds.append('u:%s' % params['username']) creds.extend(groups) return creds def remember(self, request, principal, *kw): return [] def forget(self, request): return [('WWW-Authenticate', _generate_digest_challenge( round(time.time()), self.secret, self.realm, 'NPDIGEST' ))]
annndrey/npui-unik
netprofile/netprofile/common/auth.py
Python
agpl-3.0
6,265
<?php namespace Drupal\effective_activism\AccessControlHandler; use Drupal; use Drupal\Core\Access\AccessResult; use Drupal\Core\Entity\EntityAccessControlHandler; use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Session\AccountInterface; /** * Access controller for the Event entity. * * @see \Drupal\effective_activism\Entity\Event. */ class EventAccessControlHandler extends EntityAccessControlHandler { /** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { switch ($operation) { case 'view': if (!$entity->isPublished()) { return AccessControl::isManager($entity->get('parent')->entity->get('organization')->entity, $account); } else { return AccessControl::isStaff($entity->get('parent')->entity->get('organization')->entity, $account); } case 'update': return AccessControl::isGroupStaff([$entity->get('parent')->entity], $account); case 'delete': return AccessControl::isManager($entity->get('parent')->entity->get('organization')->entity, $account); } // Unknown operation, no opinion. return AccessResult::neutral(); } /** * {@inheritdoc} */ protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) { return AccessControl::isGroupStaff([Drupal::request()->get('group')], $account); } }
EffectiveActivism/effective_activism
src/AccessControlHandler/EventAccessControlHandler.php
PHP
agpl-3.0
1,456
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.actions; import com.rapidminer.RapidMiner; import com.rapidminer.core.license.ProductConstraintManager; import com.rapidminer.gui.MainFrame; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.dialogs.AboutBox; import java.awt.event.ActionEvent; /** * The type About action. * * @author Simon Fischer */ public class AboutAction extends ResourceAction { private static final long serialVersionUID = 1L; private MainFrame mainFrame; /** * Instantiates a new About action. * * @param mainFrame the main frame */ public AboutAction(MainFrame mainFrame) { super("about"); this.mainFrame = mainFrame; setCondition(EDIT_IN_PROGRESS, DONT_CARE); } @Override public void actionPerformed(ActionEvent e) { new AboutBox(mainFrame, RapidMiner.getLongVersion(), ProductConstraintManager.INSTANCE.getActiveLicense()) .setVisible(true); } }
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/gui/actions/AboutAction.java
Java
agpl-3.0
1,819
class CreateVersions < ActiveRecord::Migration def self.up create_table :versions do |t| t.string :item_type, :null => false t.integer :item_id, :null => false t.string :event, :null => false t.string :whodunnit t.text :object t.datetime :created_at end add_index :versions, [:item_type, :item_id] create_table :blog_post_versions do |t| t.string :item_type, :null => false t.integer :item_id, :null => false t.string :event, :null => false t.string :whodunnit t.text :object t.datetime :created_at end add_index :blog_post_versions, [:item_type, :item_id] end def self.down drop_table :blog_post_versions drop_table :versions end end
xdite/Airesis
db/migrate/20131202101922_create_versions.rb
Ruby
agpl-3.0
783
(function() { 'use strict'; angular.module('columbyApp') .controller('SearchCtrl', function($log,$rootScope, $scope, SearchSrv) { /* ---------- SETUP ----------------------------------------------------------------------------- */ $scope.contentLoading = true; $scope.search = {}; $rootScope.title = 'columby.com | search'; $scope.pagination = { itemsPerPage: 20, datasets:{ currentPage: 1 }, accounts:{ currentPage: 1 }, tags:{ currentPage: 1 } }; /* ---------- SCOPE FUNCTIONS ------------------------------------------------------------------- */ $scope.doSearch = function(){ $scope.search.hits = null; if ($scope.search.searchTerm.length>2){ $scope.search.message = 'Searching for: ' + $scope.search.searchTerm; SearchSrv.query({ text: $scope.search.searchTerm, limit: $scope.pagination.itemsPerPage }).then(function (response) { $scope.search.hits = response; $scope.search.message = null; $scope.pagination.datasets.numPages = response.datasets.count / $scope.pagination.itemsPerPage; $scope.pagination.accounts.numPages = response.accounts.count / $scope.pagination.itemsPerPage; $scope.pagination.tags.numPages = response.tags.count / $scope.pagination.itemsPerPage; }, function(err){ $scope.search.message = 'Error: ' + err.data.message; }); } else { $scope.search.message = 'Type at least 3 characters.'; } }; /* ---------- INIT ---------------------------------------------------------------------------- */ if ($rootScope.searchTerm){ $scope.search.searchTerm = $rootScope.searchTerm; $log.debug($scope.search.searchTerm); delete $rootScope.searchTerm; $log.debug($scope.search.searchTerm); $scope.doSearch(); } }); })();
columby/www.columby.com
src/www/app/controllers/search/search.controller.js
JavaScript
agpl-3.0
1,953
QuestionCuePoint cuePoint = new QuestionCuePoint(); cuePoint.EntryId = "0_mej0it92"; cuePoint.Question = "hello world"; OnCompletedHandler<CuePoint> handler = new OnCompletedHandler<CuePoint>( (CuePoint result, Exception e) => { CodeExample.PrintObject(result); done = true; }); CuePointService.Add(cuePoint) .SetCompletion(handler) .Execute(client);
kaltura/developer-platform
test/golden/add_question_cuepoint/csharp.cs
C#
agpl-3.0
391
from . import models from . import lroe
factorlibre/l10n-spain
l10n_es_ticketbai_api_batuz/__init__.py
Python
agpl-3.0
40
/** * Copyright (c) 2011-2018 libgroestlcoin developers (see AUTHORS) * * This file is part of libgroestlcoin. * * libgroestlcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <groestlcoin/groestlcoin/network/protocol.hpp> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <system_error> #include <boost/date_time.hpp> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <groestlcoin/groestlcoin/error.hpp> #include <groestlcoin/groestlcoin/network/authority.hpp> #include <groestlcoin/groestlcoin/network/hosts.hpp> #include <groestlcoin/groestlcoin/network/handshake.hpp> #include <groestlcoin/groestlcoin/network/seeder.hpp> #include <groestlcoin/groestlcoin/utility/logger.hpp> #include <groestlcoin/groestlcoin/utility/threadpool.hpp> namespace libgroestlcoin { namespace network { using std::placeholders::_1; using std::placeholders::_2; using boost::filesystem::path; using boost::format; using boost::posix_time::time_duration; using boost::posix_time::seconds; // Based on http://bitcoinstats.com/network/dns-servers #ifdef ENABLE_TESTNET const hosts::authority_list protocol::default_seeds = { { "testnet-seed.alexykot.me", 18333 }, { "testnet-seed.bitcoin.petertodd.org", 18333 }, { "testnet-seed.bluematt.me", 18333 }, { "testnet-seed.bitcoin.schildbach.de", 18333 } }; #else const hosts::authority_list protocol::default_seeds = { { "seed.bitnodes.io", 8333 }, { "seed.bitcoinstats.com", 8333 }, { "seed.bitcoin.sipa.be", 8333 }, { "dnsseed.bluematt.me", 8333 }, { "seed.bitcoin.jonasschnelli.ch", 8333 }, { "dnsseed.bitcoin.dashjr.org", 8333 } // Previously also included: // bitseed.xf2.org:8333 // archivum.info:8333 // progressbar.sk:8333 // faucet.bitcoin.st:8333 // bitcoin.securepayment.cc:8333 }; #endif const size_t protocol::default_max_outbound = 8; // TODO: parameterize for config access. const size_t watermark_connection_limit = 10; const time_duration watermark_reset_interval = seconds(1); protocol::protocol(threadpool& pool, hosts& peers, handshake& shake, network& net, const hosts::authority_list& seeds, uint16_t port, size_t max_outbound) : strand_(pool), host_pool_(peers), handshake_(shake), network_(net), max_outbound_(max_outbound), watermark_timer_(pool.service()), watermark_count_(0), listen_port_(port), channel_subscribe_(std::make_shared<channel_subscriber_type>(pool)), seeds_(seeds) { } void protocol::start(completion_handler handle_complete) { // handshake.start doesn't accept an error code so we prevent its // execution in case of start failure, using this lambda wrapper. const auto start_handshake = [this, handle_complete] (const std::error_code& ec) { if (ec) { handle_complete(ec); return; } strand_.wrap(&handshake::start, &handshake_, handle_complete)(); }; const auto run_protocol = strand_.wrap(&protocol::handle_start, this, _1, start_handshake); host_pool_.load( strand_.wrap(&protocol::fetch_count, this, _1, run_protocol)); } void protocol::handle_start(const std::error_code& ec, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure fetching height: " << ec.message(); handle_complete(ec); return; } // TODO: handle run startup failure. handle_complete(ec); run(); } void protocol::stop(completion_handler handle_complete) { host_pool_.save( strand_.wrap(&protocol::handle_stop, this, _1, handle_complete)); } void protocol::handle_stop(const std::error_code& ec, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure saving hosts file: " << ec.message(); handle_complete(ec); return; } channel_subscribe_->relay(error::service_stopped, nullptr); handle_complete(error::success); } void protocol::fetch_count(const std::error_code& ec, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure loading hosts file: " << ec.message(); handle_complete(ec); return; } host_pool_.fetch_count( strand_.wrap(&protocol::start_seeder, this, _1, _2, handle_complete)); } void protocol::start_seeder(const std::error_code& ec, size_t hosts_count, completion_handler handle_complete) { if (ec) { log_error(LOG_PROTOCOL) << "Failure checking existing hosts file: " << ec.message(); handle_complete(ec); return; } if (hosts_count == 0) { seeder_ = std::make_shared<seeder>(this, seeds_, handle_complete); seeder_->start(); return; } handle_complete(error::success); } std::string protocol::state_to_string(connect_state state) const { switch (state) { case connect_state::finding_peer: return "finding peer"; case connect_state::connecting: return "connecting to peer"; case connect_state::established: return "established connection"; case connect_state::stopped: return "stopped"; } // Unhandled state! BITCOIN_ASSERT(false); return ""; } void protocol::modify_slot(slot_index slot, connect_state state) { connect_states_[slot] = state; log_debug(LOG_PROTOCOL) << "Outbound connection on slot [" << slot << "] " << state_to_string(state) << "."; } void protocol::run() { strand_.queue( std::bind(&protocol::start_connecting, this)); if (listen_port_ == 0) return; // Unhandled startup failure condition. network_.listen(listen_port_, strand_.wrap(&protocol::handle_listen, this, _1, _2)); } void protocol::start_connecting() { // Initialize the connection slots. BITCOIN_ASSERT(connections_.empty()); BITCOIN_ASSERT(connect_states_.empty()); connect_states_.resize(max_outbound_); for (size_t slot = 0; slot < connect_states_.size(); ++slot) modify_slot(slot, connect_state::stopped); // Start the main outbound connect loop. start_stopped_connects(); start_watermark_reset_timer(); } void protocol::start_stopped_connects() { for (size_t slot = 0; slot < connect_states_.size(); ++slot) if (connect_states_[slot] == connect_state::stopped) try_connect_once(slot); } void protocol::try_connect_once(slot_index slot) { ++watermark_count_; if (watermark_count_ > watermark_connection_limit) return; BITCOIN_ASSERT(slot <= connect_states_.size()); BITCOIN_ASSERT(connect_states_[slot] == connect_state::stopped); // Begin connection flow: finding_peer -> connecting -> established. // Failures end with connect_state::stopped and loop back here again. modify_slot(slot, connect_state::finding_peer); host_pool_.fetch_address( strand_.wrap(&protocol::attempt_connect, this, _1, _2, slot)); } void protocol::start_watermark_reset_timer() { // This timer just loops continuously at fixed intervals // resetting the watermark_count_ variable and starting stopped slots. const auto reset_watermark = [this](const boost::system::error_code& ec) { if (ec) { if (ec != boost::asio::error::operation_aborted) log_error(LOG_PROTOCOL) << "Failure resetting watermark timer: " << ec.message(); BITCOIN_ASSERT(ec == boost::asio::error::operation_aborted); return; } if (watermark_count_ > watermark_connection_limit) log_debug(LOG_PROTOCOL) << "Resuming connection attempts."; // Perform the reset, reallowing connection attempts. watermark_count_ = 0; start_stopped_connects(); // Looping timer... start_watermark_reset_timer(); }; watermark_timer_.expires_from_now(watermark_reset_interval); watermark_timer_.async_wait(strand_.wrap(reset_watermark, _1)); } template <typename ConnectionList> bool already_connected(const network_address_type& address, const ConnectionList& connections) { for (const auto& connection: connections) if (connection.address.ip == address.ip && connection.address.port == address.port) return true; return false; } void protocol::attempt_connect(const std::error_code& ec, const network_address_type& address, slot_index slot) { BITCOIN_ASSERT(connect_states_[slot] == connect_state::finding_peer); modify_slot(slot, connect_state::connecting); if (ec) { log_error(LOG_PROTOCOL) << "Failure randomly selecting a peer address for slot [" << slot << "] " << ec.message(); return; } if (already_connected(address, connections_)) { log_debug(LOG_PROTOCOL) << "Already connected to selected peer [" << authority(address).to_string() << "]"; // Retry another connection, still in same strand. modify_slot(slot, connect_state::stopped); try_connect_once(slot); return; } log_debug(LOG_PROTOCOL) << "Connecting to peer [" << authority(address).to_string() << "] on slot [" << slot << "]"; const authority peer(address); connect(handshake_, network_, peer.host, peer.port, strand_.wrap(&protocol::handle_connect, this, _1, _2, address, slot)); } void protocol::handle_connect(const std::error_code& ec, channel_ptr node, const network_address_type& address, slot_index slot) { BITCOIN_ASSERT(connect_states_[slot] == connect_state::connecting); if (ec || !node) { log_debug(LOG_PROTOCOL) << "Failure connecting to peer [" << authority(address).to_string() << "] on slot [" << slot << "] " << ec.message(); // Retry another connection, still in same strand. modify_slot(slot, connect_state::stopped); try_connect_once(slot); return; } modify_slot(slot, connect_state::established); BITCOIN_ASSERT(connections_.size() <= max_outbound_); connections_.push_back({address, node}); log_info(LOG_PROTOCOL) << "Connected to peer [" << authority(address).to_string() << "] on slot [" << slot << "] (" << connections_.size() << " total)"; // Remove channel from list of connections node->subscribe_stop( strand_.wrap(&protocol::outbound_channel_stopped, this, _1, node, slot)); setup_new_channel(node); } void protocol::maintain_connection(const std::string& hostname, uint16_t port) { connect(handshake_, network_, hostname, port, strand_.wrap(&protocol::handle_manual_connect, this, _1, _2, hostname, port)); } void protocol::handle_manual_connect(const std::error_code& ec, channel_ptr node, const std::string& hostname, uint16_t port) { if (ec || !node) { log_debug(LOG_PROTOCOL) << "Failure connecting manually to peer [" << authority(hostname, port).to_string() << "] " << ec.message(); // Retry connect. maintain_connection(hostname, port); return; } manual_connections_.push_back(node); // Connected! log_info(LOG_PROTOCOL) << "Connection to peer established manually [" << authority(hostname, port).to_string() << "]"; // Subscript to channel stop notifications. node->subscribe_stop( strand_.wrap(&protocol::manual_channel_stopped, this, _1, node, hostname, port)); setup_new_channel(node); } void protocol::handle_listen(const std::error_code& ec, acceptor_ptr accept) { if (!accept) return; if (ec) { log_error(LOG_PROTOCOL) << "Error while starting listener: " << ec.message(); return; } // Listen for connections. accept->accept( strand_.wrap(&protocol::handle_accept, this, _1, _2, accept)); } void protocol::handle_accept(const std::error_code& ec, channel_ptr node, acceptor_ptr accept) { if (!accept) return; // Relisten for connections. accept->accept( strand_.wrap(&protocol::handle_accept, this, _1, _2, accept)); if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Failure accepting connection from [" << node->address().to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Failure accepting connection: " << ec.message(); return; } accepted_channels_.push_back(node); log_info(LOG_PROTOCOL) << "Accepted connection from [" << node->address().to_string() << "] (" << accepted_channels_.size() << " total)"; const auto handshake_complete = [this, node](const std::error_code& ec) { if (!node) return; if (ec) { log_debug(LOG_PROTOCOL) << "Failure in handshake from [" << node->address().to_string() << "] " << ec.message(); return; } // Remove channel from list of connections node->subscribe_stop( strand_.wrap(&protocol::inbound_channel_stopped, this, _1, node)); setup_new_channel(node); }; handshake_.ready(node, handshake_complete); } void protocol::setup_new_channel(channel_ptr node) { if (!node) return; const auto handle_send = [node](const std::error_code& ec) { if (!node) return; if (ec) { log_debug(LOG_PROTOCOL) << "Send error [" << node->address().to_string() << "] " << ec.message(); } }; // Subscribe to address messages. node->subscribe_address( strand_.wrap(&protocol::handle_address_message, this, _1, _2, node)); node->send(get_address_type(), handle_send); // Notify subscribers channel_subscribe_->relay(error::success, node); } template <typename ConnectionsList> void remove_connection(ConnectionsList& connections, channel_ptr node) { auto it = connections.begin(); for (; it != connections.end(); ++it) if (it->node == node) break; BITCOIN_ASSERT(it != connections.end()); connections.erase(it); } void protocol::outbound_channel_stopped(const std::error_code& ec, channel_ptr node, slot_index slot) { // We must always attempt a reconnection. if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Channel stopped (outbound) [" << node->address().to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Channel stopped (outbound): " << ec.message(); } // Erase this channel from our list and then attempt a reconnection. remove_connection(connections_, node); BITCOIN_ASSERT(connect_states_[slot] == connect_state::established); modify_slot(slot, connect_state::stopped); // Attempt reconnection. try_connect_once(slot); } template <typename ChannelsList> void remove_channel(ChannelsList& channels, channel_ptr node) { const auto it = std::find(channels.begin(), channels.end(), node); BITCOIN_ASSERT(it != channels.end()); channels.erase(it); } void protocol::manual_channel_stopped(const std::error_code& ec, channel_ptr node, const std::string& hostname, uint16_t port) { // We must always attempt a reconnection. if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Channel stopped (manual) [" << authority(hostname, port).to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Channel stopped (manual): " << ec.message(); } // Remove from accepted connections. // Timeout logic would go here if we ever need it. remove_channel(manual_connections_, node); // Attempt reconnection. maintain_connection(hostname, port); } void protocol::inbound_channel_stopped(const std::error_code& ec, channel_ptr node) { // We do not attempt to reconnect inbound connections. if (ec) { if (node) log_debug(LOG_PROTOCOL) << "Channel stopped (inbound) [" << node->address().to_string() << "] " << ec.message(); else log_debug(LOG_PROTOCOL) << "Channel stopped (inbound): " << ec.message(); } // Remove from accepted connections (no reconnect). remove_channel(accepted_channels_, node); } void protocol::handle_address_message(const std::error_code& ec, const address_type& packet, channel_ptr node) { if (!node) return; if (ec) { // TODO: reset the connection. log_debug(LOG_PROTOCOL) << "Failure getting addresses from [" << node->address().to_string() << "] " << ec.message(); return; } log_debug(LOG_PROTOCOL) << "Storing addresses from [" << node->address().to_string() << "]"; for (const auto& net_address: packet.addresses) host_pool_.store(net_address, strand_.wrap(&protocol::handle_store_address, this, _1)); // Subscribe to address messages. node->subscribe_address( strand_.wrap(&protocol::handle_address_message, this, _1, _2, node)); } void protocol::handle_store_address(const std::error_code& ec) { if (ec) log_error(LOG_PROTOCOL) << "Failed to store address: " << ec.message(); } void protocol::fetch_connection_count( fetch_connection_count_handler handle_fetch) { strand_.queue( std::bind(&protocol::do_fetch_connection_count, this, handle_fetch)); } void protocol::do_fetch_connection_count( fetch_connection_count_handler handle_fetch) { handle_fetch(error::success, connections_.size()); } void protocol::subscribe_channel(channel_handler handle_channel) { channel_subscribe_->subscribe(handle_channel); } size_t protocol::total_connections() const { return connections_.size() + manual_connections_.size() + accepted_channels_.size(); } void protocol::set_max_outbound(size_t max_outbound) { max_outbound_ = max_outbound; } void protocol::set_hosts_filename(const std::string& hosts_path) { host_pool_.file_path_ = hosts_path; } // Deprecated, this is problematic because there is no enabler. void protocol::disable_listener() { listen_port_ = 0; } // Deprecated, should be private. void protocol::bootstrap(completion_handler handle_complete) { } } // namespace network } // namespace libgroestlcoin
GroestlCoin/libgroestlcoin
src/network/protocol.cpp
C++
agpl-3.0
19,757
/* * PHEX - The pure-java Gnutella-servent. * Copyright (C) 2001 - 2006 Arne Babenhauserheide ( arne_bab <at> web <dot> 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 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 * * Created on 08.02.2005 * --- CVS Information --- * $Id: RSSParser.java 3682 2007-01-09 15:32:14Z gregork $ */ package phex.util; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RSSParser { /** This Class reads out RSS-files passed to it and * collects them in the array "magnets[]". * Check the usage in phex.gui.dialogs.NewDowloadDialog */ /** * List of possible EOL characters, not exactly according to YAML 4.1.4 */ private static final String EOL_CHARACTERS = "\r\n"; private static final char[] AMPERSAND_AMP = new char[] {'a', 'm', 'p', ';'}; private static final String START_OF_ELEMENT_CHAR = "<"; private static final String END_OF_ELEMENT_CHAR = ">"; private static final String END_OF_ELEMENT_CHARN = "/"; private static final char[] XML_LINE = new char[] {'<', '?', 'x', 'm', 'l'}; private static final char[] MAGNET_PREFIX = new char[] {'m', 'a', 'g', 'n', 'e', 't'}; private static final char[] HTTP_PREFIX = new char[] {'h', 't', 't', 'p', ':', '/'}; private static final char[] MAGNET_TAG = new char[] {'<', 'm', 'a', 'g', 'n', 'e', 't', '>'}; private static final char[] ENCLOSURE_TAG_START = new char[] {'<', 'e', 'n', 'c', 'l', 'o', 's', 'u'}; private static final char[] ENCLOSURE_TAG_MID = new char[] {'r', 'e'}; private static final char[] URL_IDENTIFIER = new char[] {'u', 'r', 'l', '=', '"'}; //" private static final char[] ITEM_ELEMENT = new char[] {'<', 'i', 't', 'e', 'm', '>',}; private static final char[] END_OF_ITEM_ELEMENT = new char[] {'<', '/', 'i', 't', 'e', 'm', '>',}; private static final char[] RSS_TAG = new char[] {'<', 'r', 's', 's', '>',}; private static final char[] END_OF_RSS_TAG = new char[] {'<', '/', 'r', 's', 's', '>',}; private final PushbackReader reader; private final List<String> magnets; public RSSParser(Reader reader) { magnets = new ArrayList<String>(); this.reader = new PushbackReader(reader, 6); } public void start() throws IOException { try { /* The FileReader checks, if the File begins with "#MAGMA" * and sends the characters following the "#MAGMA" to the * listFinder. */ char buff[] = new char[5]; int readBytes = 0; while (readBytes != 5) { int count = reader.read(buff, readBytes, 5); if (count == -1) { throw new IOException("Input file is no XML-File (" + String.valueOf(buff) + ")."); } readBytes += count; } if (Arrays.equals(buff, XML_LINE)) { parseXml(); } } finally { reader.close(); } } public List getMagnets() { // Can be called to get the included magnets return magnets; } private void parseXml() throws IOException { int pos = 0; int c; while (true) { c = reader.read(); if (c == RSS_TAG[pos]) { pos++; if (pos == RSS_TAG.length) { // found rss-tag.. find the first item. parseList(); pos = 0; } } else if (c == -1) { // reached the end... return; } else {// next char of rss tag not found... skip line... pos = 0; //skipToEndOfObject(); parseList(); // ignore that this is careless } } } private void parseList() throws IOException { int pos = 0; int c; while (true) { c = reader.read(); if (c == ITEM_ELEMENT[pos]) { pos++; if (pos == ITEM_ELEMENT.length) { // found list: element.. skip line and continue to parse body. parseItemBody(); pos = 0; } } else if (c == END_OF_RSS_TAG[pos]) { pos++; if (pos == END_OF_RSS_TAG.length) { // RSS_TAG ended. pos = 0; return; } } else if (c == -1) { // reached the end... return; } else {// next char of list element not found... skip line... pos = 0; } } } public void parseItemBody() throws IOException { int c; int pos = 0; while (true) { c = reader.read(); if (c == MAGNET_TAG[pos]) { pos++; if (pos == MAGNET_TAG.length) { // we found a magnet-element // pre check if this really is a magnet.. char buff[] = new char[6]; int readBytes = 0; while (readBytes != 6) { int count = reader.read(buff, readBytes, 6); if (count == -1) { return; } readBytes += count; } reader.unread(buff); if (Arrays.equals(buff, MAGNET_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); } else if (Arrays.equals(buff, HTTP_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); } else { // skip to the end of this magnet-tag, // it doesn't contain a magnet nor a http-uri. } pos = 0; } } /** * Code to read out enclosures with * http- or magnet-uris doesn't work yet. */ else if (c == ENCLOSURE_TAG_START[pos]) { pos++; if (pos == ENCLOSURE_TAG_START.length) { // we found an enclosure-tag // pre check if this contains a magnet or http-url.. pos = 0; while (true) { c = reader.read(); //go forward up to the end of the URL-identifier. if (c == URL_IDENTIFIER[pos]) { pos++; if (pos == URL_IDENTIFIER.length) { //this containis an url-identifier. // check for magnet or http-start. char buff[] = new char[6]; int readBytes = 0; while (readBytes != 6) { int count = reader.read(buff, readBytes, 6); if (count == -1) { return; } readBytes += count; } reader.unread(buff); if (Arrays.equals(buff, MAGNET_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); break; } else if (Arrays.equals(buff, HTTP_PREFIX)) { // reached quoted http-url pos = 0; parseMagnet(); break; } } } else if (END_OF_ELEMENT_CHAR.indexOf(c) != -1) { //return if we reached the end of the enclosure. pos = 0; break; } else if (c == -1) { pos = 0; return; } else { pos = 0; } } // end of inner while (true) } else // pos != ENCLOSURE_TAG_START.length { // next letter } } else if (c == -1) { // reached the EOF pos = 0; return; } /** * Commented it out, because it creaded an Array Out of Bounds error * ToDo: Catch the Error and read out the titles of the items to use them along the magnets. * ToDo: Read out the content of the rss-items, so they can be shown alongside the magnet in the list (best in a tooltip). */ else if (pos <= 6 && c == END_OF_ITEM_ELEMENT[pos]) { pos++; if (pos == END_OF_ITEM_ELEMENT.length) { // the item ended. pos = 0; return; } } /* **/ else { pos = 0; // didn't continue as magnet or enclosure tag, reset pos. } } //end of of while-loop } public void parseMagnet() throws IOException { StringBuffer magnetBuf = new StringBuffer(); int c; while (true) { c = reader.read(); if (c == ' ' || EOL_CHARACTERS.indexOf(c) != -1) {// skip all line folding characters.. and all spaces continue; } else if (c == '<') {// found the end of the magnet. break; } /** * only necessary when we are able to read out enclosures. */ else if (c == '"') //" { // found the end of the magnet. break; } else if (c == -1) { // unexpected end... return; } else if (c == '&') { char buff[] = new char[4]; int readBytes = 0; while (readBytes != 4) { int count = reader.read(buff, readBytes, 4); if (count == -1) { return; } readBytes += count; } if (Arrays.equals(buff, AMPERSAND_AMP)) { // reached quoted magnet magnetBuf.append('&'); } else { reader.unread(buff); magnetBuf.append((char) c); } } else { magnetBuf.append((char) c); } } magnets.add(magnetBuf.toString()); } /** * Skips all content till end of line. */ private void skipToEndOfObject() throws IOException { // Only gets the next ending of any object. Could be improved to get // the end of a specific object supplied by the calling funktion. // At the moment ends either with "/>" or with "</" int c; while (true) { c = reader.read(); if (c < 0) {// stream ended... a valid line could not be read... return return; } else if (START_OF_ELEMENT_CHAR.indexOf(c) != -1) {// we found a possble end o the object... check if there are followups c = reader.read(); if (END_OF_ELEMENT_CHARN.indexOf(c) != -1) { return; } else { // the last character was no End of Element char... push it back reader.unread(c); } } else if (END_OF_ELEMENT_CHARN.indexOf(c) != -1) {// we found a possble end o the object... check if there are followups c = reader.read(); if (END_OF_ELEMENT_CHAR.indexOf(c) != -1) { return; } else { // the last character was no End of Element char... push it back reader.unread(c); } } } } }
deepstupid/phex
src/main/java/phex/util/RSSParser.java
Java
agpl-3.0
13,551
<?php /* Smarty version 2.6.11, created on 2012-09-04 14:40:06 compiled from cache/modules/Accounts/EditView.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_include', 'cache/modules/Accounts/EditView.tpl', 39, false),array('function', 'counter', 'cache/modules/Accounts/EditView.tpl', 45, false),array('function', 'sugar_translate', 'cache/modules/Accounts/EditView.tpl', 49, false),array('function', 'sugar_getjspath', 'cache/modules/Accounts/EditView.tpl', 150, false),array('function', 'html_options', 'cache/modules/Accounts/EditView.tpl', 389, false),array('function', 'sugar_getimagepath', 'cache/modules/Accounts/EditView.tpl', 417, false),array('modifier', 'default', 'cache/modules/Accounts/EditView.tpl', 46, false),array('modifier', 'strip_semicolon', 'cache/modules/Accounts/EditView.tpl', 57, false),array('modifier', 'lookup', 'cache/modules/Accounts/EditView.tpl', 414, false),array('modifier', 'count', 'cache/modules/Accounts/EditView.tpl', 494, false),)), $this); ?> <div class="clear"></div> <form action="index.php" method="POST" name="<?php echo $this->_tpl_vars['form_name']; ?> " id="<?php echo $this->_tpl_vars['form_id']; ?> " <?php echo $this->_tpl_vars['enctype']; ?> > <table width="100%" cellpadding="0" cellspacing="0" border="0" class="dcQuickEdit"> <tr> <td class="buttons"> <input type="hidden" name="module" value="<?php echo $this->_tpl_vars['module']; ?> "> <?php if (isset ( $_REQUEST['isDuplicate'] ) && $_REQUEST['isDuplicate'] == 'true'): ?> <input type="hidden" name="record" value=""> <input type="hidden" name="duplicateSave" value="true"> <input type="hidden" name="duplicateId" value="<?php echo $this->_tpl_vars['fields']['id']['value']; ?> "> <?php else: ?> <input type="hidden" name="record" value="<?php echo $this->_tpl_vars['fields']['id']['value']; ?> "> <?php endif; ?> <input type="hidden" name="isDuplicate" value="false"> <input type="hidden" name="action"> <input type="hidden" name="return_module" value="<?php echo $_REQUEST['return_module']; ?> "> <input type="hidden" name="return_action" value="<?php echo $_REQUEST['return_action']; ?> "> <input type="hidden" name="return_id" value="<?php echo $_REQUEST['return_id']; ?> "> <input type="hidden" name="module_tab"> <input type="hidden" name="contact_role"> <?php if (! empty ( $_REQUEST['return_module'] ) || ! empty ( $_REQUEST['relate_to'] )): ?> <input type="hidden" name="relate_to" value="<?php if ($_REQUEST['return_relationship']): echo $_REQUEST['return_relationship']; elseif ($_REQUEST['relate_to'] && empty ( $_REQUEST['from_dcmenu'] )): echo $_REQUEST['relate_to']; elseif (empty ( $this->_tpl_vars['isDCForm'] ) && empty ( $_REQUEST['from_dcmenu'] )): echo $_REQUEST['return_module']; endif; ?>"> <input type="hidden" name="relate_id" value="<?php echo $_REQUEST['return_id']; ?> "> <?php endif; ?> <input type="hidden" name="offset" value="<?php echo $this->_tpl_vars['offset']; ?> "> <input type="submit" id="SAVE" value="Save" name="button" title="Save" accessKey="a" class="button primary" onclick="this.form.action.value='Save'; saveClickCheckPrimary(); if(check_form('EditView'))SUGAR.ajaxUI.submitForm(this.form);return false; " value="Save" > <?php if (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $_REQUEST['return_id'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " type="button" id="CANCEL"> <?php elseif (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $this->_tpl_vars['fields']['id']['value'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php elseif (empty ( $_REQUEST['return_action'] ) || empty ( $_REQUEST['return_id'] ) && ! empty ( $this->_tpl_vars['fields']['id']['value'] )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=Accounts'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php else: ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php endif; if ($this->_tpl_vars['bean']->aclAccess('detail')): if (! empty ( $this->_tpl_vars['fields']['id']['value'] ) && $this->_tpl_vars['isAuditEnabled']): ?><input id="btn_view_change_log" title="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> " class="button" onclick='open_popup("Audit", "600", "400", "&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> &module_name=Accounts", true, false, { "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] } ); return false;' type="button" value="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> "><?php endif; endif; ?> </td> <td align='right'> <?php echo $this->_tpl_vars['PAGINATION']; ?> </td> </tr> </table><?php echo smarty_function_sugar_include(array('include' => $this->_tpl_vars['includes']), $this);?> <span id='tabcounterJS'><script>SUGAR.TabFields=new Array();//this will be used to track tabindexes for references</script></span> <div id="EditView_tabs" > <div > <div id="LBL_ACCOUNT_INFORMATION"> <?php echo smarty_function_counter(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?> <table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : smarty_modifier_default($_tmp, 'edit view dcQuickEdit edit508')); ?> "> <tr> <th align="left" colspan="8"> <h4><?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCOUNT_INFORMATION','module' => 'Accounts'), $this);?> </h4> </th> </tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='first_name_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_FIRST_NAME','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="first_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> <span class="required">*</span> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['first_name']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['first_name']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['first_name']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['first_name']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['first_name']['name']; ?> ' size='30' maxlength='15' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' accesskey='7' > <td valign="top" id='LBL_FIRST_NAME_label' width='12.5%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <td valign="top" id='_label' width='%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='%' > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='last_name_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_LAST_NAME','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="last_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['last_name']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['last_name']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['last_name']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['last_name']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['last_name']['name']; ?> ' size='30' maxlength='15' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='website_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_WEBSITE','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="website"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (! empty ( $this->_tpl_vars['fields']['website']['value'] )): ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' size='30' maxlength='255' value='<?php echo $this->_tpl_vars['fields']['website']['value']; ?> ' title='' tabindex='0' > <?php else: ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['website']['name']; ?> ' size='30' maxlength='255' <?php if ($this->_tpl_vars['displayView'] == 'advanced_search' || $this->_tpl_vars['displayView'] == 'basic_search'): ?>value=''<?php else: ?>value='http://'<?php endif; ?> title='' tabindex='0' > <?php endif; ?> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='2'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <script type="text/javascript" src='<?php echo smarty_function_sugar_getjspath(array('file' => "include/SugarFields/Fields/Address/SugarFieldAddress.js"), $this);?> '></script> <fieldset id='BILLING_address_fieldset'> <legend><?php echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS','module' => ''), $this);?> </legend> <table border="0" cellspacing="1" cellpadding="0" class="edit" width="100%"> <tr> <td valign="top" id="billing_address_street_label" width='25%' scope='row' > <label for="billing_address_street"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_STREET','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_street']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td width="*"> <textarea id="billing_address_street" name="billing_address_street" maxlength="150" rows="2" cols="30" tabindex="0"><?php echo $this->_tpl_vars['fields']['billing_address_street']['value']; ?> </textarea> </td> </tr> <tr> <td id="billing_address_city_label" width='%' scope='row' > <label for="billing_address_city"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_CITY','module' => ''), $this);?> : <?php if ($this->_tpl_vars['fields']['billing_address_city']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_city" id="billing_address_city" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_city']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="billing_address_state_label" width='%' scope='row' > <label for="billing_address_state"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_STATE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_state']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_state" id="billing_address_state" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_state']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="billing_address_postalcode_label" width='%' scope='row' > <label for="billing_address_postalcode"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_POSTAL_CODE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_postalcode']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_postalcode" id="billing_address_postalcode" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_postalcode']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="billing_address_country_label" width='%' scope='row' > <label for="billing_address_country"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_COUNTRY','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['billing_address_country']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="billing_address_country" id="billing_address_country" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['billing_address_country']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td colspan='2' NOWRAP>&nbsp;</td> </tr> </table> </fieldset> <script type="text/javascript"> SUGAR.util.doWhen("typeof(SUGAR.AddressField) != 'undefined'", function(){ billing_address = new SUGAR.AddressField("billing_checkbox",'', 'billing'); }); </script> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='2'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <script type="text/javascript" src='<?php echo smarty_function_sugar_getjspath(array('file' => "include/SugarFields/Fields/Address/SugarFieldAddress.js"), $this);?> '></script> <fieldset id='SHIPPING_address_fieldset'> <legend><?php echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS','module' => ''), $this);?> </legend> <table border="0" cellspacing="1" cellpadding="0" class="edit" width="100%"> <tr> <td valign="top" id="shipping_address_street_label" width='25%' scope='row' > <label for="shipping_address_street"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_STREET','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_street']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td width="*"> <textarea id="shipping_address_street" name="shipping_address_street" maxlength="150" rows="2" cols="30" tabindex="0"><?php echo $this->_tpl_vars['fields']['shipping_address_street']['value']; ?> </textarea> </td> </tr> <tr> <td id="shipping_address_city_label" width='%' scope='row' > <label for="shipping_address_city"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_CITY','module' => ''), $this);?> : <?php if ($this->_tpl_vars['fields']['shipping_address_city']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_city" id="shipping_address_city" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_city']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="shipping_address_state_label" width='%' scope='row' > <label for="shipping_address_state"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_STATE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_state']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_state" id="shipping_address_state" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_state']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="shipping_address_postalcode_label" width='%' scope='row' > <label for="shipping_address_postalcode"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_POSTAL_CODE','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_postalcode']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_postalcode" id="shipping_address_postalcode" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_postalcode']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td id="shipping_address_country_label" width='%' scope='row' > <label for="shipping_address_country"><?php echo smarty_function_sugar_translate(array('label' => 'LBL_COUNTRY','module' => ''), $this);?> :</label> <?php if ($this->_tpl_vars['fields']['shipping_address_country']['required'] || false): ?> <span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?> </span> <?php endif; ?> </td> <td> <input type="text" name="shipping_address_country" id="shipping_address_country" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['shipping_address_country']['value']; ?> ' tabindex="0"> </td> </tr> <tr> <td scope='row' NOWRAP> <?php echo smarty_function_sugar_translate(array('label' => 'LBL_COPY_ADDRESS_FROM_LEFT','module' => ''), $this);?> : </td> <td> <input id="shipping_checkbox" name="shipping_checkbox" type="checkbox" onclick="shipping_address.syncFields();"> </td> </tr> </table> </fieldset> <script type="text/javascript"> SUGAR.util.doWhen("typeof(SUGAR.AddressField) != 'undefined'", function(){ shipping_address = new SUGAR.AddressField("shipping_checkbox",'billing', 'shipping'); }); </script> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='email1_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_EMAIL','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="email1"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php echo $this->_tpl_vars['EMAIL']; ?> <td valign="top" id='phoneno_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_PHONENO','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for=""><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php echo $this->_tpl_vars['PHONENOS']; ?> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='description_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_DESCRIPTION','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="description"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (empty ( $this->_tpl_vars['fields']['description']['value'] )): $this->assign('value', $this->_tpl_vars['fields']['description']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['description']['value']); endif; ?> <textarea id='<?php echo $this->_tpl_vars['fields']['description']['name']; ?> ' name='<?php echo $this->_tpl_vars['fields']['description']['name']; ?> ' rows="6" cols="80" title='' tabindex="0" ><?php echo $this->_tpl_vars['value']; ?> </textarea> <td valign="top" id='phone_fax_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_FAX','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="phone_fax"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['phone_fax']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['phone_fax']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['phone_fax']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['phone_fax']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['phone_fax']['name']; ?> ' size='30' maxlength='100' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' tabindex='0' class="phone" > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='client_source_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_CLIENT_SOURCE','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="client_source"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (! isset ( $this->_tpl_vars['config']['enable_autocomplete'] ) || $this->_tpl_vars['config']['enable_autocomplete'] == false): ?> <select name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " title='' > <?php if (isset ( $this->_tpl_vars['fields']['client_source']['value'] ) && $this->_tpl_vars['fields']['client_source']['value'] != ''): echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['value']), $this);?> <?php else: echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['default']), $this);?> <?php endif; ?> </select> <?php else: $this->assign('field_options', $this->_tpl_vars['fields']['client_source']['options']); ob_start(); echo $this->_tpl_vars['fields']['client_source']['value']; $this->_smarty_vars['capture']['field_val'] = ob_get_contents(); ob_end_clean(); $this->assign('field_val', $this->_smarty_vars['capture']['field_val']); ob_start(); echo $this->_tpl_vars['fields']['client_source']['name']; $this->_smarty_vars['capture']['ac_key'] = ob_get_contents(); ob_end_clean(); $this->assign('ac_key', $this->_smarty_vars['capture']['ac_key']); ?> <select style='display:none' name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> " title='' > <?php if (isset ( $this->_tpl_vars['fields']['client_source']['value'] ) && $this->_tpl_vars['fields']['client_source']['value'] != ''): echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['value']), $this);?> <?php else: echo smarty_function_html_options(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['default']), $this);?> <?php endif; ?> </select> <input id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input" name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input" size="30" value="<?php echo ((is_array($_tmp=$this->_tpl_vars['field_val'])) ? $this->_run_mod_handler('lookup', true, $_tmp, $this->_tpl_vars['field_options']) : smarty_modifier_lookup($_tmp, $this->_tpl_vars['field_options'])); ?> " type="text" style="vertical-align: top;"> <span class="id-ff multiple"> <button type="button"><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-down.png"), $this);?> " id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -image"></button><button type="button" id="btn-clear-<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input" title="Clear" onclick="SUGAR.clearRelateField(this.form, '<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input', '<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> ');sync_<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> ()"><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-clear.png"), $this);?> "></button> </span> <?php echo ' <script> SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo ' = []; '; ?> <?php echo ' (function (){ var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); if (typeof select_defaults =="undefined") select_defaults = []; select_defaults[selectElem.id] = {key:selectElem.value,text:\'\'}; //get default for (i=0;i<selectElem.options.length;i++){ if (selectElem.options[i].value==selectElem.value) select_defaults[selectElem.id].text = selectElem.options[i].innerHTML; } //SUGAR.AutoComplete.{$ac_key}.ds = //get options array from vardefs var options = SUGAR.AutoComplete.getOptionsArray(""); YUI().use(\'datasource\', \'datasource-jsonschema\',function (Y) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.ds = new Y.DataSource.Function({ source: function (request) { var ret = []; for (i=0;i<selectElem.options.length;i++) if (!(selectElem.options[i].value==\'\' && selectElem.options[i].innerHTML==\'\')) ret.push({\'key\':selectElem.options[i].value,\'text\':selectElem.options[i].innerHTML}); return ret; } }); }); })(); '; ?> <?php echo ' YUI().use("autocomplete", "autocomplete-filters", "autocomplete-highlighters", "node","node-event-simulate", function (Y) { '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .inputNode = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input'); SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .inputImage = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> -image'); SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .inputHidden = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?> '); <?php echo ' function SyncToHidden(selectme){ var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); var doSimulateChange = false; if (selectElem.value!=selectme) doSimulateChange=true; selectElem.value=selectme; for (i=0;i<selectElem.options.length;i++){ selectElem.options[i].selected=false; if (selectElem.options[i].value==selectme) selectElem.options[i].selected=true; } if (doSimulateChange) SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'change\'); } //global variable sync_'; echo $this->_tpl_vars['fields']['client_source']['name']; echo ' = function(){ SyncToHidden(); } function syncFromHiddenToWidget(){ var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); //if select no longer on page, kill timer if (selectElem==null || selectElem.options == null) return; var currentvalue = SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.get(\'value\'); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.simulate(\'keyup\'); for (i=0;i<selectElem.options.length;i++){ if (selectElem.options[i].value==selectElem.value && document.activeElement != document.getElementById(\''; echo $this->_tpl_vars['fields']['client_source']['name']; ?> -input<?php echo '\')) SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.set(\'value\',selectElem.options[i].innerHTML); } } YAHOO.util.Event.onAvailable("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '", syncFromHiddenToWidget); '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen = 0; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay = 0; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .numOptions = <?php echo count($this->_tpl_vars['field_options']); ?> ; if(SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .numOptions >= 300) <?php echo '{ '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen = 1; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay = 200; <?php echo ' } '; ?> if(SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .numOptions >= 3000) <?php echo '{ '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen = 1; SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay = 500; <?php echo ' } '; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .optionsVisible = false; <?php echo ' SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.plug(Y.Plugin.AutoComplete, { activateFirstItem: true, '; ?> minQueryLength: SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen, queryDelay: SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .queryDelay, zIndex: 99999, <?php echo ' source: SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.ds, resultTextLocator: \'text\', resultHighlighter: \'phraseMatch\', resultFilters: \'phraseMatch\', }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.expandHover = function(ex){ var hover = YAHOO.util.Dom.getElementsByClassName(\'dccontent\'); if(hover[0] != null){ if (ex) { var h = \'1000px\'; hover[0].style.height = h; } else{ hover[0].style.height = \'\'; } } } if('; ?> SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?> .minQLen<?php echo ' == 0){ // expand the dropdown options upon focus SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'focus\', function () { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.sendRequest(\'\'); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible = true; }); } SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'click\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'click\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'dblclick\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'dblclick\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'focus\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'focus\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'mouseup\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'mouseup\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'mousedown\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'mousedown\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'blur\', function(e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'blur\'); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible = false; var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '"); //if typed value is a valid option, do nothing for (i=0;i<selectElem.options.length;i++) if (selectElem.options[i].innerHTML==SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.get(\'value\')) return; //typed value is invalid, so set the text and the hidden to blank SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.set(\'value\', select_defaults[selectElem.id].text); SyncToHidden(select_defaults[selectElem.id].key); }); // when they click on the arrow image, toggle the visibility of the options SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputImage.ancestor().on(\'click\', function () { if (SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.blur(); } else { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.focus(); } }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'query\', function () { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.set(\'value\', \'\'); }); SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'visibleChange\', function (e) { SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.expandHover(e.newVal); // expand }); // when they select an option, set the hidden input with the KEY, to be saved SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'select\', function(e) { SyncToHidden(e.result.raw.key); }); }); </script> '; ?> <?php endif; ?> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; ?> </table> </div> <?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?> <script>document.getElementById("LBL_ACCOUNT_INFORMATION").style.display='none';</script> <?php endif; ?> <div id="LBL_PANEL_PASSWORD"> <?php echo smarty_function_counter(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?> <table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : smarty_modifier_default($_tmp, 'edit view dcQuickEdit edit508')); ?> "> <tr> <th align="left" colspan="8"> <h4><?php echo smarty_function_sugar_translate(array('label' => 'LBL_PANEL_PASSWORD','module' => 'Accounts'), $this);?> </h4> </th> </tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='password_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_PASSWORD','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="password"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <?php if (strlen ( $this->_tpl_vars['fields']['password']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['password']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['password']['value']); endif; ?> <input type='text' name='<?php echo $this->_tpl_vars['fields']['password']['name']; ?> ' id='<?php echo $this->_tpl_vars['fields']['password']['name']; ?> ' size='30' maxlength='15' value='<?php echo $this->_tpl_vars['value']; ?> ' title='' > <td valign="top" id='LBL_PASSWORD_label' width='12.5%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' > <td valign="top" id='_label' width='%' scope="col"> &nbsp; </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='%' > </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; ?> </table> </div> <?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?> <script>document.getElementById("LBL_PANEL_PASSWORD").style.display='none';</script> <?php endif; ?> <div id="LBL_PANEL_ASSIGNMENT"> <?php echo smarty_function_counter(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?> <table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : smarty_modifier_default($_tmp, 'edit view dcQuickEdit edit508')); ?> "> <tr> <th align="left" colspan="8"> <h4><?php echo smarty_function_sugar_translate(array('label' => 'LBL_PANEL_ASSIGNMENT','module' => 'Accounts'), $this);?> </h4> </th> </tr> <?php echo smarty_function_counter(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?> <?php ob_start(); ?> <tr> <td valign="top" id='assigned_user_name_label' width='12.5%' scope="col"> <?php ob_start(); echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?> <label for="assigned_user_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : smarty_modifier_strip_semicolon($_tmp)); ?> :</label> </td> <?php echo smarty_function_counter(array('name' => 'fieldsUsed'), $this);?> <td valign="top" width='37.5%' colspan='3'> <?php echo smarty_function_counter(array('name' => 'panelFieldCount'), $this);?> <input type="text" name="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " class="sqsEnabled" tabindex="0" id="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " size="" value="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['value']; ?> " title='' autocomplete="off" > <input type="hidden" name="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?> " id="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?> " value="<?php echo $this->_tpl_vars['fields']['assigned_user_id']['value']; ?> "> <span class="id-ff multiple"> <button type="button" name="btn_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " id="btn_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " tabindex="0" title="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_SELECT_USERS_TITLE'), $this);?> " class="button firstChild" value="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_SELECT_USERS_LABEL'), $this);?> " onclick='open_popup( "<?php echo $this->_tpl_vars['fields']['assigned_user_name']['module']; ?> ", 600, 400, "", true, false, <?php echo '{"call_back_function":"set_return","form_name":"EditView","field_to_name_array":{"id":"assigned_user_id","user_name":"assigned_user_name"}}'; ?> , "single", true );' ><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-select.png"), $this);?> "></button><button type="button" name="btn_clr_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " id="btn_clr_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> " tabindex="0" title="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_CLEAR_USERS_TITLE'), $this);?> " class="button lastChild" onclick="SUGAR.clearRelateField(this.form, '<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> ', '<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?> ');" value="<?php echo smarty_function_sugar_translate(array('label' => 'LBL_ACCESSKEY_CLEAR_USERS_LABEL'), $this);?> " ><img src="<?php echo smarty_function_sugar_getimagepath(array('file' => "id-ff-clear.png"), $this);?> "></button> </span> <script type="text/javascript"> SUGAR.util.doWhen( "typeof(sqs_objects) != 'undefined' && typeof(sqs_objects['<?php echo $this->_tpl_vars['form_name']; ?> _<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?> ']) != 'undefined'", enableQS ); </script> </tr> <?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?> <?php endif; ?> </table> </div> <?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?> <script>document.getElementById("LBL_PANEL_ASSIGNMENT").style.display='none';</script> <?php endif; ?> </div></div> <div class="buttons"> <input type="submit" id="SAVE" value="Save" name="button" title="Save" accessKey="a" class="button primary" onclick="this.form.action.value='Save'; saveClickCheckPrimary(); if(check_form('EditView'))SUGAR.ajaxUI.submitForm(this.form);return false; " value="Save" > <?php if (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $_REQUEST['return_id'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " type="button" id="CANCEL"> <?php elseif (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $this->_tpl_vars['fields']['id']['value'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php elseif (empty ( $_REQUEST['return_action'] ) || empty ( $_REQUEST['return_id'] ) && ! empty ( $this->_tpl_vars['fields']['id']['value'] )): ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=Accounts'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php else: ?><input title="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_TITLE']; ?> " accessKey="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_KEY']; ?> " class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=<?php echo $_REQUEST['return_module']; ?> &record=<?php echo $_REQUEST['return_id']; ?> '); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['LBL_CANCEL_BUTTON_LABEL']; ?> " id="CANCEL"> <?php endif; if ($this->_tpl_vars['bean']->aclAccess('detail')): if (! empty ( $this->_tpl_vars['fields']['id']['value'] ) && $this->_tpl_vars['isAuditEnabled']): ?><input id="btn_view_change_log" title="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> " class="button" onclick='open_popup("Audit", "600", "400", "&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?> &module_name=Accounts", true, false, { "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] } ); return false;' type="button" value="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?> "><?php endif; endif; ?> </div> </form> <?php echo $this->_tpl_vars['set_focus_block']; ?> <script>SUGAR.util.doWhen("document.getElementById('EditView') != null", function(){SUGAR.util.buildAccessKeyLabels();}); </script><?php echo $this->_tpl_vars['overlibStuff']; ?> <script type="text/javascript"> YAHOO.util.Event.onContentReady("EditView", function () { initEditView(document.forms.EditView) }); //window.setTimeout(, 100); window.onbeforeunload = function () { return onUnloadEditView(); }; </script><?php echo ' <script type="text/javascript"> addForm(\'EditView\');addToValidate(\'EditView\', \'name\', \'name\', true,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'date_entered_date\', \'date\', false,\'Date Created\' ); addToValidate(\'EditView\', \'date_modified_date\', \'date\', false,\'Date Modified\' ); addToValidate(\'EditView\', \'modified_user_id\', \'assigned_user_name\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MODIFIED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'modified_by_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MODIFIED_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'created_by\', \'assigned_user_name\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CREATED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'created_by_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CREATED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'description\', \'text\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_DESCRIPTION','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'deleted\', \'bool\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_DELETED','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'assigned_user_id\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO_ID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'assigned_user_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'account_type\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_TYPE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'industry\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_INDUSTRY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'annual_revenue\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ANNUAL_REVENUE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'phone_fax\', \'phone\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_FAX','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street_2\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET_2','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street_3\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET_3','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_street_4\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STREET_4','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_city\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_CITY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_state\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_STATE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_postalcode\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_POSTALCODE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'billing_address_country\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_BILLING_ADDRESS_COUNTRY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'rating\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_RATING','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'phone_office\', \'phone\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PHONE_OFFICE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'phone_alternate\', \'phone\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PHONE_ALT','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'website\', \'url\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_WEBSITE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'ownership\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_OWNERSHIP','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'employees\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_EMPLOYEES','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'ticker_symbol\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_TICKER_SYMBOL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street_2\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET_2','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street_3\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET_3','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_street_4\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STREET_4','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_city\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_CITY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_state\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_STATE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_postalcode\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_POSTALCODE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'shipping_address_country\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SHIPPING_ADDRESS_COUNTRY','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'email1\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'accountfilter\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => '','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'viewasfilter\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => '','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'client_source\', \'enum\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CLIENT_SOURCE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'first_name\', \'varchar\', true,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_FIRST_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'call_time\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CALL_TIME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'last_name\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_LAST_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'parent_id\', \'id\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PARENT_ACCOUNT_ID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'sic_code\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_SIC_CODE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'parent_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MEMBER_OF','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'email_opt_out\', \'bool\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_EMAIL_OPT_OUT','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'invalid_email\', \'bool\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_INVALID_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'email\', \'email\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ANY_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'campaign_id\', \'id\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CAMPAIGN_ID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'campaign_name\', \'relate\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_CAMPAIGN','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'password\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_PASSWORD','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'zohoid\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_ZOHOID','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidate(\'EditView\', \'mobile\', \'varchar\', false,\''; echo smarty_function_sugar_translate(array('label' => 'LBL_MOBILE','module' => 'Accounts','for_js' => true), $this); echo '\' ); addToValidateBinaryDependency(\'EditView\', \'assigned_user_name\', \'alpha\', false,\''; echo smarty_function_sugar_translate(array('label' => 'ERR_SQS_NO_MATCH_FIELD','module' => 'Accounts','for_js' => true), $this); echo ': '; echo smarty_function_sugar_translate(array('label' => 'LBL_ASSIGNED_TO','module' => 'Accounts','for_js' => true), $this); echo '\', \'assigned_user_id\' ); </script><script language="javascript">if(typeof sqs_objects == \'undefined\'){var sqs_objects = new Array;}sqs_objects[\'EditView_assigned_user_name\']={"form":"EditView","method":"get_user_array","field_list":["user_name","id"],"populate_list":["assigned_user_name","assigned_user_id"],"required_list":["assigned_user_id"],"conditions":[{"name":"user_name","op":"like_custom","end":"%","value":""}],"limit":"30","no_match_text":"No Match"};</script>'; ?>
acuteventures/CRM
cache/smarty/templates_c/%%F7^F76^F763801C%%EditView.tpl.php
PHP
agpl-3.0
62,985
/* Copyright (C) 2016 Anki Universal Team <ankiuniversal@outlook.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace AnkiU.UserControls { public sealed partial class RichEditBoxContentDialog : ContentDialog { public string Text { get; set; } public RichEditBoxContentDialog(string text) { this.InitializeComponent(); richEditBox.Document.SetText(TextSetOptions.None, text); } private void OkButtonClickHandler(ContentDialog sender, ContentDialogButtonClickEventArgs args) { string text; richEditBox.Document.GetText(TextGetOptions.None, out text); Text = text; this.Hide(); } private void CancelButtonClickHandler(ContentDialog sender, ContentDialogButtonClickEventArgs args) { Text = null; this.Hide(); } } }
AnkiUniversal/Anki-Universal
AnkiU/UserControls/RichEditBoxContentDialog.xaml.cs
C#
agpl-3.0
1,960
package integration.tests; import static org.junit.Assert.assertEquals; import gr.ntua.vision.monitoring.VismoConfiguration; import gr.ntua.vision.monitoring.VismoVMInfo; import gr.ntua.vision.monitoring.dispatch.VismoEventDispatcher; import gr.ntua.vision.monitoring.events.MonitoringEvent; import gr.ntua.vision.monitoring.notify.VismoEventRegistry; import gr.ntua.vision.monitoring.rules.Rule; import gr.ntua.vision.monitoring.rules.VismoRulesEngine; import gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory; import gr.ntua.vision.monitoring.service.Service; import gr.ntua.vision.monitoring.service.VismoService; import gr.ntua.vision.monitoring.zmq.ZMQFactory; import java.io.IOException; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZContext; /** * This is used to test the general facilities of the {@link VismoService}; thus is should receive events from producers, process * them in a rules engine and dispatch them to consumers. */ public class VismoServiceTest { /** * This is used to count the number of events received. */ private final class EventCountRule extends Rule { /***/ private int counter = 0; /** * Constructor. * * @param engine */ public EventCountRule(final VismoRulesEngine engine) { super(engine); } /** * @param expectedNoEvents */ public void hasSeenExpectedNoEvents(final int expectedNoEvents) { assertEquals(expectedNoEvents, counter); } /** * @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object) */ @Override public void performWith(final MonitoringEvent e) { if (e != null) ++counter; } } /** the log target. */ private static final Logger log = LoggerFactory.getLogger(VismoServiceTest.class); /***/ private static final int NO_GET_OPS = 100; /***/ private static final int NO_PUT_OPS = 100; /***/ @SuppressWarnings("serial") private static final Properties p = new Properties() { { setProperty("cloud.name", "visioncloud.eu"); setProperty("cloud.heads", "10.0.2.211, 10.0.2.212"); setProperty("cluster.name", "vision-1"); setProperty("cluster.head", "10.0.2.211"); setProperty("producers.point", "tcp://127.0.0.1:56429"); setProperty("consumers.port", "56430"); setProperty("udp.port", "56431"); setProperty("cluster.head.port", "56432"); setProperty("cloud.head.port", "56433"); setProperty("mon.group.addr", "228.5.6.7"); setProperty("mon.group.port", "12345"); setProperty("mon.ping.period", "60000"); setProperty("startup.rules", "PassThroughRule"); setProperty("web.port", "9996"); } }; /***/ EventCountRule countRule; /***/ private final VismoConfiguration conf = new VismoConfiguration(p); /***/ private FakeObjectService obs; /** the object under test. */ private Service service; /** the socket factory. */ private final ZMQFactory socketFactory = new ZMQFactory(new ZContext()); /** * @throws IOException */ @Before public void setUp() throws IOException { obs = new FakeObjectService(new VismoEventDispatcher(socketFactory, conf, "fake-obs")); service = new ClusterHeadNodeFactory(conf, socketFactory) { @Override protected void submitRules(final VismoRulesEngine engine) { countRule = new EventCountRule(engine); countRule.submit(); super.submitRules(engine); } }.build(new VismoVMInfo()); } /***/ @After public void tearDown() { if (service != null) service.halt(); } /** * @throws InterruptedException */ @Test public void vismoDeliversEventsToClient() throws InterruptedException { final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort()); final CountDownLatch latch = new CountDownLatch(1); final ConsumerHandler consumer = new ConsumerHandler(latch, NO_GET_OPS + NO_PUT_OPS); service.start(); reg.registerToAll(consumer); final long start = System.currentTimeMillis(); doGETs(NO_GET_OPS); doPUTs(NO_PUT_OPS); log.debug("waiting event delivery..."); latch.await(10, TimeUnit.SECONDS); final double dur = (System.currentTimeMillis() - start) / 1000.0; log.debug("{} events delivered to client in {} sec ({} events/sec)", new Object[] { consumer.getNoReceivedEvents(), dur, consumer.getNoReceivedEvents() / dur }); consumerHasReceivedExpectedNoEvents(consumer, NO_GET_OPS + NO_PUT_OPS); } /** * @throws InterruptedException */ @Test public void vismoReceivesEventsFromProducers() throws InterruptedException { service.start(); doGETs(NO_GET_OPS); doPUTs(NO_PUT_OPS); waitForEventsDelivery(2000); assertThatVismoReceivedEvents(); } /***/ private void assertThatVismoReceivedEvents() { countRule.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS); } /** * @param noOps */ private void doGETs(final int noOps) { for (int i = 0; i < noOps; ++i) obs.getEvent("ntua", "bill", "foo-container", "bar-object").send(); } /** * @param noOps */ private void doPUTs(final int noOps) { for (int i = 0; i < noOps; ++i) obs.putEvent("ntua", "bill", "foo-container", "bar-object").send(); } /** * @param consumerHandler * @param expectedNoEvents */ private static void consumerHasReceivedExpectedNoEvents(final ConsumerHandler consumerHandler, final int expectedNoEvents) { assertEquals(expectedNoEvents, consumerHandler.getNoReceivedEvents()); } /** * @param n * @throws InterruptedException */ private static void waitForEventsDelivery(final int n) throws InterruptedException { Thread.sleep(n); } }
spyrosg/VISION-Cloud-Monitoring
vismo-core/src/test/java/integration/tests/VismoServiceTest.java
Java
agpl-3.0
7,451
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltdb.SystemProcedureCatalog.Config; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Procedure; import org.voltdb.compiler.Language; import org.voltdb.groovy.GroovyScriptProcedureDelegate; import org.voltdb.utils.LogKeys; import com.google_voltpatches.common.collect.ImmutableMap; public class LoadedProcedureSet { private static final VoltLogger hostLog = new VoltLogger("HOST"); // user procedures. ImmutableMap<String, ProcedureRunner> procs = ImmutableMap.<String, ProcedureRunner>builder().build(); // map of sysproc fragment ids to system procedures. final HashMap<Long, ProcedureRunner> m_registeredSysProcPlanFragments = new HashMap<Long, ProcedureRunner>(); final ProcedureRunnerFactory m_runnerFactory; final long m_siteId; final int m_siteIndex; final SiteProcedureConnection m_site; public LoadedProcedureSet(SiteProcedureConnection site, ProcedureRunnerFactory runnerFactory, long siteId, int siteIndex) { m_runnerFactory = runnerFactory; m_siteId = siteId; m_siteIndex = siteIndex; m_site = site; } public ProcedureRunner getSysproc(long fragmentId) { synchronized (m_registeredSysProcPlanFragments) { return m_registeredSysProcPlanFragments.get(fragmentId); } } public void registerPlanFragment(final long pfId, final ProcedureRunner proc) { synchronized (m_registeredSysProcPlanFragments) { assert(m_registeredSysProcPlanFragments.containsKey(pfId) == false); m_registeredSysProcPlanFragments.put(pfId, proc); } } public void loadProcedures( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp) { m_registeredSysProcPlanFragments.clear(); ImmutableMap.Builder<String, ProcedureRunner> builder = loadProceduresFromCatalog(catalogContext, backendTarget, csp); loadSystemProcedures(catalogContext, backendTarget, csp, builder); procs = builder.build(); } private ImmutableMap.Builder<String, ProcedureRunner> loadProceduresFromCatalog( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp) { // load up all the stored procedures final CatalogMap<Procedure> catalogProcedures = catalogContext.database.getProcedures(); ImmutableMap.Builder<String, ProcedureRunner> builder = ImmutableMap.<String, ProcedureRunner>builder(); for (final Procedure proc : catalogProcedures) { // Sysprocs used to be in the catalog. Now they aren't. Ignore // sysprocs found in old catalog versions. (PRO-365) if (proc.getTypeName().startsWith("@")) { continue; } ProcedureRunner runner = null; VoltProcedure procedure = null; if (proc.getHasjava()) { final String className = proc.getClassname(); Language lang; try { lang = Language.valueOf(proc.getLanguage()); } catch (IllegalArgumentException e) { // default to java for earlier compiled catalogs lang = Language.JAVA; } Class<?> procClass = null; try { procClass = catalogContext.classForProcedure(className); } catch (final ClassNotFoundException e) { if (className.startsWith("org.voltdb.")) { VoltDB.crashLocalVoltDB("VoltDB does not support procedures with package names " + "that are prefixed with \"org.voltdb\". Please use a different " + "package name and retry. Procedure name was " + className + ".", false, null); } else { VoltDB.crashLocalVoltDB("VoltDB was unable to load a procedure (" + className + ") it expected to be in the " + "catalog jarfile and will now exit.", false, null); } } try { procedure = lang.accept(procedureInstantiator, procClass); } catch (final Exception e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } } else { procedure = new ProcedureRunner.StmtProcedure(); } assert(procedure != null); runner = m_runnerFactory.create(procedure, proc, csp); builder.put(proc.getTypeName().intern(), runner); } return builder; } private static Language.CheckedExceptionVisitor<VoltProcedure, Class<?>, Exception> procedureInstantiator = new Language.CheckedExceptionVisitor<VoltProcedure, Class<?>, Exception>() { @Override public VoltProcedure visitJava(Class<?> p) throws Exception { return (VoltProcedure)p.newInstance(); } @Override public VoltProcedure visitGroovy(Class<?> p) throws Exception { return new GroovyScriptProcedureDelegate(p); } }; private void loadSystemProcedures( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp, ImmutableMap.Builder<String, ProcedureRunner> builder) { Set<Entry<String,Config>> entrySet = SystemProcedureCatalog.listing.entrySet(); for (Entry<String, Config> entry : entrySet) { Config sysProc = entry.getValue(); Procedure proc = sysProc.asCatalogProcedure(); VoltSystemProcedure procedure = null; ProcedureRunner runner = null; final String className = sysProc.getClassname(); Class<?> procClass = null; // this check is for sysprocs that don't have a procedure class if (className != null) { try { procClass = catalogContext.classForProcedure(className); } catch (final ClassNotFoundException e) { if (sysProc.commercial) { continue; } hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } try { procedure = (VoltSystemProcedure) procClass.newInstance(); } catch (final InstantiationException e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } catch (final IllegalAccessException e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } runner = m_runnerFactory.create(procedure, proc, csp); procedure.initSysProc(m_site, this, proc, catalogContext.cluster); builder.put(entry.getKey().intern(), runner); } } } public ProcedureRunner getProcByName(String procName) { return procs.get(procName); } }
zheguang/voltdb
src/frontend/org/voltdb/LoadedProcedureSet.java
Java
agpl-3.0
8,988
/** * ISARI Import Scripts File Definitions * ====================================== * * Defining the various files to import as well as their line consumers. */ module.exports = { organizations: require('./organizations.js'), people: require('./people.js'), activities: require('./activities.js'), postProcessing: require('./post-processing.js') };
SciencesPo/isari
scripts/import/files/index.js
JavaScript
agpl-3.0
363
/* * Copyright © Région Nord Pas de Calais-Picardie. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package org.entcore.cursus.controllers; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Map; import io.vertx.core.http.*; import org.entcore.common.http.filter.ResourceFilter; import org.entcore.common.user.UserInfos; import org.entcore.common.user.UserUtils; import org.entcore.common.utils.MapFactory; import org.entcore.cursus.filters.CursusFilter; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import org.vertx.java.core.http.RouteMatcher; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.rs.*; import fr.wseduc.security.ActionType; import fr.wseduc.security.SecuredAction; import fr.wseduc.webutils.Either; import fr.wseduc.webutils.http.BaseController; public class CursusController extends BaseController { //Service private final CursusService service = new CursusService(); //Webservice client & endpoint private HttpClient cursusClient; private final URL wsEndpoint; //Webservice auth request conf private final JsonObject authConf; //Auth reply data & wallets list private Map<String, String> cursusMap; @Override public void init(Vertx vertx, JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions); HttpClientOptions cursusClientOptions = new HttpClientOptions() .setDefaultHost(wsEndpoint.getHost()); if("https".equals(wsEndpoint.getProtocol())){ cursusClientOptions .setSsl(true) .setTrustAll(true) .setDefaultPort(443); } else { cursusClientOptions .setDefaultPort(wsEndpoint.getPort() == -1 ? 80 : wsEndpoint.getPort()); } cursusClient = vertx.createHttpClient(cursusClientOptions); cursusMap = MapFactory.getSyncClusterMap("cursusMap", vertx, false); /* service.refreshToken(new Handler<Boolean>() { public void handle(Boolean res) { if(!res) log.error("[Cursus][refreshToken] Error while retrieving the Token."); else log.info("[Cursus][refreshToken] Token refreshed."); } }); */ if(cursusMap.containsKey("wallets")) return; service.refreshWallets(new Handler<Boolean>() { public void handle(Boolean res) { if(!res) log.error("[Cursus][refreshWallets] Error while retrieving the wallets list."); else log.info("[Cursus][refreshWallets] Wallets list refreshed."); } }); } public CursusController(URL endpoint, final JsonObject conf){ wsEndpoint = endpoint; authConf = conf; } @Put("/refreshToken") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(CursusFilter.class) public void refreshToken(final HttpServerRequest request){ service.refreshToken(new Handler<Boolean>() { public void handle(Boolean success) { if(success){ ok(request); } else { badRequest(request); } } }); } @Put("/refreshWallets") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(CursusFilter.class) public void refreshWallets(final HttpServerRequest request){ service.refreshWallets(new Handler<Boolean>() { public void handle(Boolean success) { if(success){ ok(request); } else { badRequest(request); } } }); } @Get("/sales") @SecuredAction(value = "", type = ActionType.AUTHENTICATED) public void getSales(final HttpServerRequest request){ final String cardNb = request.params().get("cardNb"); if(cardNb == null){ badRequest(request); return; } service.getUserInfo(cardNb, new Handler<Either<String,JsonArray>>() { public void handle(Either<String, JsonArray> result) { if(result.isLeft()){ badRequest(request); return; } final String id = result.right().getValue().getJsonObject(0).getInteger("id").toString(); String birthDateEncoded = result.right().getValue().getJsonObject(0).getString("dateNaissance"); try { birthDateEncoded = birthDateEncoded.replace("/Date(", ""); birthDateEncoded = birthDateEncoded.substring(0, birthDateEncoded.indexOf("+")); final Date birthDate = new Date(Long.parseLong(birthDateEncoded)); UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { public void handle(UserInfos infos) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date sessionBirthDate = format.parse(infos.getBirthDate()); if(sessionBirthDate.compareTo(birthDate) == 0){ service.getSales(id, cardNb, new Handler<Either<String,JsonArray>>() { public void handle(Either<String, JsonArray> result) { if(result.isLeft()){ badRequest(request); return; } JsonObject finalResult = new JsonObject() .put("wallets", new JsonArray(cursusMap.get("wallets"))) .put("sales", result.right().getValue()); renderJson(request, finalResult); } }); } else { badRequest(request); } } catch (ParseException e) { badRequest(request); return; } } }); } catch(Exception e){ badRequest(request); } } }); } /** * Inner service class. */ private class CursusService{ public void authWrapper(final Handler<Boolean> handler){ JsonObject authObject = new JsonObject(); if(cursusMap.get("auth") != null) authObject = new JsonObject(cursusMap.get("auth")); Long currentDate = Calendar.getInstance().getTimeInMillis(); Long expirationDate = 0l; if(authObject != null) expirationDate = authObject.getLong("tokenInit", 0l) + authConf.getLong("tokenDelay", 1800000l); if(expirationDate < currentDate){ log.info("[Cursus] Token seems to have expired."); refreshToken(handler); } else { handler.handle(true); } } public void refreshToken(final Handler<Boolean> handler){ HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/AuthentificationImpl.svc/json/AuthentificationExtranet", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(false); log.error(response.statusMessage()); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { log.info("[Cursus][refreshToken] Token refreshed."); JsonObject authData = new JsonObject(body.toString()); authData.put("tokenInit", new Date().getTime()); cursusMap.put("auth", authData.encode()); handler.handle(true); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(authConf.encode()); } public void refreshWallets(final Handler<Boolean> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(false); return; } int schoolYear = Calendar.getInstance().get(Calendar.MONTH) < 8 ? Calendar.getInstance().get(Calendar.YEAR) - 1 : Calendar.getInstance().get(Calendar.YEAR); /* JSON */ JsonObject reqBody = new JsonObject(); reqBody .put("numSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("typeListes", new JsonArray() .add(new JsonObject() .put("typeListe", "LST_PORTEMONNAIE") .put("param1", schoolYear + "-" + (schoolYear + 1)) ) ); /* */ /* XML / String reqBody = "<tem:GetListes xmlns:tem=\"http://tempuri.org/\" xmlns:wcf=\"http://schemas.datacontract.org/2004/07/WcfExtranetChequeBL.POCO.Parametres\">" + "<tem:numSite>"+ authConf.getString("numSite") +"</tem:numSite>" + "<tem:typeListes>" + "<wcf:RechercheTypeListe>" + "<wcf:typeListe>LST_PORTEMONNAIE</wcf:typeListe>" + "<wcf:param1>"+ schoolYear + "-" + (schoolYear + 1) +"</wcf:param1>" + "</wcf:RechercheTypeListe>" + "</tem:typeListes>" + "<tem:tokenId>"+ authData.getString("tokenId") +"</tem:tokenId>" + "</tem:GetListes>"; /* */ HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/GeneralImpl.svc/json/GetListes", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(false); log.error(response.statusMessage()); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { try{ cursusMap.put("wallets", new JsonArray(body.toString()).getJsonObject(0) .getJsonArray("parametres").encode()); handler.handle(true); } catch(Exception e){ handler.handle(false); } } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); }; public void getUserInfo(final String cardNb, final Handler<Either<String, JsonArray>> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(new Either.Left<String, JsonArray>("[Cursus][getUserInfo] Issue while retrieving token.")); return; } JsonObject reqBody = new JsonObject(); reqBody .put("numSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("filtres", new JsonObject() .put("numeroCarte", cardNb)); HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/BeneficiaireImpl.svc/json/GetListeBeneficiaire", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(new Either.Left<String, JsonArray>("invalid.status.code")); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { handler.handle(new Either.Right<String, JsonArray>(new JsonArray(body.toString()))); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); } public void getSales(final String numeroDossier, final String cardNb, final Handler<Either<String, JsonArray>> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(new Either.Left<String, JsonArray>("[Cursus][getSales] Issue while retrieving token.")); return; } JsonObject reqBody = new JsonObject(); reqBody .put("numeroSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("filtresSoldesBeneficiaire", new JsonObject() .put("numeroDossier", numeroDossier) .put("numeroCarte", cardNb)); HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/BeneficiaireImpl.svc/json/GetSoldesBeneficiaire", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(new Either.Left<String, JsonArray>("invalid.status.code")); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { handler.handle(new Either.Right<String, JsonArray>(new JsonArray(body.toString()))); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); } } }
OPEN-ENT-NG/cursus
src/main/java/org/entcore/cursus/controllers/CursusController.java
Java
agpl-3.0
13,069
// Copyright David Abrahams 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef UNWIND_TYPE_DWA200222_HPP # define UNWIND_TYPE_DWA200222_HPP # include <boost/python/detail/cv_category.hpp> # include <boost/python/detail/indirect_traits.hpp> # include <boost/type_traits/object_traits.hpp> namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{ namespace python { namespace detail { #ifndef _MSC_VER //if forward declared, msvc6.5 does not recognize them as inline // forward declaration, required (at least) by Tru64 cxx V6.5-042 template <class Generator, class U> inline typename Generator::result_type unwind_type(U const& p, Generator* = 0); // forward declaration, required (at least) by Tru64 cxx V6.5-042 template <class Generator, class U> inline typename Generator::result_type unwind_type(abt_boost::type<U>*p = 0, Generator* = 0); #endif template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U* p, cv_unqualified, Generator* = 0) { return Generator::execute(p); } template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U const* p, const_, Generator* = 0) { return unwind_type(const_cast<U*>(p), (Generator*)0); } template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U volatile* p, volatile_, Generator* = 0) { return unwind_type(const_cast<U*>(p), (Generator*)0); } template <class Generator, class U> inline typename Generator::result_type unwind_type_cv(U const volatile* p, const_volatile_, Generator* = 0) { return unwind_type(const_cast<U*>(p), (Generator*)0); } template <class Generator, class U> inline typename Generator::result_type unwind_ptr_type(U* p, Generator* = 0) { typedef typename cv_category<U>::type tag; return unwind_type_cv<Generator>(p, tag()); } template <bool is_ptr> struct unwind_helper { template <class Generator, class U> static typename Generator::result_type execute(U p, Generator* = 0) { return unwind_ptr_type(p, (Generator*)0); } }; template <> struct unwind_helper<false> { template <class Generator, class U> static typename Generator::result_type execute(U& p, Generator* = 0) { return unwind_ptr_type(&p, (Generator*)0); } }; template <class Generator, class U> inline typename Generator::result_type #ifndef _MSC_VER unwind_type(U const& p, Generator*) #else unwind_type(U const& p, Generator* = 0) #endif { return unwind_helper<is_pointer<U>::value>::execute(p, (Generator*)0); } enum { direct_ = 0, pointer_ = 1, reference_ = 2, reference_to_pointer_ = 3 }; template <int indirection> struct unwind_helper2; template <> struct unwind_helper2<direct_> { template <class Generator, class U> static typename Generator::result_type execute(U(*)(), Generator* = 0) { return unwind_ptr_type((U*)0, (Generator*)0); } }; template <> struct unwind_helper2<pointer_> { template <class Generator, class U> static typename Generator::result_type execute(U*(*)(), Generator* = 0) { return unwind_ptr_type((U*)0, (Generator*)0); } }; template <> struct unwind_helper2<reference_> { template <class Generator, class U> static typename Generator::result_type execute(U&(*)(), Generator* = 0) { return unwind_ptr_type((U*)0, (Generator*)0); } }; template <> struct unwind_helper2<reference_to_pointer_> { template <class Generator, class U> static typename Generator::result_type execute(U&(*)(), Generator* = 0) { return unwind_ptr_type(U(0), (Generator*)0); } }; // Call this one with both template parameters explicitly specified // and no function arguments: // // return unwind_type<my_generator,T>(); // // Doesn't work if T is an array type; we could handle that case, but // why bother? template <class Generator, class U> inline typename Generator::result_type #ifndef _MSC_VER unwind_type(abt_boost::type<U>*, Generator*) #else unwind_type(abt_boost::type<U>*p =0, Generator* =0) #endif { BOOST_STATIC_CONSTANT(int, indirection = (abt_boost::is_pointer<U>::value ? pointer_ : 0) + (indirect_traits::is_reference_to_pointer<U>::value ? reference_to_pointer_ : abt_boost::is_reference<U>::value ? reference_ : 0)); return unwind_helper2<indirection>::execute((U(*)())0,(Generator*)0); } }}} // namespace abt_boost::python::detail #endif // UNWIND_TYPE_DWA200222_HPP
jbruestle/aggregate_btree
tiny_boost/boost/python/detail/unwind_type.hpp
C++
agpl-3.0
4,739
class Api::AccountsController < ApiController def index @accounts = current_user.accounts respond_with(@accounts) end def show find_account! respond_with(@account) end def update find_account! @account.update(account_params) respond_with(@account) end private def find_account! @account = Account.find_by!(id: params.fetch(:id)) authorize! AccountReadPolicy.new(@account, current_user) end def account_params params.permit(:name, :website_url, :webhook_url, :prefers_archiving) end end
asm-helpful/helpful-web
app/controllers/api/accounts_controller.rb
Ruby
agpl-3.0
555
define(['sylvester', 'sha1', 'PrairieGeom'], function (Sylvester, Sha1, PrairieGeom) { var $V = Sylvester.Vector.create; var Vector = Sylvester.Vector; var Matrix = Sylvester.Matrix; /*****************************************************************************/ /** Creates a PrairieDraw object. @constructor @this {PrairieDraw} @param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt. @param {Function} drawfcn An optional function that draws on the canvas. */ function PrairieDraw(canvas, drawFcn) { if (canvas) { if (canvas instanceof HTMLCanvasElement) { this._canvas = canvas; } else if (canvas instanceof String || typeof canvas === 'string') { this._canvas = document.getElementById(canvas); } else { //throw new Error("PrairieDraw: unknown object type for constructor") this._canvas = undefined; } if (this._canvas) { this._canvas.prairieDraw = this; this._ctx = this._canvas.getContext('2d'); if (this._ctx.setLineDash === undefined) { this._ctx.setLineDash = function () {}; } this._width = this._canvas.width; this._height = this._canvas.height; this._trans = Matrix.I(3); this._transStack = []; this._initViewAngleX3D = (-Math.PI / 2) * 0.75; this._initViewAngleY3D = 0; this._initViewAngleZ3D = (-Math.PI / 2) * 1.25; this._viewAngleX3D = this._initViewAngleX3D; this._viewAngleY3D = this._initViewAngleY3D; this._viewAngleZ3D = this._initViewAngleZ3D; this._trans3D = PrairieGeom.rotateTransform3D( Matrix.I(4), this._initViewAngleX3D, this._initViewAngleY3D, this._initViewAngleZ3D ); this._trans3DStack = []; this._props = {}; this._initProps(); this._propStack = []; this._options = {}; this._history = {}; this._images = {}; this._redrawCallbacks = []; if (drawFcn) { this.draw = drawFcn.bind(this); } this.save(); this.draw(); this.restoreAll(); } } } /** Creates a new PrairieDraw from a canvas ID. @param {string} id The ID of the canvas element to draw on. @return {PrairieDraw} The new PrairieDraw object. */ PrairieDraw.fromCanvasId = function (id) { var canvas = document.getElementById(id); if (!canvas) { throw new Error('PrairieDraw: unable to find canvas ID: ' + id); } return new PrairieDraw(canvas); }; /** Prototype function to draw on the canvas, should be implemented by children. */ PrairieDraw.prototype.draw = function () {}; /** Redraw the drawing. */ PrairieDraw.prototype.redraw = function () { this.save(); this.draw(); this.restoreAll(); for (var i = 0; i < this._redrawCallbacks.length; i++) { this._redrawCallbacks[i](); } }; /** Add a callback on redraw() calls. */ PrairieDraw.prototype.registerRedrawCallback = function (callback) { this._redrawCallbacks.push(callback.bind(this)); }; /** @private Initialize properties. */ PrairieDraw.prototype._initProps = function () { this._props.viewAngleXMin = -Math.PI / 2 + 1e-6; this._props.viewAngleXMax = -1e-6; this._props.viewAngleYMin = -Infinity; this._props.viewAngleYMax = Infinity; this._props.viewAngleZMin = -Infinity; this._props.viewAngleZMax = Infinity; this._props.arrowLineWidthPx = 2; this._props.arrowLinePattern = 'solid'; this._props.arrowheadLengthRatio = 7; // arrowheadLength / arrowLineWidth this._props.arrowheadWidthRatio = 0.3; // arrowheadWidth / arrowheadLength this._props.arrowheadOffsetRatio = 0.3; // arrowheadOffset / arrowheadLength this._props.circleArrowWrapOffsetRatio = 1.5; this._props.arrowOutOfPageRadiusPx = 5; this._props.textOffsetPx = 4; this._props.textFontSize = 14; this._props.pointRadiusPx = 2; this._props.shapeStrokeWidthPx = 2; this._props.shapeStrokePattern = 'solid'; this._props.shapeOutlineColor = 'rgb(0, 0, 0)'; this._props.shapeInsideColor = 'rgb(255, 255, 255)'; this._props.hiddenLineDraw = true; this._props.hiddenLineWidthPx = 2; this._props.hiddenLinePattern = 'dashed'; this._props.hiddenLineColor = 'rgb(0, 0, 0)'; this._props.centerOfMassStrokeWidthPx = 2; this._props.centerOfMassColor = 'rgb(180, 49, 4)'; this._props.centerOfMassRadiusPx = 5; this._props.rightAngleSizePx = 10; this._props.rightAngleStrokeWidthPx = 1; this._props.rightAngleColor = 'rgb(0, 0, 0)'; this._props.measurementStrokeWidthPx = 1; this._props.measurementStrokePattern = 'solid'; this._props.measurementEndLengthPx = 10; this._props.measurementOffsetPx = 3; this._props.measurementColor = 'rgb(0, 0, 0)'; this._props.groundDepthPx = 10; this._props.groundWidthPx = 10; this._props.groundSpacingPx = 10; this._props.groundOutlineColor = 'rgb(0, 0, 0)'; this._props.groundInsideColor = 'rgb(220, 220, 220)'; this._props.gridColor = 'rgb(200, 200, 200)'; this._props.positionColor = 'rgb(0, 0, 255)'; this._props.angleColor = 'rgb(0, 100, 180)'; this._props.velocityColor = 'rgb(0, 200, 0)'; this._props.angVelColor = 'rgb(100, 180, 0)'; this._props.accelerationColor = 'rgb(255, 0, 255)'; this._props.rotationColor = 'rgb(150, 0, 150)'; this._props.angAccColor = 'rgb(100, 0, 180)'; this._props.angMomColor = 'rgb(255, 0, 0)'; this._props.forceColor = 'rgb(210, 105, 30)'; this._props.momentColor = 'rgb(255, 102, 80)'; }; /*****************************************************************************/ /** The golden ratio. */ PrairieDraw.prototype.goldenRatio = (1 + Math.sqrt(5)) / 2; /** Get the canvas width. @return {number} The canvas width in Px. */ PrairieDraw.prototype.widthPx = function () { return this._width; }; /** Get the canvas height. @return {number} The canvas height in Px. */ PrairieDraw.prototype.heightPx = function () { return this._height; }; /*****************************************************************************/ /** Conversion constants. */ PrairieDraw.prototype.milesPerKilometer = 0.621371; /*****************************************************************************/ /** Scale the coordinate system. @param {Vector} factor Scale factors. */ PrairieDraw.prototype.scale = function (factor) { this._trans = PrairieGeom.scaleTransform(this._trans, factor); }; /** Translate the coordinate system. @param {Vector} offset Translation offset (drawing coords). */ PrairieDraw.prototype.translate = function (offset) { this._trans = PrairieGeom.translateTransform(this._trans, offset); }; /** Rotate the coordinate system. @param {number} angle Angle to rotate by (radians). */ PrairieDraw.prototype.rotate = function (angle) { this._trans = PrairieGeom.rotateTransform(this._trans, angle); }; /** Transform the coordinate system (scale, translate, rotate) to match old points to new. Drawing at the old locations will result in points at the new locations. @param {Vector} old1 The old location of point 1. @param {Vector} old2 The old location of point 2. @param {Vector} new1 The new location of point 1. @param {Vector} new2 The new location of point 2. */ PrairieDraw.prototype.transformByPoints = function (old1, old2, new1, new2) { this._trans = PrairieGeom.transformByPointsTransform(this._trans, old1, old2, new1, new2); }; /*****************************************************************************/ /** Transform a vector from drawing to pixel coords. @param {Vector} vDw Vector in drawing coords. @return {Vector} Vector in pixel coords. */ PrairieDraw.prototype.vec2Px = function (vDw) { return PrairieGeom.transformVec(this._trans, vDw); }; /** Transform a position from drawing to pixel coords. @param {Vector} pDw Position in drawing coords. @return {Vector} Position in pixel coords. */ PrairieDraw.prototype.pos2Px = function (pDw) { return PrairieGeom.transformPos(this._trans, pDw); }; /** Transform a vector from pixel to drawing coords. @param {Vector} vPx Vector in pixel coords. @return {Vector} Vector in drawing coords. */ PrairieDraw.prototype.vec2Dw = function (vPx) { return PrairieGeom.transformVec(this._trans.inverse(), vPx); }; /** Transform a position from pixel to drawing coords. @param {Vector} pPx Position in pixel coords. @return {Vector} Position in drawing coords. */ PrairieDraw.prototype.pos2Dw = function (pPx) { return PrairieGeom.transformPos(this._trans.inverse(), pPx); }; /** @private Returns true if the current transformation is a reflection. @return {bool} Whether the current transformation is a reflection. */ PrairieDraw.prototype._transIsReflection = function () { var det = this._trans.e(1, 1) * this._trans.e(2, 2) - this._trans.e(1, 2) * this._trans.e(2, 1); if (det < 0) { return true; } else { return false; } }; /** Transform a position from normalized viewport [0,1] to drawing coords. @param {Vector} pNm Position in normalized viewport coordinates. @return {Vector} Position in drawing coordinates. */ PrairieDraw.prototype.posNm2Dw = function (pNm) { var pPx = this.posNm2Px(pNm); return this.pos2Dw(pPx); }; /** Transform a position from normalized viewport [0,1] to pixel coords. @param {Vector} pNm Position in normalized viewport coords. @return {Vector} Position in pixel coords. */ PrairieDraw.prototype.posNm2Px = function (pNm) { return $V([pNm.e(1) * this._width, (1 - pNm.e(2)) * this._height]); }; /*****************************************************************************/ /** Set the 3D view to the given angles. @param {number} angleX The rotation angle about the X axis. @param {number} angleY The rotation angle about the Y axis. @param {number} angleZ The rotation angle about the Z axis. @param {bool} clip (Optional) Whether to clip to max/min range (default: true). @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDraw.prototype.setView3D = function (angleX, angleY, angleZ, clip, redraw) { clip = clip === undefined ? true : clip; redraw = redraw === undefined ? true : redraw; this._viewAngleX3D = angleX; this._viewAngleY3D = angleY; this._viewAngleZ3D = angleZ; if (clip) { this._viewAngleX3D = PrairieGeom.clip( this._viewAngleX3D, this._props.viewAngleXMin, this._props.viewAngleXMax ); this._viewAngleY3D = PrairieGeom.clip( this._viewAngleY3D, this._props.viewAngleYMin, this._props.viewAngleYMax ); this._viewAngleZ3D = PrairieGeom.clip( this._viewAngleZ3D, this._props.viewAngleZMin, this._props.viewAngleZMax ); } this._trans3D = PrairieGeom.rotateTransform3D( Matrix.I(4), this._viewAngleX3D, this._viewAngleY3D, this._viewAngleZ3D ); if (redraw) { this.redraw(); } }; /** Reset the 3D view to default. @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDraw.prototype.resetView3D = function (redraw) { this.setView3D( this._initViewAngleX3D, this._initViewAngleY3D, this._initViewAngleZ3D, undefined, redraw ); }; /** Increment the 3D view by the given angles. @param {number} deltaAngleX The incremental rotation angle about the X axis. @param {number} deltaAngleY The incremental rotation angle about the Y axis. @param {number} deltaAngleZ The incremental rotation angle about the Z axis. @param {bool} clip (Optional) Whether to clip to max/min range (default: true). */ PrairieDraw.prototype.incrementView3D = function (deltaAngleX, deltaAngleY, deltaAngleZ, clip) { this.setView3D( this._viewAngleX3D + deltaAngleX, this._viewAngleY3D + deltaAngleY, this._viewAngleZ3D + deltaAngleZ, clip ); }; /*****************************************************************************/ /** Scale the 3D coordinate system. @param {Vector} factor Scale factor. */ PrairieDraw.prototype.scale3D = function (factor) { this._trans3D = PrairieGeom.scaleTransform3D(this._trans3D, factor); }; /** Translate the 3D coordinate system. @param {Vector} offset Translation offset. */ PrairieDraw.prototype.translate3D = function (offset) { this._trans3D = PrairieGeom.translateTransform3D(this._trans3D, offset); }; /** Rotate the 3D coordinate system. @param {number} angleX Angle to rotate by around the X axis (radians). @param {number} angleY Angle to rotate by around the Y axis (radians). @param {number} angleZ Angle to rotate by around the Z axis (radians). */ PrairieDraw.prototype.rotate3D = function (angleX, angleY, angleZ) { this._trans3D = PrairieGeom.rotateTransform3D(this._trans3D, angleX, angleY, angleZ); }; /*****************************************************************************/ /** Transform a position to the view coordinates in 3D. @param {Vector} pDw Position in 3D drawing coords. @return {Vector} Position in 3D viewing coords. */ PrairieDraw.prototype.posDwToVw = function (pDw) { var pVw = PrairieGeom.transformPos3D(this._trans3D, pDw); return pVw; }; /** Transform a position from the view coordinates in 3D. @param {Vector} pVw Position in 3D viewing coords. @return {Vector} Position in 3D drawing coords. */ PrairieDraw.prototype.posVwToDw = function (pVw) { var pDw = PrairieGeom.transformPos3D(this._trans3D.inverse(), pVw); return pDw; }; /** Transform a vector to the view coordinates in 3D. @param {Vector} vDw Vector in 3D drawing coords. @return {Vector} Vector in 3D viewing coords. */ PrairieDraw.prototype.vecDwToVw = function (vDw) { var vVw = PrairieGeom.transformVec3D(this._trans3D, vDw); return vVw; }; /** Transform a vector from the view coordinates in 3D. @param {Vector} vVw Vector in 3D viewing coords. @return {Vector} Vector in 3D drawing coords. */ PrairieDraw.prototype.vecVwToDw = function (vVw) { var vDw = PrairieGeom.transformVec3D(this._trans3D.inverse(), vVw); return vDw; }; /** Transform a position from 3D to 2D drawing coords if necessary. @param {Vector} pDw Position in 2D or 3D drawing coords. @return {Vector} Position in 2D drawing coords. */ PrairieDraw.prototype.pos3To2 = function (pDw) { if (pDw.elements.length === 3) { return PrairieGeom.orthProjPos3D(this.posDwToVw(pDw)); } else { return pDw; } }; /** Transform a vector from 3D to 2D drawing coords if necessary. @param {Vector} vDw Vector in 2D or 3D drawing coords. @param {Vector} pDw Base point of vector (if in 3D). @return {Vector} Vector in 2D drawing coords. */ PrairieDraw.prototype.vec3To2 = function (vDw, pDw) { if (vDw.elements.length === 3) { var qDw = pDw.add(vDw); var p2Dw = this.pos3To2(pDw); var q2Dw = this.pos3To2(qDw); var v2Dw = q2Dw.subtract(p2Dw); return v2Dw; } else { return vDw; } }; /** Transform a position from 2D to 3D drawing coords if necessary (adding z = 0). @param {Vector} pDw Position in 2D or 3D drawing coords. @return {Vector} Position in 3D drawing coords. */ PrairieDraw.prototype.pos2To3 = function (pDw) { if (pDw.elements.length === 2) { return $V([pDw.e(1), pDw.e(2), 0]); } else { return pDw; } }; /** Transform a vector from 2D to 3D drawing coords if necessary (adding z = 0). @param {Vector} vDw Vector in 2D or 3D drawing coords. @return {Vector} Vector in 3D drawing coords. */ PrairieDraw.prototype.vec2To3 = function (vDw) { if (vDw.elements.length === 2) { return $V([vDw.e(1), vDw.e(2), 0]); } else { return vDw; } }; /*****************************************************************************/ /** Set a property. @param {string} name The name of the property. @param {number} value The value to set the property to. */ PrairieDraw.prototype.setProp = function (name, value) { if (!(name in this._props)) { throw new Error('PrairieDraw: unknown property name: ' + name); } this._props[name] = value; }; /** Get a property. @param {string} name The name of the property. @return {number} The current value of the property. */ PrairieDraw.prototype.getProp = function (name) { if (!(name in this._props)) { throw new Error('PrairieDraw: unknown property name: ' + name); } return this._props[name]; }; /** @private Colors. */ PrairieDraw._colors = { black: 'rgb(0, 0, 0)', white: 'rgb(255, 255, 255)', red: 'rgb(255, 0, 0)', green: 'rgb(0, 255, 0)', blue: 'rgb(0, 0, 255)', cyan: 'rgb(0, 255, 255)', magenta: 'rgb(255, 0, 255)', yellow: 'rgb(255, 255, 0)', }; /** @private Get a color property for a given type. @param {string} type Optional type to find the color for. */ PrairieDraw.prototype._getColorProp = function (type) { if (type === undefined) { return this._props.shapeOutlineColor; } var col = type + 'Color'; if (col in this._props) { var c = this._props[col]; if (c in PrairieDraw._colors) { return PrairieDraw._colors[c]; } else { return c; } } else if (type in PrairieDraw._colors) { return PrairieDraw._colors[type]; } else { return type; } }; /** @private Set shape drawing properties for drawing hidden lines. */ PrairieDraw.prototype.setShapeDrawHidden = function () { this._props.shapeStrokeWidthPx = this._props.hiddenLineWidthPx; this._props.shapeStrokePattern = this._props.hiddenLinePattern; this._props.shapeOutlineColor = this._props.hiddenLineColor; }; /*****************************************************************************/ /** Add an external option for this drawing. @param {string} name The option name. @param {object} value The default initial value. */ PrairieDraw.prototype.addOption = function (name, value, triggerRedraw) { if (!(name in this._options)) { this._options[name] = { value: value, resetValue: value, callbacks: {}, triggerRedraw: triggerRedraw === undefined ? true : triggerRedraw, }; } else if (!('value' in this._options[name])) { var option = this._options[name]; option.value = value; option.resetValue = value; for (var p in option.callbacks) { option.callbacks[p](option.value); } } }; /** Set an option to a given value. @param {string} name The option name. @param {object} value The new value for the option. @param {bool} redraw (Optional) Whether to trigger a redraw() (default: true). @param {Object} trigger (Optional) The object that triggered the change. @param {bool} setReset (Optional) Also set this value to be the new reset value (default: false). */ PrairieDraw.prototype.setOption = function (name, value, redraw, trigger, setReset) { redraw = redraw === undefined ? true : redraw; setReset = setReset === undefined ? false : setReset; if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; option.value = value; if (setReset) { option.resetValue = value; } for (var p in option.callbacks) { option.callbacks[p](option.value, trigger); } if (redraw) { this.redraw(); } }; /** Get the value of an option. @param {string} name The option name. @return {object} The current value for the option. */ PrairieDraw.prototype.getOption = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if (!('value' in this._options[name])) { throw new Error('PrairieDraw: option has no value: ' + name); } return this._options[name].value; }; /** Set an option to the logical negation of its current value. @param {string} name The option name. */ PrairieDraw.prototype.toggleOption = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if (!('value' in this._options[name])) { throw new Error('PrairieDraw: option has no value: ' + name); } var option = this._options[name]; option.value = !option.value; for (var p in option.callbacks) { option.callbacks[p](option.value); } this.redraw(); }; /** Register a callback on option changes. @param {string} name The option to register on. @param {Function} callback The callback(value) function. @param {string} callbackID (Optional) The ID of the callback. If omitted, a new unique ID will be generated. */ PrairieDraw.prototype.registerOptionCallback = function (name, callback, callbackID) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; var useID; if (callbackID === undefined) { var nextIDNumber = 0, curIDNumber; for (var p in option.callbacks) { curIDNumber = parseInt(p, 10); if (isFinite(curIDNumber)) { nextIDNumber = Math.max(nextIDNumber, curIDNumber + 1); } } useID = nextIDNumber.toString(); } else { useID = callbackID; } option.callbacks[useID] = callback.bind(this); option.callbacks[useID](option.value); }; /** Clear the value for the given option. @param {string} name The option to clear. */ PrairieDraw.prototype.clearOptionValue = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } if ('value' in this._options[name]) { delete this._options[name].value; } this.redraw(); }; /** Reset the value for the given option. @param {string} name The option to reset. */ PrairieDraw.prototype.resetOptionValue = function (name) { if (!(name in this._options)) { throw new Error('PrairieDraw: unknown option: ' + name); } var option = this._options[name]; if (!('resetValue' in option)) { throw new Error('PrairieDraw: option has no resetValue: ' + name); } option.value = option.resetValue; for (var p in option.callbacks) { option.callbacks[p](option.value); } }; /*****************************************************************************/ /** Save the graphics state (properties, options, and transformations). @see restore(). */ PrairieDraw.prototype.save = function () { this._ctx.save(); var oldProps = {}; for (var p in this._props) { oldProps[p] = this._props[p]; } this._propStack.push(oldProps); this._transStack.push(this._trans.dup()); this._trans3DStack.push(this._trans3D.dup()); }; /** Restore the graphics state (properties, options, and transformations). @see save(). */ PrairieDraw.prototype.restore = function () { this._ctx.restore(); if (this._propStack.length === 0) { throw new Error('PrairieDraw: tried to restore() without corresponding save()'); } if (this._propStack.length !== this._transStack.length) { throw new Error('PrairieDraw: incompatible save stack lengths'); } if (this._propStack.length !== this._trans3DStack.length) { throw new Error('PrairieDraw: incompatible save stack lengths'); } this._props = this._propStack.pop(); this._trans = this._transStack.pop(); this._trans3D = this._trans3DStack.pop(); }; /** Restore all outstanding saves. */ PrairieDraw.prototype.restoreAll = function () { while (this._propStack.length > 0) { this.restore(); } if (this._saveTrans !== undefined) { this._trans = this._saveTrans; } }; /*****************************************************************************/ /** Reset the canvas image and drawing context. */ PrairieDraw.prototype.clearDrawing = function () { this._ctx.clearRect(0, 0, this._width, this._height); }; /** Reset everything to the intial state. */ PrairieDraw.prototype.reset = function () { for (var optionName in this._options) { this.resetOptionValue(optionName); } this.resetView3D(false); this.redraw(); }; /** Stop all action and computation. */ PrairieDraw.prototype.stop = function () {}; /*****************************************************************************/ /** Set the visable coordinate sizes. @param {number} xSize The horizontal size of the drawing area in coordinate units. @param {number} ySize The vertical size of the drawing area in coordinate units. @param {number} canvasWidth (Optional) The width of the canvas in px. @param {bool} preserveCanvasSize (Optional) If true, do not resize the canvas to match the coordinate ratio. */ PrairieDraw.prototype.setUnits = function (xSize, ySize, canvasWidth, preserveCanvasSize) { this.clearDrawing(); this._trans = Matrix.I(3); if (canvasWidth !== undefined) { var canvasHeight = Math.floor((ySize / xSize) * canvasWidth); if (this._width !== canvasWidth || this._height !== canvasHeight) { this._canvas.width = canvasWidth; this._canvas.height = canvasHeight; this._width = canvasWidth; this._height = canvasHeight; } preserveCanvasSize = true; } var xScale = this._width / xSize; var yScale = this._height / ySize; if (xScale < yScale) { this._scale = xScale; if (!preserveCanvasSize && xScale !== yScale) { var newHeight = xScale * ySize; this._canvas.height = newHeight; this._height = newHeight; } this.translate($V([this._width / 2, this._height / 2])); this.scale($V([1, -1])); this.scale($V([xScale, xScale])); } else { this._scale = yScale; if (!preserveCanvasSize && xScale !== yScale) { var newWidth = yScale * xSize; this._canvas.width = newWidth; this._width = newWidth; } this.translate($V([this._width / 2, this._height / 2])); this.scale($V([1, -1])); this.scale($V([yScale, yScale])); } this._saveTrans = this._trans; }; /*****************************************************************************/ /** Draw a point. @param {Vector} posDw Position of the point (drawing coords). */ PrairieDraw.prototype.point = function (posDw) { posDw = this.pos3To2(posDw); var posPx = this.pos2Px(posDw); this._ctx.beginPath(); this._ctx.arc(posPx.e(1), posPx.e(2), this._props.pointRadiusPx, 0, 2 * Math.PI); this._ctx.fillStyle = this._props.shapeOutlineColor; this._ctx.fill(); }; /*****************************************************************************/ /** @private Set the stroke/fill styles for drawing lines. @param {string} type The type of line being drawn. */ PrairieDraw.prototype._setLineStyles = function (type) { var col = this._getColorProp(type); this._ctx.strokeStyle = col; this._ctx.fillStyle = col; }; /** Return the dash array for the given line pattern. @param {string} type The type of the dash pattern ('solid', 'dashed', 'dotted'). @return {Array} The numerical array of dash segment lengths. */ PrairieDraw.prototype._dashPattern = function (type) { if (type === 'solid') { return []; } else if (type === 'dashed') { return [6, 6]; } else if (type === 'dotted') { return [2, 2]; } else { throw new Error('PrairieDraw: unknown dash pattern: ' + type); } }; /** Draw a single line given start and end positions. @param {Vector} startDw Initial point of the line (drawing coords). @param {Vector} endDw Final point of the line (drawing coords). @param {string} type Optional type of line being drawn. */ PrairieDraw.prototype.line = function (startDw, endDw, type) { startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var startPx = this.pos2Px(startDw); var endPx = this.pos2Px(endDw); this._ctx.save(); this._setLineStyles(type); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.beginPath(); this._ctx.moveTo(startPx.e(1), startPx.e(2)); this._ctx.lineTo(endPx.e(1), endPx.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a cubic Bezier segment. @param {Vector} p0Dw The starting point. @param {Vector} p1Dw The first control point. @param {Vector} p2Dw The second control point. @param {Vector} p3Dw The ending point. @param {string} type (Optional) type of line being drawn. */ PrairieDraw.prototype.cubicBezier = function (p0Dw, p1Dw, p2Dw, p3Dw, type) { var p0Px = this.pos2Px(this.pos3To2(p0Dw)); var p1Px = this.pos2Px(this.pos3To2(p1Dw)); var p2Px = this.pos2Px(this.pos3To2(p2Dw)); var p3Px = this.pos2Px(this.pos3To2(p3Dw)); this._ctx.save(); this._setLineStyles(type); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.beginPath(); this._ctx.moveTo(p0Px.e(1), p0Px.e(2)); this._ctx.bezierCurveTo(p1Px.e(1), p1Px.e(2), p2Px.e(1), p2Px.e(2), p3Px.e(1), p3Px.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** @private Draw an arrowhead in pixel coords. @param {Vector} posPx Position of the tip. @param {Vector} dirPx Direction vector that the arrowhead points in. @param {number} lenPx Length of the arrowhead. */ PrairieDraw.prototype._arrowheadPx = function (posPx, dirPx, lenPx) { var dxPx = -(1 - this._props.arrowheadOffsetRatio) * lenPx; var dyPx = this._props.arrowheadWidthRatio * lenPx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(dirPx)); this._ctx.beginPath(); this._ctx.moveTo(0, 0); this._ctx.lineTo(-lenPx, dyPx); this._ctx.lineTo(dxPx, 0); this._ctx.lineTo(-lenPx, -dyPx); this._ctx.closePath(); this._ctx.fill(); this._ctx.restore(); }; /** @private Draw an arrowhead. @param {Vector} posDw Position of the tip (drawing coords). @param {Vector} dirDw Direction vector that the arrowhead point in (drawing coords). @param {number} lenPx Length of the arrowhead (pixel coords). */ PrairieDraw.prototype._arrowhead = function (posDw, dirDw, lenPx) { var posPx = this.pos2Px(posDw); var dirPx = this.vec2Px(dirDw); this._arrowheadPx(posPx, dirPx, lenPx); }; /** Draw an arrow given start and end positions. @param {Vector} startDw Initial point of the arrow (drawing coords). @param {Vector} endDw Final point of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrow = function (startDw, endDw, type) { startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var offsetDw = endDw.subtract(startDw); var offsetPx = this.vec2Px(offsetDw); var arrowLengthPx = offsetPx.modulus(); var lineEndDw, drawArrowHead, arrowheadLengthPx; if (arrowLengthPx < 1) { // if too short, just draw a simple line lineEndDw = endDw; drawArrowHead = false; } else { var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, arrowLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var lineLengthPx = arrowLengthPx - arrowheadCenterLengthPx; lineEndDw = startDw.add(offsetDw.x(lineLengthPx / arrowLengthPx)); drawArrowHead = true; } var startPx = this.pos2Px(startDw); var lineEndPx = this.pos2Px(lineEndDw); this.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); this._ctx.beginPath(); this._ctx.moveTo(startPx.e(1), startPx.e(2)); this._ctx.lineTo(lineEndPx.e(1), lineEndPx.e(2)); this._ctx.stroke(); if (drawArrowHead) { this._arrowhead(endDw, offsetDw, arrowheadLengthPx); } this.restore(); }; /** Draw an arrow given the start position and offset. @param {Vector} startDw Initial point of the arrow (drawing coords). @param {Vector} offsetDw Offset vector of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowFrom = function (startDw, offsetDw, type) { var endDw = startDw.add(offsetDw); this.arrow(startDw, endDw, type); }; /** Draw an arrow given the end position and offset. @param {Vector} endDw Final point of the arrow (drawing coords). @param {Vector} offsetDw Offset vector of the arrow (drawing coords). @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowTo = function (endDw, offsetDw, type) { var startDw = endDw.subtract(offsetDw); this.arrow(startDw, endDw, type); }; /** Draw an arrow out of the page (circle with centered dot). @param {Vector} posDw The position of the arrow. @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowOutOfPage = function (posDw, type) { var posPx = this.pos2Px(posDw); var r = this._props.arrowOutOfPageRadiusPx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.fillStyle = 'rgb(255, 255, 255)'; this._ctx.fill(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._setLineStyles(type); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.arc(0, 0, this._props.arrowLineWidthPx * 0.7, 0, 2 * Math.PI); this._ctx.fill(); this._ctx.restore(); }; /** Draw an arrow into the page (circle with times). @param {Vector} posDw The position of the arrow. @param {string} type Optional type of vector being drawn. */ PrairieDraw.prototype.arrowIntoPage = function (posDw, type) { var posPx = this.pos2Px(posDw); var r = this._props.arrowOutOfPageRadiusPx; var rs = r / Math.sqrt(2); this._ctx.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._setLineStyles(type); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.fillStyle = 'rgb(255, 255, 255)'; this._ctx.fill(); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(-rs, -rs); this._ctx.lineTo(rs, rs); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(rs, -rs); this._ctx.lineTo(-rs, rs); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a circle arrow by specifying the center and extent. @param {Vector} posDw The center of the circle arrow. @param {number} radDw The radius at the mid-angle. @param {number} centerAngleDw The center angle (counterclockwise from x axis, in radians). @param {number} extentAngleDw The extent of the arrow (counterclockwise, in radians). @param {string} type (Optional) The type of the arrow. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype.circleArrowCentered = function ( posDw, radDw, centerAngleDw, extentAngleDw, type, fixedRad ) { var startAngleDw = centerAngleDw - extentAngleDw / 2; var endAngleDw = centerAngleDw + extentAngleDw / 2; this.circleArrow(posDw, radDw, startAngleDw, endAngleDw, type, fixedRad); }; /** Draw a circle arrow. @param {Vector} posDw The center of the circle arrow. @param {number} radDw The radius at the mid-angle. @param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians). @param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians). @param {string} type (Optional) The type of the arrow. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). @param {number} idealSegmentSize (Optional) The ideal linear segment size to use (radians). */ PrairieDraw.prototype.circleArrow = function ( posDw, radDw, startAngleDw, endAngleDw, type, fixedRad, idealSegmentSize ) { this.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); // convert to Px coordinates var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw); var posPx = this.pos2Px(posDw); var startOffsetPx = this.vec2Px(startOffsetDw); var radiusPx = startOffsetPx.modulus(); var startAnglePx = PrairieGeom.angleOf(startOffsetPx); var deltaAngleDw = endAngleDw - startAngleDw; // assume a possibly reflected/rotated but equally scaled Dw/Px transformation var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw; var endAnglePx = startAnglePx + deltaAnglePx; // compute arrowhead properties var startRadiusPx = this._circleArrowRadius( radiusPx, startAnglePx, startAnglePx, endAnglePx, fixedRad ); var endRadiusPx = this._circleArrowRadius( radiusPx, endAnglePx, startAnglePx, endAnglePx, fixedRad ); var arrowLengthPx = radiusPx * Math.abs(endAnglePx - startAnglePx); var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; var arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, arrowLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var arrowheadExtraCenterLengthPx = (1 - this._props.arrowheadOffsetRatio / 3) * arrowheadLengthPx; var arrowheadAnglePx = arrowheadCenterLengthPx / endRadiusPx; var arrowheadExtraAnglePx = arrowheadExtraCenterLengthPx / endRadiusPx; var preEndAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadAnglePx; var arrowBaseAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadExtraAnglePx; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); idealSegmentSize = idealSegmentSize === undefined ? 0.2 : idealSegmentSize; // radians var numSegments = Math.ceil(Math.abs(preEndAnglePx - startAnglePx) / idealSegmentSize); var i, anglePx, rPx; var offsetPx = PrairieGeom.vector2DAtAngle(startAnglePx).x(startRadiusPx); this._ctx.beginPath(); this._ctx.moveTo(offsetPx.e(1), offsetPx.e(2)); for (i = 1; i <= numSegments; i++) { anglePx = PrairieGeom.linearInterp(startAnglePx, preEndAnglePx, i / numSegments); rPx = this._circleArrowRadius(radiusPx, anglePx, startAnglePx, endAnglePx, fixedRad); offsetPx = PrairieGeom.vector2DAtAngle(anglePx).x(rPx); this._ctx.lineTo(offsetPx.e(1), offsetPx.e(2)); } this._ctx.stroke(); this._ctx.restore(); var arrowBaseRadiusPx = this._circleArrowRadius( radiusPx, arrowBaseAnglePx, startAnglePx, endAnglePx, fixedRad ); var arrowPosPx = posPx.add(PrairieGeom.vector2DAtAngle(endAnglePx).x(endRadiusPx)); var arrowBasePosPx = posPx.add( PrairieGeom.vector2DAtAngle(arrowBaseAnglePx).x(arrowBaseRadiusPx) ); var arrowDirPx = arrowPosPx.subtract(arrowBasePosPx); var arrowPosDw = this.pos2Dw(arrowPosPx); var arrowDirDw = this.vec2Dw(arrowDirPx); this._arrowhead(arrowPosDw, arrowDirDw, arrowheadLengthPx); this.restore(); }; /** @private Compute the radius at a certain angle within a circle arrow. @param {number} midRadPx The radius at the midpoint of the circle arrow. @param {number} anglePx The angle at which to find the radius. @param {number} startAnglePx The starting angle (counterclockwise from x axis, in radians). @param {number} endAnglePx The ending angle (counterclockwise from x axis, in radians). @return {number} The radius at the given angle (pixel coords). @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype._circleArrowRadius = function ( midRadPx, anglePx, startAnglePx, endAnglePx, fixedRad ) { if (fixedRad !== undefined && fixedRad === true) { return midRadPx; } if (Math.abs(endAnglePx - startAnglePx) < 1e-4) { return midRadPx; } var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; /* jshint laxbreak: true */ var spacingPx = arrowheadMaxLengthPx * this._props.arrowheadWidthRatio * this._props.circleArrowWrapOffsetRatio; var circleArrowWrapDensity = (midRadPx * Math.PI * 2) / spacingPx; var midAnglePx = (startAnglePx + endAnglePx) / 2; var offsetAnglePx = (anglePx - midAnglePx) * PrairieGeom.sign(endAnglePx - startAnglePx); if (offsetAnglePx > 0) { return midRadPx * (1 + offsetAnglePx / circleArrowWrapDensity); } else { return midRadPx * Math.exp(offsetAnglePx / circleArrowWrapDensity); } }; /*****************************************************************************/ /** Draw an arc in 3D. @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). @param {string} type (Optional) The type of the line. @param {Object} options (Optional) Various options. */ PrairieDraw.prototype.arc3D = function ( posDw, radDw, normDw, refDw, startAngleDw, endAngleDw, options ) { posDw = this.pos2To3(posDw); normDw = normDw === undefined ? Vector.k : normDw; refDw = refDw === undefined ? PrairieGeom.chooseNormVec(normDw) : refDw; var fullCircle = startAngleDw === undefined && endAngleDw === undefined; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; options = options === undefined ? {} : options; var idealSegmentSize = options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize); var points = []; var theta, p; for (var i = 0; i <= numSegments; i++) { theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments); p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); points.push(this.pos3To2(p)); } if (fullCircle) { points.pop(); this.polyLine(points, true, false); } else { this.polyLine(points); } }; /*****************************************************************************/ /** Draw a circle arrow in 3D. @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). @param {string} type (Optional) The type of the line. @param {Object} options (Optional) Various options. */ PrairieDraw.prototype.circleArrow3D = function ( posDw, radDw, normDw, refDw, startAngleDw, endAngleDw, type, options ) { posDw = this.pos2To3(posDw); normDw = normDw || Vector.k; refDw = refDw || Vector.i; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; options = options === undefined ? {} : options; var idealSegmentSize = options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize); var points = []; var theta, p; for (var i = 0; i <= numSegments; i++) { theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments); p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); points.push(this.pos3To2(p)); } this.polyLineArrow(points, type); }; /** Label a circle line in 3D. @param {string} labelText The label text. @param {Vector} labelAnchor The label anchor (first coord -1 to 1 along the line, second -1 to 1 transverse). @param {Vector} posDw The center of the arc. @param {number} radDw The radius of the arc. @param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). */ PrairieDraw.prototype.labelCircleLine3D = function ( labelText, labelAnchor, posDw, radDw, normDw, refDw, startAngleDw, endAngleDw ) { if (labelText === undefined) { return; } posDw = this.pos2To3(posDw); normDw = normDw || Vector.k; refDw = refDw || Vector.i; startAngleDw = startAngleDw === undefined ? 0 : startAngleDw; endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw; var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector(); var vDw = normDw.toUnitVector().cross(uDw); var theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, (labelAnchor.e(1) + 1) / 2); var p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta))); var p2Dw = this.pos3To2(p); var t3Dw = uDw.x(-Math.sin(theta)).add(vDw.x(Math.cos(theta))); var n3Dw = uDw.x(Math.cos(theta)).add(vDw.x(Math.sin(theta))); var t2Px = this.vec2Px(this.vec3To2(t3Dw, p)); var n2Px = this.vec2Px(this.vec3To2(n3Dw, p)); n2Px = PrairieGeom.orthComp(n2Px, t2Px); t2Px = t2Px.toUnitVector(); n2Px = n2Px.toUnitVector(); var oPx = t2Px.x(labelAnchor.e(1)).add(n2Px.x(labelAnchor.e(2))); var oDw = this.vec2Dw(oPx); var aDw = oDw.x(-1).toUnitVector(); var anchor = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(labelAnchor.max())); this.text(p2Dw, anchor, labelText); }; /*****************************************************************************/ /** Draw a sphere. @param {Vector} posDw Position of the sphere center. @param {number} radDw Radius of the sphere. @param {bool} filled (Optional) Whether to fill the sphere (default: false). */ PrairieDraw.prototype.sphere = function (posDw, radDw, filled) { filled = filled === undefined ? false : filled; var posVw = this.posDwToVw(posDw); var edgeDw = posDw.add($V([radDw, 0, 0])); var edgeVw = this.posDwToVw(edgeDw); var radVw = edgeVw.subtract(posVw).modulus(); var posDw2 = PrairieGeom.orthProjPos3D(posVw); this.circle(posDw2, radVw, filled); }; /** Draw a circular slice on a sphere. @param {Vector} posDw Position of the sphere center. @param {number} radDw Radius of the sphere. @param {Vector} normDw Normal vector to the circle. @param {number} distDw Distance from sphere center to circle center along normDw. @param {string} drawBack (Optional) Whether to draw the back line (default: true). @param {string} drawFront (Optional) Whether to draw the front line (default: true). @param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw). @param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0). @param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi). */ PrairieDraw.prototype.sphereSlice = function ( posDw, radDw, normDw, distDw, drawBack, drawFront, refDw, startAngleDw, endAngleDw ) { var cRDwSq = radDw * radDw - distDw * distDw; if (cRDwSq <= 0) { return; } var cRDw = Math.sqrt(cRDwSq); var circlePosDw = posDw.add(normDw.toUnitVector().x(distDw)); drawBack = drawBack === undefined ? true : drawBack; drawFront = drawFront === undefined ? true : drawFront; var normVw = this.vecDwToVw(normDw); if (PrairieGeom.orthComp(Vector.k, normVw).modulus() < 1e-10) { // looking straight down on the circle if (distDw > 0) { // front side, completely visible this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); } else if (distDw < 0) { // back side, completely invisible this.save(); this.setShapeDrawHidden(); this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); this.restore(); } // if distDw == 0 then it's a great circle, don't draw it return; } var refVw; if (refDw === undefined) { refVw = PrairieGeom.orthComp(Vector.k, normVw); refDw = this.vecVwToDw(refVw); } refVw = this.vecDwToVw(refDw); var uVw = refVw.toUnitVector(); var vVw = normVw.toUnitVector().cross(uVw); var dVw = this.vecDwToVw(normDw.toUnitVector().x(distDw)); var cRVw = this.vecDwToVw(refDw.toUnitVector().x(cRDw)).modulus(); var A = -dVw.e(3); var B = uVw.e(3) * cRVw; var C = vVw.e(3) * cRVw; var BCMag = Math.sqrt(B * B + C * C); var AN = A / BCMag; var phi = Math.atan2(C, B); if (AN <= -1) { // only front if (drawFront) { this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); } } else if (AN >= 1) { // only back if (drawBack && this._props.hiddenLineDraw) { this.save(); this.setShapeDrawHidden(); this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw); this.restore(); } } else { // front and back var acosAN = Math.acos(AN); var theta1 = phi + acosAN; var theta2 = phi + 2 * Math.PI - acosAN; var i, intersections, range; if (drawBack && this._props.hiddenLineDraw) { this.save(); this.setShapeDrawHidden(); if (theta2 > theta1) { if (startAngleDw === undefined || endAngleDw === undefined) { this.arc3D(circlePosDw, cRDw, normDw, refDw, theta1, theta2); } else { intersections = PrairieGeom.intersectAngleRanges( [theta1, theta2], [startAngleDw, endAngleDw] ); for (i = 0; i < intersections.length; i++) { range = intersections[i]; this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]); } } } this.restore(); } if (drawFront) { if (startAngleDw === undefined || endAngleDw === undefined) { this.arc3D(circlePosDw, cRDw, normDw, refDw, theta2, theta1 + 2 * Math.PI); } else { intersections = PrairieGeom.intersectAngleRanges( [theta2, theta1 + 2 * Math.PI], [startAngleDw, endAngleDw] ); for (i = 0; i < intersections.length; i++) { range = intersections[i]; this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]); } } } } }; /*****************************************************************************/ /** Label an angle with an inset label. @param {Vector} pos The corner position. @param {Vector} p1 Position of first other point. @param {Vector} p2 Position of second other point. @param {string} label The label text. */ PrairieDraw.prototype.labelAngle = function (pos, p1, p2, label) { pos = this.pos3To2(pos); p1 = this.pos3To2(p1); p2 = this.pos3To2(p2); var v1 = p1.subtract(pos); var v2 = p2.subtract(pos); var vMid = v1.add(v2).x(0.5); var anchor = vMid.x(-1.8 / PrairieGeom.supNorm(vMid)); this.text(pos, anchor, label); }; /*****************************************************************************/ /** Draw an arc. @param {Vector} centerDw The center of the circle. @param {Vector} radiusDw The radius of the circle (or major axis for ellipses). @param {number} startAngle (Optional) The start angle of the arc (radians, default: 0). @param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi). @param {bool} filled (Optional) Whether to fill the arc (default: false). @param {Number} aspect (Optional) The aspect ratio (major / minor) (default: 1). */ PrairieDraw.prototype.arc = function (centerDw, radiusDw, startAngle, endAngle, filled, aspect) { startAngle = startAngle === undefined ? 0 : startAngle; endAngle = endAngle === undefined ? 2 * Math.PI : endAngle; filled = filled === undefined ? false : filled; aspect = aspect === undefined ? 1 : aspect; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); var anglePx = PrairieGeom.angleOf(offsetPx); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.save(); this._ctx.translate(centerPx.e(1), centerPx.e(2)); this._ctx.rotate(anglePx); this._ctx.scale(1, 1 / aspect); this._ctx.beginPath(); this._ctx.arc(0, 0, radiusPx, -endAngle, -startAngle); this._ctx.restore(); if (filled) { this._ctx.fill(); } this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a polyLine (closed or open). @param {Array} pointsDw A list of drawing coordinates that form the polyLine. @param {bool} closed (Optional) Whether the shape should be closed (default: false). @param {bool} filled (Optional) Whether the shape should be filled (default: true). */ PrairieDraw.prototype.polyLine = function (pointsDw, closed, filled) { if (pointsDw.length < 2) { return; } this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.beginPath(); var pDw = this.pos3To2(pointsDw[0]); var pPx = this.pos2Px(pDw); this._ctx.moveTo(pPx.e(1), pPx.e(2)); for (var i = 1; i < pointsDw.length; i++) { pDw = this.pos3To2(pointsDw[i]); pPx = this.pos2Px(pDw); this._ctx.lineTo(pPx.e(1), pPx.e(2)); } if (closed !== undefined && closed === true) { this._ctx.closePath(); if (filled === undefined || filled === true) { this._ctx.fill(); } } this._ctx.stroke(); this._ctx.restore(); }; /** Draw a polyLine arrow. @param {Array} pointsDw A list of drawing coordinates that form the polyLine. */ PrairieDraw.prototype.polyLineArrow = function (pointsDw, type) { if (pointsDw.length < 2) { return; } // convert the line to pixel coords and find its length var pointsPx = []; var i; var polyLineLengthPx = 0; for (i = 0; i < pointsDw.length; i++) { pointsPx.push(this.pos2Px(this.pos3To2(pointsDw[i]))); if (i > 0) { polyLineLengthPx += pointsPx[i].subtract(pointsPx[i - 1]).modulus(); } } // shorten the line to fit the arrowhead, dropping points and moving the last point var drawArrowHead, arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx; if (polyLineLengthPx < 1) { // if too short, don't draw the arrowhead drawArrowHead = false; } else { drawArrowHead = true; var arrowheadMaxLengthPx = this._props.arrowheadLengthRatio * this._props.arrowLineWidthPx; arrowheadLengthPx = Math.min(arrowheadMaxLengthPx, polyLineLengthPx / 2); var arrowheadCenterLengthPx = (1 - this._props.arrowheadOffsetRatio) * arrowheadLengthPx; var lengthToRemovePx = arrowheadCenterLengthPx; i = pointsPx.length - 1; arrowheadEndPx = pointsPx[i]; var segmentLengthPx; while (i > 0) { segmentLengthPx = pointsPx[i].subtract(pointsPx[i - 1]).modulus(); if (lengthToRemovePx > segmentLengthPx) { lengthToRemovePx -= segmentLengthPx; pointsPx.pop(); i--; } else { pointsPx[i] = PrairieGeom.linearInterpVector( pointsPx[i], pointsPx[i - 1], lengthToRemovePx / segmentLengthPx ); break; } } var arrowheadBasePx = pointsPx[i]; arrowheadOffsetPx = arrowheadEndPx.subtract(arrowheadBasePx); } // draw the line this._ctx.save(); this._ctx.lineWidth = this._props.arrowLineWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern)); this._setLineStyles(type); this._ctx.beginPath(); var pPx = pointsPx[0]; this._ctx.moveTo(pPx.e(1), pPx.e(2)); for (i = 1; i < pointsPx.length; i++) { pPx = pointsPx[i]; this._ctx.lineTo(pPx.e(1), pPx.e(2)); } this._ctx.stroke(); // draw the arrowhead if (drawArrowHead) { i = pointsPx[i]; this._arrowheadPx(arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx); } this._ctx.restore(); }; /*****************************************************************************/ /** Draw a circle. @param {Vector} centerDw The center in drawing coords. @param {number} radiusDw the radius in drawing coords. @param {bool} filled (Optional) Whether to fill the circle (default: true). */ PrairieDraw.prototype.circle = function (centerDw, radiusDw, filled) { filled = filled === undefined ? true : filled; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI); if (filled) { this._ctx.fill(); } this._ctx.stroke(); this._ctx.restore(); }; /** Draw a filled circle. @param {Vector} centerDw The center in drawing coords. @param {number} radiusDw the radius in drawing coords. */ PrairieDraw.prototype.filledCircle = function (centerDw, radiusDw) { var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); this._ctx.save(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.fillStyle = this._props.shapeOutlineColor; this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI); this._ctx.fill(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw a triagular distributed load @param {Vector} startDw The first point (in drawing coordinates) of the distributed load @param {Vector} endDw The end point (in drawing coordinates) of the distributed load @param {number} sizeStartDw length of the arrow at startDw @param {number} sizeEndDw length of the arrow at endDw @param {string} label the arrow size at startDw @param {string} label the arrow size at endDw @param {boolean} true if arrow heads are towards the line that connects points startDw and endDw, opposite direction if false @param {boolean} true if arrow points up (positive y-axis), false otherwise */ PrairieDraw.prototype.triangularDistributedLoad = function ( startDw, endDw, sizeStartDw, sizeEndDw, labelStart, labelEnd, arrowToLine, arrowDown ) { var LengthDw = endDw.subtract(startDw); var L = LengthDw.modulus(); if (arrowDown) { var sizeStartDwSign = sizeStartDw; var sizeEndDwSign = sizeEndDw; } else { var sizeStartDwSign = -sizeStartDw; var sizeEndDwSign = -sizeEndDw; } var nSpaces = Math.ceil((2 * L) / sizeStartDw); var spacing = L / nSpaces; var inc = 0; this.save(); this.setProp('shapeOutlineColor', 'rgb(255,0,0)'); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); if (arrowToLine) { this.line(startDw.add($V([0, sizeStartDwSign])), endDw.add($V([0, sizeEndDwSign]))); var startArrow = startDw.add($V([0, sizeStartDwSign])); var endArrow = startDw; for (i = 0; i <= nSpaces; i++) { this.arrow( startArrow.add($V([inc, (inc * (sizeEndDwSign - sizeStartDwSign)) / L])), endArrow.add($V([inc, 0])) ); inc = inc + spacing; } this.text(startArrow, $V([2, 0]), labelStart); this.text( startArrow.add( $V([inc - spacing, ((inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L]) ), $V([-2, 0]), labelEnd ); } else { this.line(startDw, endDw); var startArrow = startDw; var endArrow = startDw.subtract($V([0, sizeStartDwSign])); for (i = 0; i <= nSpaces; i++) { this.arrow( startArrow.add($V([inc, 0])), endArrow.add($V([inc, (-inc * (sizeEndDwSign - sizeStartDwSign)) / L])) ); inc = inc + spacing; } this.text(endArrow, $V([2, 0]), labelStart); this.text( endArrow.add( $V([inc - spacing, (-(inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L]) ), $V([-2, 0]), labelEnd ); } this.restore(); }; /*****************************************************************************/ /** Draw a rod with hinge points at start and end and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} startDw The second hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.rod = function (startDw, endDw, widthDw) { var offsetLengthDw = endDw.subtract(startDw); var offsetWidthDw = offsetLengthDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var offsetLengthPx = this.vec2Px(offsetLengthDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthPx = offsetLengthPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx); this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a L-shape rod with hinge points at start, center and end, and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} centerDw The second hinge point (drawing coordinates). @param {Vector} endDw The third hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.LshapeRod = function (startDw, centerDw, endDw, widthDw) { var offsetLength1Dw = centerDw.subtract(startDw); var offsetLength2Dw = endDw.subtract(centerDw); var offsetWidthDw = offsetLength1Dw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var centerPx = this.pos2Px(centerDw); var endPx = this.pos2Px(endDw); var offsetLength1Px = this.vec2Px(offsetLength1Dw); var offsetLength2Px = this.vec2Px(offsetLength2Dw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var length1Px = offsetLength1Px.modulus(); var length2Px = offsetLength2Px.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLength1Px)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); var beta = -PrairieGeom.angleFrom(offsetLength1Px, offsetLength2Px); var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta); var y1 = rPx; var x2 = length1Px + length2Px * Math.cos(beta); var y2 = -length2Px * Math.sin(beta); var x3 = x2 + rPx * Math.sin(beta); var y3 = y2 + rPx * Math.cos(beta); var x4 = x3 + rPx * Math.cos(beta); var y4 = y3 - rPx * Math.sin(beta); var x5 = x2 + rPx * Math.cos(beta); var y5 = y2 - rPx * Math.sin(beta); var x6 = x5 - rPx * Math.sin(beta); var y6 = y5 - rPx * Math.cos(beta); var x7 = length1Px - rPx / Math.sin(beta) + rPx / Math.tan(beta); var y7 = -rPx; this._ctx.arcTo(x1, y1, x3, y3, rPx); this._ctx.arcTo(x4, y4, x5, y5, rPx); this._ctx.arcTo(x6, y6, x7, y7, rPx); this._ctx.arcTo(x7, y7, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a T-shape rod with hinge points at start, center, center-end and end, and the given width. @param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates. @param {Vector} centerDw The second hinge point (drawing coordinates). @param {Vector} endDw The third hinge point (drawing coordinates). @param {Vector} centerEndDw The fourth hinge point (drawing coordinates). @param {number} widthDw The width of the rod (drawing coordinates). */ PrairieDraw.prototype.TshapeRod = function (startDw, centerDw, endDw, centerEndDw, widthDw) { var offsetStartRodDw = centerDw.subtract(startDw); var offsetEndRodDw = endDw.subtract(centerDw); var offsetCenterRodDw = centerEndDw.subtract(centerDw); var offsetWidthDw = offsetStartRodDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var startPx = this.pos2Px(startDw); var centerPx = this.pos2Px(centerDw); var endPx = this.pos2Px(endDw); var offsetStartRodPx = this.vec2Px(offsetStartRodDw); var offsetEndRodPx = this.vec2Px(offsetEndRodDw); var offsetCenterRodPx = this.vec2Px(offsetCenterRodDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthStartRodPx = offsetStartRodPx.modulus(); var lengthEndRodPx = offsetEndRodPx.modulus(); var lengthCenterRodPx = offsetCenterRodPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetStartRodPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); var angleStartToEnd = PrairieGeom.angleFrom(offsetStartRodPx, offsetEndRodPx); var angleEndToCenter = PrairieGeom.angleFrom(offsetEndRodPx, offsetCenterRodPx); if (Math.abs(angleEndToCenter) < Math.PI) { var length1Px = lengthStartRodPx; var length2Px = lengthEndRodPx; var length3Px = lengthCenterRodPx; var beta = -angleStartToEnd; var alpha = -angleEndToCenter; } else { var length1Px = lengthStartRodPx; var length2Px = lengthCenterRodPx; var length3Px = lengthEndRodPx; var beta = -PrairieGeom.angleFrom(offsetStartRodPx, offsetCenterRodPx); var alpha = angleEndToCenter; } var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta); var y1 = rPx; var x2 = length1Px + length2Px * Math.cos(beta); var y2 = -length2Px * Math.sin(beta); var x3 = x2 + rPx * Math.sin(beta); var y3 = y2 + rPx * Math.cos(beta); var x4 = x3 + rPx * Math.cos(beta); var y4 = y3 - rPx * Math.sin(beta); var x5 = x2 + rPx * Math.cos(beta); var y5 = y2 - rPx * Math.sin(beta); var x6 = x5 - rPx * Math.sin(beta); var y6 = y5 - rPx * Math.cos(beta); var x7 = length1Px + rPx * Math.cos(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta)); var y7 = -rPx / Math.cos(beta) - rPx * Math.sin(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta)); var x8 = length1Px + length3Px * Math.cos(beta + alpha); var y8 = -length3Px * Math.sin(beta + alpha); var x9 = x8 + rPx * Math.sin(beta + alpha); var y9 = y8 + rPx * Math.cos(beta + alpha); var x10 = x9 + rPx * Math.cos(beta + alpha); var y10 = y9 - rPx * Math.sin(beta + alpha); var x11 = x8 + rPx * Math.cos(beta + alpha); var y11 = y8 - rPx * Math.sin(beta + alpha); var x12 = x11 - rPx * Math.sin(beta + alpha); var y12 = y11 - rPx * Math.cos(beta + alpha); var x13 = length1Px - rPx / Math.sin(beta + alpha) + rPx / Math.tan(beta + alpha); var y13 = -rPx; this._ctx.arcTo(x1, y1, x3, y3, rPx); this._ctx.arcTo(x4, y4, x5, y5, rPx); this._ctx.arcTo(x6, y6, x7, y7, rPx); this._ctx.arcTo(x7, y7, x9, y9, rPx); this._ctx.arcTo(x10, y10, x11, y11, rPx); this._ctx.arcTo(x12, y12, x13, y13, rPx); this._ctx.arcTo(x13, y13, 0, -rPx, rPx); this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx); this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx); if (this._props.shapeInsideColor !== 'none') { this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); } this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a pivot. @param {Vector} baseDw The center of the base (drawing coordinates). @param {Vector} hingeDw The hinge point (center of circular end) in drawing coordinates. @param {number} widthDw The width of the pivot (drawing coordinates). */ PrairieDraw.prototype.pivot = function (baseDw, hingeDw, widthDw) { var offsetLengthDw = hingeDw.subtract(baseDw); var offsetWidthDw = offsetLengthDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(widthDw); var basePx = this.pos2Px(baseDw); var offsetLengthPx = this.vec2Px(offsetLengthDw); var offsetWidthPx = this.vec2Px(offsetWidthDw); var lengthPx = offsetLengthPx.modulus(); var rPx = offsetWidthPx.modulus() / 2; this._ctx.save(); this._ctx.translate(basePx.e(1), basePx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx)); this._ctx.beginPath(); this._ctx.moveTo(0, rPx); this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx); this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx); this._ctx.lineTo(0, -rPx); this._ctx.closePath(); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a square with a given base point and center. @param {Vector} baseDw The mid-point of the base (drawing coordinates). @param {Vector} centerDw The center of the square (drawing coordinates). */ PrairieDraw.prototype.square = function (baseDw, centerDw) { var basePx = this.pos2Px(baseDw); var centerPx = this.pos2Px(centerDw); var offsetPx = centerPx.subtract(basePx); var rPx = offsetPx.modulus(); this._ctx.save(); this._ctx.translate(basePx.e(1), basePx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetPx)); this._ctx.beginPath(); this._ctx.rect(0, -rPx, 2 * rPx, 2 * rPx); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.shapeOutlineColor; this._ctx.fillStyle = this._props.shapeInsideColor; this._ctx.fill(); this._ctx.stroke(); this._ctx.restore(); }; /** Draw an axis-aligned rectangle with a given width and height, centered at the origin. @param {number} widthDw The width of the rectangle. @param {number} heightDw The height of the rectangle. @param {number} centerDw Optional: The center of the rectangle (default: the origin). @param {number} angleDw Optional: The rotation angle of the rectangle (default: zero). @param {bool} filled Optional: Whether to fill the rectangle (default: true). */ PrairieDraw.prototype.rectangle = function (widthDw, heightDw, centerDw, angleDw, filled) { centerDw = centerDw === undefined ? $V([0, 0]) : centerDw; angleDw = angleDw === undefined ? 0 : angleDw; var pointsDw = [ $V([-widthDw / 2, -heightDw / 2]), $V([widthDw / 2, -heightDw / 2]), $V([widthDw / 2, heightDw / 2]), $V([-widthDw / 2, heightDw / 2]), ]; var closed = true; filled = filled === undefined ? true : filled; this.save(); this.translate(centerDw); this.rotate(angleDw); this.polyLine(pointsDw, closed, filled); this.restore(); }; /** Draw a rectangle with the given corners and height. @param {Vector} pos1Dw First corner of the rectangle. @param {Vector} pos2Dw Second corner of the rectangle. @param {number} heightDw The height of the rectangle. */ PrairieDraw.prototype.rectangleGeneric = function (pos1Dw, pos2Dw, heightDw) { var dDw = PrairieGeom.perp(pos2Dw.subtract(pos1Dw)).toUnitVector().x(heightDw); var pointsDw = [pos1Dw, pos2Dw, pos2Dw.add(dDw), pos1Dw.add(dDw)]; var closed = true; this.polyLine(pointsDw, closed); }; /** Draw a ground element. @param {Vector} posDw The position of the ground center (drawing coordinates). @param {Vector} normDw The outward normal (drawing coordinates). @param (number} lengthDw The total length of the ground segment. */ PrairieDraw.prototype.ground = function (posDw, normDw, lengthDw) { var tangentDw = normDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(lengthDw); var posPx = this.pos2Px(posDw); var normPx = this.vec2Px(normDw); var tangentPx = this.vec2Px(tangentDw); var lengthPx = tangentPx.modulus(); var groundDepthPx = Math.min(lengthPx, this._props.groundDepthPx); this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(normPx) - Math.PI / 2); this._ctx.beginPath(); this._ctx.rect(-lengthPx / 2, -groundDepthPx, lengthPx, groundDepthPx); this._ctx.fillStyle = this._props.groundInsideColor; this._ctx.fill(); this._ctx.beginPath(); this._ctx.moveTo(-lengthPx / 2, 0); this._ctx.lineTo(lengthPx / 2, 0); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a ground element with hashed shading. @param {Vector} posDw The position of the ground center (drawing coords). @param {Vector} normDw The outward normal (drawing coords). @param (number} lengthDw The total length of the ground segment (drawing coords). @param {number} offsetDw (Optional) The offset of the shading (drawing coords). */ PrairieDraw.prototype.groundHashed = function (posDw, normDw, lengthDw, offsetDw) { offsetDw = offsetDw === undefined ? 0 : offsetDw; var tangentDw = normDw .rotate(Math.PI / 2, $V([0, 0])) .toUnitVector() .x(lengthDw); var offsetVecDw = tangentDw.toUnitVector().x(offsetDw); var posPx = this.pos2Px(posDw); var normPx = this.vec2Px(normDw); var tangentPx = this.vec2Px(tangentDw); var lengthPx = tangentPx.modulus(); var offsetVecPx = this.vec2Px(offsetVecDw); var offsetPx = offsetVecPx.modulus() * PrairieGeom.sign(offsetDw); this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(normPx) + Math.PI / 2); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.beginPath(); this._ctx.moveTo(-lengthPx / 2, 0); this._ctx.lineTo(lengthPx / 2, 0); this._ctx.stroke(); var startX = offsetPx % this._props.groundSpacingPx; var x = startX; while (x < lengthPx / 2) { this._ctx.beginPath(); this._ctx.moveTo(x, 0); this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx); this._ctx.stroke(); x += this._props.groundSpacingPx; } x = startX - this._props.groundSpacingPx; while (x > -lengthPx / 2) { this._ctx.beginPath(); this._ctx.moveTo(x, 0); this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx); this._ctx.stroke(); x -= this._props.groundSpacingPx; } this._ctx.restore(); }; /** Draw an arc ground element. @param {Vector} centerDw The center of the circle. @param {Vector} radiusDw The radius of the circle. @param {number} startAngle (Optional) The start angle of the arc (radians, default: 0). @param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi). @param {bool} outside (Optional) Whether to draw the ground outside the curve (default: true). */ PrairieDraw.prototype.arcGround = function (centerDw, radiusDw, startAngle, endAngle, outside) { startAngle = startAngle === undefined ? 0 : startAngle; endAngle = endAngle === undefined ? 2 * Math.PI : endAngle; outside = outside === undefined ? true : outside; var centerPx = this.pos2Px(centerDw); var offsetDw = $V([radiusDw, 0]); var offsetPx = this.vec2Px(offsetDw); var radiusPx = offsetPx.modulus(); var groundDepthPx = Math.min(radiusPx, this._props.groundDepthPx); var groundOffsetPx = outside ? groundDepthPx : -groundDepthPx; this._ctx.save(); // fill the shaded area this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle, false); this._ctx.arc( centerPx.e(1), centerPx.e(2), radiusPx + groundOffsetPx, -startAngle, -endAngle, true ); this._ctx.fillStyle = this._props.groundInsideColor; this._ctx.fill(); // draw the ground surface this._ctx.beginPath(); this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle); this._ctx.lineWidth = this._props.shapeStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern)); this._ctx.strokeStyle = this._props.groundOutlineColor; this._ctx.stroke(); this._ctx.restore(); }; /** Draw a center-of-mass object. @param {Vector} posDw The position of the center of mass. */ PrairieDraw.prototype.centerOfMass = function (posDw) { var posPx = this.pos2Px(posDw); var r = this._props.centerOfMassRadiusPx; this._ctx.save(); this._ctx.lineWidth = this._props.centerOfMassStrokeWidthPx; this._ctx.strokeStyle = this._props.centerOfMassColor; this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.beginPath(); this._ctx.moveTo(-r, 0); this._ctx.lineTo(r, 0); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(0, -r); this._ctx.lineTo(0, r); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.arc(0, 0, r, 0, 2 * Math.PI); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a measurement line. @param {Vector} startDw The start position of the measurement. @param {Vector} endDw The end position of the measurement. @param {string} text The measurement label. */ PrairieDraw.prototype.measurement = function (startDw, endDw, text) { var startPx = this.pos2Px(startDw); var endPx = this.pos2Px(endDw); var offsetPx = endPx.subtract(startPx); var d = offsetPx.modulus(); var h = this._props.measurementEndLengthPx; var o = this._props.measurementOffsetPx; this._ctx.save(); this._ctx.lineWidth = this._props.measurementStrokeWidthPx; this._ctx.setLineDash(this._dashPattern(this._props.measurementStrokePattern)); this._ctx.strokeStyle = this._props.measurementColor; this._ctx.translate(startPx.e(1), startPx.e(2)); this._ctx.rotate(PrairieGeom.angleOf(offsetPx)); this._ctx.beginPath(); this._ctx.moveTo(0, o); this._ctx.lineTo(0, o + h); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(d, o); this._ctx.lineTo(d, o + h); this._ctx.stroke(); this._ctx.beginPath(); this._ctx.moveTo(0, o + h / 2); this._ctx.lineTo(d, o + h / 2); this._ctx.stroke(); this._ctx.restore(); var orthPx = offsetPx .rotate(-Math.PI / 2, $V([0, 0])) .toUnitVector() .x(-o - h / 2); var lineStartPx = startPx.add(orthPx); var lineEndPx = endPx.add(orthPx); var lineStartDw = this.pos2Dw(lineStartPx); var lineEndDw = this.pos2Dw(lineEndPx); this.labelLine(lineStartDw, lineEndDw, $V([0, -1]), text); }; /** Draw a right angle. @param {Vector} posDw The position angle point. @param {Vector} dirDw The baseline direction (angle is counter-clockwise from this direction in 2D). @param {Vector} normDw (Optional) The third direction (required for 3D). */ PrairieDraw.prototype.rightAngle = function (posDw, dirDw, normDw) { if (dirDw.modulus() < 1e-20) { return; } var posPx, dirPx, normPx; if (posDw.elements.length === 3) { posPx = this.pos2Px(this.pos3To2(posDw)); var d = this.vec2To3(this.vec2Dw($V([this._props.rightAngleSizePx, 0]))).modulus(); dirPx = this.vec2Px(this.vec3To2(dirDw.toUnitVector().x(d), posDw)); normPx = this.vec2Px(this.vec3To2(normDw.toUnitVector().x(d), posDw)); } else { posPx = this.pos2Px(posDw); dirPx = this.vec2Px(dirDw).toUnitVector().x(this._props.rightAngleSizePx); if (normDw !== undefined) { normPx = this.vec2Px(normDw).toUnitVector().x(this._props.rightAngleSizePx); } else { normPx = dirPx.rotate(-Math.PI / 2, $V([0, 0])); } } this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.lineWidth = this._props.rightAngleStrokeWidthPx; this._ctx.strokeStyle = this._props.rightAngleColor; this._ctx.beginPath(); this._ctx.moveTo(dirPx.e(1), dirPx.e(2)); this._ctx.lineTo(dirPx.e(1) + normPx.e(1), dirPx.e(2) + normPx.e(2)); this._ctx.lineTo(normPx.e(1), normPx.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /** Draw a right angle (improved version). @param {Vector} p0Dw The base point. @param {Vector} p1Dw The first other point. @param {Vector} p2Dw The second other point. */ PrairieDraw.prototype.rightAngleImproved = function (p0Dw, p1Dw, p2Dw) { var p0Px = this.pos2Px(this.pos3To2(p0Dw)); var p1Px = this.pos2Px(this.pos3To2(p1Dw)); var p2Px = this.pos2Px(this.pos3To2(p2Dw)); var d1Px = p1Px.subtract(p0Px); var d2Px = p2Px.subtract(p0Px); var minDLen = Math.min(d1Px.modulus(), d2Px.modulus()); if (minDLen < 1e-10) { return; } var rightAngleSizePx = Math.min(minDLen / 2, this._props.rightAngleSizePx); d1Px = d1Px.toUnitVector().x(rightAngleSizePx); d2Px = d2Px.toUnitVector().x(rightAngleSizePx); p1Px = p0Px.add(d1Px); p2Px = p0Px.add(d2Px); var p12Px = p1Px.add(d2Px); this._ctx.save(); this._ctx.lineWidth = this._props.rightAngleStrokeWidthPx; this._ctx.strokeStyle = this._props.rightAngleColor; this._ctx.beginPath(); this._ctx.moveTo(p1Px.e(1), p1Px.e(2)); this._ctx.lineTo(p12Px.e(1), p12Px.e(2)); this._ctx.lineTo(p2Px.e(1), p2Px.e(2)); this._ctx.stroke(); this._ctx.restore(); }; /*****************************************************************************/ /** Draw text. @param {Vector} posDw The position to draw at. @param {Vector} anchor The anchor on the text that will be located at pos (in -1 to 1 local coordinates). @param {string} text The text to draw. If text begins with "TEX:" then it is interpreted as LaTeX. @param {bool} boxed (Optional) Whether to draw a white box behind the text (default: false). @param {Number} angle (Optional) The rotation angle (radians, default: 0). */ PrairieDraw.prototype.text = function (posDw, anchor, text, boxed, angle) { if (text === undefined) { return; } boxed = boxed === undefined ? false : boxed; angle = angle === undefined ? 0 : angle; var posPx = this.pos2Px(this.pos3To2(posDw)); var offsetPx; if (text.length >= 4 && text.slice(0, 4) === 'TEX:') { var texText = text.slice(4); var hash = Sha1.hash(texText); this._texts = this._texts || {}; var img; if (hash in this._texts) { img = this._texts[hash]; var xPx = (-(anchor.e(1) + 1) / 2) * img.width; var yPx = ((anchor.e(2) - 1) / 2) * img.height; //var offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx); offsetPx = anchor.x(this._props.textOffsetPx); var textBorderPx = 5; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.rotate(angle); if (boxed) { this._ctx.save(); this._ctx.fillStyle = 'white'; this._ctx.fillRect( xPx - offsetPx.e(1) - textBorderPx, yPx + offsetPx.e(2) - textBorderPx, img.width + 2 * textBorderPx, img.height + 2 * textBorderPx ); this._ctx.restore(); } this._ctx.drawImage(img, xPx - offsetPx.e(1), yPx + offsetPx.e(2)); this._ctx.restore(); } else { var imgSrc = 'text/' + hash + '.png'; img = new Image(); var that = this; img.onload = function () { that.redraw(); if (that.trigger) { that.trigger('imgLoad'); } }; img.src = imgSrc; this._texts[hash] = img; } } else { var align, baseline, bbRelOffset; /* jshint indent: false */ switch (PrairieGeom.sign(anchor.e(1))) { case -1: align = 'left'; bbRelOffset = 0; break; case 0: align = 'center'; bbRelOffset = 0.5; break; case 1: align = 'right'; bbRelOffset = 1; break; } switch (PrairieGeom.sign(anchor.e(2))) { case -1: baseline = 'bottom'; break; case 0: baseline = 'middle'; break; case 1: baseline = 'top'; break; } this.save(); this._ctx.textAlign = align; this._ctx.textBaseline = baseline; this._ctx.translate(posPx.e(1), posPx.e(2)); offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx); var drawPx = $V([-offsetPx.e(1), offsetPx.e(2)]); var metrics = this._ctx.measureText(text); var d = this._props.textOffsetPx; //var bb0 = drawPx.add($V([-metrics.actualBoundingBoxLeft - d, -metrics.actualBoundingBoxAscent - d])); //var bb1 = drawPx.add($V([metrics.actualBoundingBoxRight + d, metrics.actualBoundingBoxDescent + d])); var textHeight = this._props.textFontSize; var bb0 = drawPx.add($V([-bbRelOffset * metrics.width - d, -d])); var bb1 = drawPx.add($V([(1 - bbRelOffset) * metrics.width + d, textHeight + d])); if (boxed) { this._ctx.save(); this._ctx.fillStyle = 'white'; this._ctx.fillRect(bb0.e(1), bb0.e(2), bb1.e(1) - bb0.e(1), bb1.e(2) - bb0.e(2)); this._ctx.restore(); } this._ctx.font = this._props.textFontSize.toString() + 'px serif'; this._ctx.fillText(text, drawPx.e(1), drawPx.e(2)); this.restore(); } }; /** Draw text to label a line. @param {Vector} startDw The start position of the line. @param {Vector} endDw The end position of the line. @param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal). @param {string} text The text to draw. @param {Vector} anchor (Optional) The anchor position on the text. */ PrairieDraw.prototype.labelLine = function (startDw, endDw, pos, text, anchor) { if (text === undefined) { return; } startDw = this.pos3To2(startDw); endDw = this.pos3To2(endDw); var midpointDw = startDw.add(endDw).x(0.5); var offsetDw = endDw.subtract(startDw).x(0.5); var pDw = midpointDw.add(offsetDw.x(pos.e(1))); var u1Dw = offsetDw.toUnitVector(); var u2Dw = u1Dw.rotate(Math.PI / 2, $V([0, 0])); var oDw = u1Dw.x(pos.e(1)).add(u2Dw.x(pos.e(2))); var a = oDw.x(-1).toUnitVector().x(Math.abs(pos.max())); if (anchor !== undefined) { a = anchor; } this.text(pDw, a, text); }; /** Draw text to label a circle line. @param {Vector} posDw The center of the circle line. @param {number} radDw The radius at the mid-angle. @param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians). @param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians). @param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal). @param {string} text The text to draw. @param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false). */ PrairieDraw.prototype.labelCircleLine = function ( posDw, radDw, startAngleDw, endAngleDw, pos, text, fixedRad ) { // convert to Px coordinates var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw); var posPx = this.pos2Px(posDw); var startOffsetPx = this.vec2Px(startOffsetDw); var radiusPx = startOffsetPx.modulus(); var startAnglePx = PrairieGeom.angleOf(startOffsetPx); var deltaAngleDw = endAngleDw - startAngleDw; // assume a possibly reflected/rotated but equally scaled Dw/Px transformation var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw; var endAnglePx = startAnglePx + deltaAnglePx; var textAnglePx = ((1.0 - pos.e(1)) / 2.0) * startAnglePx + ((1.0 + pos.e(1)) / 2.0) * endAnglePx; var u1Px = PrairieGeom.vector2DAtAngle(textAnglePx); var u2Px = u1Px.rotate(-Math.PI / 2, $V([0, 0])); var u1Dw = this.vec2Dw(u1Px).toUnitVector(); var u2Dw = this.vec2Dw(u2Px).toUnitVector(); var oDw = u1Dw.x(pos.e(2)).add(u2Dw.x(pos.e(1))); var aDw = oDw.x(-1).toUnitVector(); var a = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(pos.max())); var rPx = this._circleArrowRadius(radiusPx, textAnglePx, startAnglePx, endAnglePx, fixedRad); var pPx = u1Px.x(rPx).add(posPx); var pDw = this.pos2Dw(pPx); this.text(pDw, a, text); }; /** Find the anchor for the intersection of several lines. @param {Vector} labelPoint The point to be labeled. @param {Array} points The end of the lines that meet at labelPoint. @return {Vector} The anchor offset. */ PrairieDraw.prototype.findAnchorForIntersection = function (labelPointDw, pointsDw) { // find the angles on the unit circle for each of the lines var labelPointPx = this.pos2Px(this.pos3To2(labelPointDw)); var i, v; var angles = []; for (i = 0; i < pointsDw.length; i++) { v = this.pos2Px(this.pos3To2(pointsDw[i])).subtract(labelPointPx); v = $V([v.e(1), -v.e(2)]); if (v.modulus() > 1e-6) { angles.push(PrairieGeom.angleOf(v)); } } if (angles.length === 0) { return $V([1, 0]); } // save the first angle to tie-break later var tieBreakAngle = angles[0]; // find the biggest gap between angles (might be multiple) angles.sort(function (a, b) { return a - b; }); var maxAngleDiff = angles[0] - angles[angles.length - 1] + 2 * Math.PI; var maxIs = [0]; var angleDiff; for (i = 1; i < angles.length; i++) { angleDiff = angles[i] - angles[i - 1]; if (angleDiff > maxAngleDiff - 1e-6) { if (angleDiff > maxAngleDiff + 1e-6) { // we are clearly greater maxAngleDiff = angleDiff; maxIs = [i]; } else { // we are basically equal maxIs.push(i); } } } // tie-break by choosing the first angle CCW from the tieBreakAngle var minCCWDiff = 2 * Math.PI; var angle, bestAngle; for (i = 0; i < maxIs.length; i++) { angle = angles[maxIs[i]] - maxAngleDiff / 2; angleDiff = angle - tieBreakAngle; if (angleDiff < 0) { angleDiff += 2 * Math.PI; } if (angleDiff < minCCWDiff) { minCCWDiff = angleDiff; bestAngle = angle; } } // find anchor from bestAngle var dir = PrairieGeom.vector2DAtAngle(bestAngle); dir = dir.x(1 / PrairieGeom.supNorm(dir)); return dir.x(-1); }; /** Label the intersection of several lines. @param {Vector} labelPoint The point to be labeled. @param {Array} points The end of the lines that meet at labelPoint. @param {String} label The label text. @param {Number} scaleOffset (Optional) Scale factor for the offset (default: 1). */ PrairieDraw.prototype.labelIntersection = function (labelPoint, points, label, scaleOffset) { scaleOffset = scaleOffset === undefined ? 1 : scaleOffset; var anchor = this.findAnchorForIntersection(labelPoint, points); this.text(labelPoint, anchor.x(scaleOffset), label); }; /*****************************************************************************/ PrairieDraw.prototype.clearHistory = function (name) { if (name in this._history) { delete this._history[name]; } else { console.log('WARNING: history not found: ' + name); } }; PrairieDraw.prototype.clearAllHistory = function () { this._history = {}; }; /** Save the history of a data value. @param {string} name The history variable name. @param {number} dt The time resolution to save at. @param {number} maxTime The maximum age of history to save. @param {number} curTime The current time. @param {object} curValue The current data value. @return {Array} A history array of vectors of the form [time, value]. */ PrairieDraw.prototype.history = function (name, dt, maxTime, curTime, curValue) { if (!(name in this._history)) { this._history[name] = [[curTime, curValue]]; } else { var h = this._history[name]; if (h.length < 2) { h.push([curTime, curValue]); } else { var prevPrevTime = h[h.length - 2][0]; if (curTime - prevPrevTime < dt) { // new time jump will still be short, replace the last record h[h.length - 1] = [curTime, curValue]; } else { // new time jump would be too long, just add the new record h.push([curTime, curValue]); } } // discard old values as necessary var i = 0; while (curTime - h[i][0] > maxTime && i < h.length - 1) { i++; } if (i > 0) { this._history[name] = h.slice(i); } } return this._history[name]; }; PrairieDraw.prototype.pairsToVectors = function (pairArray) { var vectorArray = []; for (var i = 0; i < pairArray.length; i++) { vectorArray.push($V(pairArray[i])); } return vectorArray; }; PrairieDraw.prototype.historyToTrace = function (data) { var trace = []; for (var i = 0; i < data.length; i++) { trace.push(data[i][1]); } return trace; }; /** Plot a history sequence. @param {Vector} originDw The lower-left position of the axes. @param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right). @param {Vector} sizeData The size of the axes in data coordinates. @param {number} timeOffset The horizontal position for the current time. @param {string} yLabel The vertical axis label. @param {Array} data An array of [time, value] arrays to plot. @param {string} type (Optional) The type of line being drawn. */ PrairieDraw.prototype.plotHistory = function ( originDw, sizeDw, sizeData, timeOffset, yLabel, data, type ) { var scale = $V([sizeDw.e(1) / sizeData.e(1), sizeDw.e(2) / sizeData.e(2)]); var lastTime = data[data.length - 1][0]; var offset = $V([timeOffset - lastTime, 0]); var plotData = PrairieGeom.scalePoints( PrairieGeom.translatePoints(this.pairsToVectors(data), offset), scale ); this.save(); this.translate(originDw); this.save(); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); this.arrow($V([0, 0]), $V([sizeDw.e(1), 0])); this.arrow($V([0, 0]), $V([0, sizeDw.e(2)])); this.text($V([sizeDw.e(1), 0]), $V([1, 1.5]), 'TEX:$t$'); this.text($V([0, sizeDw.e(2)]), $V([1.5, 1]), yLabel); this.restore(); var col = this._getColorProp(type); this.setProp('shapeOutlineColor', col); this.setProp('pointRadiusPx', '4'); this.save(); this._ctx.beginPath(); var bottomLeftPx = this.pos2Px($V([0, 0])); var topRightPx = this.pos2Px(sizeDw); var offsetPx = topRightPx.subtract(bottomLeftPx); this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height); this._ctx.clip(); this.polyLine(plotData, false); this.restore(); this.point(plotData[plotData.length - 1]); this.restore(); }; /** Draw a history of positions as a faded line. @param {Array} history History data, array of [time, position] pairs, where position is a vector. @param {number} t Current time. @param {number} maxT Maximum history time. @param {Array} currentRGB RGB triple for current time color. @param {Array} oldRGB RGB triple for old time color. */ PrairieDraw.prototype.fadeHistoryLine = function (history, t, maxT, currentRGB, oldRGB) { if (history.length < 2) { return; } for (var i = history.length - 2; i >= 0; i--) { // draw line backwards so newer segments are on top var pT = history[i][0]; var pDw1 = history[i][1]; var pDw2 = history[i + 1][1]; var alpha = (t - pT) / maxT; var rgb = PrairieGeom.linearInterpArray(currentRGB, oldRGB, alpha); var color = 'rgb(' + rgb[0].toFixed(0) + ', ' + rgb[1].toFixed(0) + ', ' + rgb[2].toFixed(0) + ')'; this.line(pDw1, pDw2, color); } }; /*****************************************************************************/ PrairieDraw.prototype.mouseDown3D = function (event) { event.preventDefault(); this._mouseDown3D = true; this._lastMouseX3D = event.clientX; this._lastMouseY3D = event.clientY; }; PrairieDraw.prototype.mouseUp3D = function () { this._mouseDown3D = false; }; PrairieDraw.prototype.mouseMove3D = function (event) { if (!this._mouseDown3D) { return; } var deltaX = event.clientX - this._lastMouseX3D; var deltaY = event.clientY - this._lastMouseY3D; this._lastMouseX3D = event.clientX; this._lastMouseY3D = event.clientY; this.incrementView3D(deltaY * 0.01, 0, deltaX * 0.01); }; PrairieDraw.prototype.activate3DControl = function () { /* Listen just on the canvas for mousedown, but on whole window * for move/up. This allows mouseup while off-canvas (and even * off-window) to be captured. Ideally we should also listen for * mousedown on the whole window and use mouseEventOnCanvas(), but * this is broken on Canary for some reason (some areas off-canvas * don't work). The advantage of listening for mousedown on the * whole window is that we can get the event during the "capture" * phase rather than the later "bubble" phase, allowing us to * preventDefault() before things like select-drag starts. */ this._canvas.addEventListener('mousedown', this.mouseDown3D.bind(this), true); window.addEventListener('mouseup', this.mouseUp3D.bind(this), true); window.addEventListener('mousemove', this.mouseMove3D.bind(this), true); }; /*****************************************************************************/ PrairieDraw.prototype.mouseDownTracking = function (event) { event.preventDefault(); this._mouseDownTracking = true; this._lastMouseXTracking = event.pageX; this._lastMouseYTracking = event.pageY; }; PrairieDraw.prototype.mouseUpTracking = function () { this._mouseDownTracking = false; }; PrairieDraw.prototype.mouseMoveTracking = function (event) { if (!this._mouseDownTracking) { return; } this._lastMouseXTracking = event.pageX; this._lastMouseYTracking = event.pageY; }; PrairieDraw.prototype.activateMouseTracking = function () { this._canvas.addEventListener('mousedown', this.mouseDownTracking.bind(this), true); window.addEventListener('mouseup', this.mouseUpTracking.bind(this), true); window.addEventListener('mousemove', this.mouseMoveTracking.bind(this), true); }; PrairieDraw.prototype.mouseDown = function () { if (this._mouseDownTracking !== undefined) { return this._mouseDownTracking; } else { return false; } }; PrairieDraw.prototype.mousePositionDw = function () { var xPx = this._lastMouseXTracking - this._canvas.offsetLeft; var yPx = this._lastMouseYTracking - this._canvas.offsetTop; var posPx = $V([xPx, yPx]); var posDw = this.pos2Dw(posPx); return posDw; }; /*****************************************************************************/ /** Creates a PrairieDrawAnim object. @constructor @this {PrairieDraw} @param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt. @param {Function} drawfcn An optional function that draws on the canvas at time t. */ function PrairieDrawAnim(canvas, drawFcn) { PrairieDraw.call(this, canvas, null); this._drawTime = 0; this._deltaTime = 0; this._running = false; this._sequences = {}; this._animStateCallbacks = []; this._animStepCallbacks = []; if (drawFcn) { this.draw = drawFcn.bind(this); } this.save(); this.draw(0); this.restoreAll(); } PrairieDrawAnim.prototype = new PrairieDraw(); /** @private Store the appropriate version of requestAnimationFrame. Use this like: prairieDraw.requestAnimationFrame.call(window, this.callback.bind(this)); We can't do prairieDraw.requestAnimationFrame(callback), because that would run requestAnimationFrame in the context of prairieDraw ("this" would be prairieDraw), and requestAnimationFrame needs "this" to be "window". We need to pass this.callback.bind(this) as the callback function rather than just this.callback as otherwise the callback functions is called from "window" context, and we want it to be called from the context of our own object. */ /* jshint laxbreak: true */ if (typeof window !== 'undefined') { PrairieDrawAnim.prototype._requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** Prototype function to draw on the canvas, should be implemented by children. @param {number} t Current animation time in seconds. */ PrairieDrawAnim.prototype.draw = function (t) { /* jshint unused: false */ }; /** Start the animation. */ PrairieDrawAnim.prototype.startAnim = function () { if (!this._running) { this._running = true; this._startFrame = true; this._requestAnimationFrame.call(window, this._callback.bind(this)); for (var i = 0; i < this._animStateCallbacks.length; i++) { this._animStateCallbacks[i](true); } } }; /** Stop the animation. */ PrairieDrawAnim.prototype.stopAnim = function () { this._running = false; for (var i = 0; i < this._animStateCallbacks.length; i++) { this._animStateCallbacks[i](false); } }; /** Toggle the animation. */ PrairieDrawAnim.prototype.toggleAnim = function () { if (this._running) { this.stopAnim(); } else { this.startAnim(); } }; /** Register a callback on animation state changes. @param {Function} callback The callback(animated) function. */ PrairieDrawAnim.prototype.registerAnimCallback = function (callback) { this._animStateCallbacks.push(callback.bind(this)); callback.apply(this, [this._running]); }; /** Register a callback on animation steps. @param {Function} callback The callback(t) function. */ PrairieDrawAnim.prototype.registerAnimStepCallback = function (callback) { this._animStepCallbacks.push(callback.bind(this)); }; /** @private Callback function to handle the animationFrame events. */ PrairieDrawAnim.prototype._callback = function (tMS) { if (this._startFrame) { this._startFrame = false; this._timeOffset = tMS - this._drawTime; } var animTime = tMS - this._timeOffset; this._deltaTime = (animTime - this._drawTime) / 1000; this._drawTime = animTime; var t = animTime / 1000; for (var i = 0; i < this._animStepCallbacks.length; i++) { this._animStepCallbacks[i](t); } this.save(); this.draw(t); this._deltaTime = 0; this.restoreAll(); if (this._running) { this._requestAnimationFrame.call(window, this._callback.bind(this)); } }; /** Get the elapsed time since the last redraw. return {number} Elapsed time in seconds. */ PrairieDrawAnim.prototype.deltaTime = function () { return this._deltaTime; }; /** Redraw the drawing at the current time. */ PrairieDrawAnim.prototype.redraw = function () { if (!this._running) { this.save(); this.draw(this._drawTime / 1000); this.restoreAll(); } }; /** Reset the animation time to zero. @param {bool} redraw (Optional) Whether to redraw (default: true). */ PrairieDrawAnim.prototype.resetTime = function (redraw) { this._drawTime = 0; for (var i = 0; i < this._animStepCallbacks.length; i++) { this._animStepCallbacks[i](0); } this._startFrame = true; if (redraw === undefined || redraw === true) { this.redraw(); } }; /** Reset everything to the intial state. */ PrairieDrawAnim.prototype.reset = function () { for (var optionName in this._options) { this.resetOptionValue(optionName); } this.resetAllSequences(); this.clearAllHistory(); this.stopAnim(); this.resetView3D(false); this.resetTime(false); this.redraw(); }; /** Stop all action and computation. */ PrairieDrawAnim.prototype.stop = function () { this.stopAnim(); }; PrairieDrawAnim.prototype.lastDrawTime = function () { return this._drawTime / 1000; }; /*****************************************************************************/ PrairieDrawAnim.prototype.mouseDownAnimOnClick = function (event) { event.preventDefault(); this.startAnim(); }; PrairieDrawAnim.prototype.activateAnimOnClick = function () { this._canvas.addEventListener('mousedown', this.mouseDownAnimOnClick.bind(this), true); }; /*****************************************************************************/ /** Interpolate between different states in a sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} holdTimes Hold times for the corresponding state. @param {Array} t Current time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.sequence = function (states, transTimes, holdTimes, t) { var totalTime = 0; var i; for (i = 0; i < states.length; i++) { totalTime += transTimes[i]; totalTime += holdTimes[i]; } var ts = t % totalTime; totalTime = 0; var state = {}; var e, ip; var lastTotalTime = 0; for (i = 0; i < states.length; i++) { ip = i === states.length - 1 ? 0 : i + 1; totalTime += transTimes[i]; if (totalTime > ts) { // in transition from i to i+1 state.t = ts - lastTotalTime; state.index = i; state.alpha = state.t / (totalTime - lastTotalTime); for (e in states[i]) { state[e] = PrairieGeom.linearInterp(states[i][e], states[ip][e], state.alpha); } return state; } lastTotalTime = totalTime; totalTime += holdTimes[i]; if (totalTime > ts) { // holding at i+1 state.t = 0; state.index = ip; state.alpha = 0; for (e in states[i]) { state[e] = states[ip][e]; } return state; } lastTotalTime = totalTime; } }; /*****************************************************************************/ /** Interpolate between different states in a sequence under external prompting. @param {string} name Name of this transition sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} t Current animation time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.controlSequence = function (name, states, transTimes, t) { if (!(name in this._sequences)) { this._sequences[name] = { index: 0, inTransition: false, startTransition: false, indefiniteHold: true, callbacks: [], }; } var seq = this._sequences[name]; var state; var transTime = 0; if (seq.startTransition) { seq.startTransition = false; seq.inTransition = true; seq.indefiniteHold = false; seq.startTime = t; } if (seq.inTransition) { transTime = t - seq.startTime; } if (seq.inTransition && transTime >= transTimes[seq.index]) { seq.inTransition = false; seq.indefiniteHold = true; seq.index = (seq.index + 1) % states.length; delete seq.startTime; } if (!seq.inTransition) { state = PrairieGeom.dupState(states[seq.index]); state.index = seq.index; state.t = 0; state.alpha = 0; state.inTransition = false; return state; } var alpha = transTime / transTimes[seq.index]; var nextIndex = (seq.index + 1) % states.length; state = PrairieGeom.linearInterpState(states[seq.index], states[nextIndex], alpha); state.t = transTime; state.index = seq.index; state.alpha = alpha; state.inTransition = true; return state; }; /** Start the next transition for the given sequence. @param {string} name Name of the sequence to transition. @param {string} stateName (Optional) Only transition if we are currently in stateName. */ PrairieDrawAnim.prototype.stepSequence = function (name, stateName) { if (!(name in this._sequences)) { throw new Error('PrairieDraw: unknown sequence: ' + name); } var seq = this._sequences[name]; if (!seq.lastState.indefiniteHold) { return; } if (stateName !== undefined) { if (seq.lastState.name !== stateName) { return; } } seq.startTransition = true; this.startAnim(); }; /*****************************************************************************/ /** Interpolate between different states (new version). @param {string} name Name of this transition sequence. @param {Array} states An array of objects, each specifying scalar or vector state values. @param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1]. @param {Array} holdtimes Hold times for each state. A negative value means to hold until externally triggered. @param {Array} t Current animation time. @return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding). */ PrairieDrawAnim.prototype.newSequence = function ( name, states, transTimes, holdTimes, interps, names, t ) { var seq = this._sequences[name]; if (seq === undefined) { this._sequences[name] = { startTransition: false, lastState: {}, callbacks: [], initialized: false, }; seq = this._sequences[name]; } var i; if (!seq.initialized) { seq.initialized = true; for (var e in states[0]) { if (typeof states[0][e] === 'number') { seq.lastState[e] = states[0][e]; } else if (typeof states[0][e] === 'function') { seq.lastState[e] = states[0][e](null, 0); } } seq.lastState.inTransition = false; seq.lastState.indefiniteHold = false; seq.lastState.index = 0; seq.lastState.name = names[seq.lastState.index]; seq.lastState.t = 0; seq.lastState.realT = t; if (holdTimes[0] < 0) { seq.lastState.indefiniteHold = true; } for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name); } } if (seq.startTransition) { seq.startTransition = false; seq.lastState.inTransition = true; seq.lastState.indefiniteHold = false; seq.lastState.t = 0; seq.lastState.realT = t; for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name); } } var endTime, nextIndex; while (true) { nextIndex = (seq.lastState.index + 1) % states.length; if (seq.lastState.inTransition) { endTime = seq.lastState.realT + transTimes[seq.lastState.index]; if (t >= endTime) { seq.lastState = this._interpState( seq.lastState, states[nextIndex], interps, endTime, endTime ); seq.lastState.inTransition = false; seq.lastState.index = nextIndex; seq.lastState.name = names[seq.lastState.index]; if (holdTimes[nextIndex] < 0) { seq.lastState.indefiniteHold = true; } else { seq.lastState.indefiniteHold = false; } for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name); } } else { return this._interpState(seq.lastState, states[nextIndex], interps, t, endTime); } } else { endTime = seq.lastState.realT + holdTimes[seq.lastState.index]; if (holdTimes[seq.lastState.index] >= 0 && t > endTime) { seq.lastState = this._extrapState(seq.lastState, states[seq.lastState.index], endTime); seq.lastState.inTransition = true; seq.lastState.indefiniteHold = false; for (i = 0; i < seq.callbacks.length; i++) { seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name); } } else { return this._extrapState(seq.lastState, states[seq.lastState.index], t); } } } }; PrairieDrawAnim.prototype._interpState = function (lastState, nextState, interps, t, tFinal) { var s1 = PrairieGeom.dupState(nextState); s1.realT = tFinal; s1.t = tFinal - lastState.realT; var s = {}; var alpha = (t - lastState.realT) / (tFinal - lastState.realT); for (var e in nextState) { if (e in interps) { s[e] = interps[e](lastState, s1, t - lastState.realT); } else { s[e] = PrairieGeom.linearInterp(lastState[e], s1[e], alpha); } } s.realT = t; s.t = Math.min(t - lastState.realT, s1.t); s.index = lastState.index; s.inTransition = lastState.inTransition; s.indefiniteHold = lastState.indefiniteHold; return s; }; PrairieDrawAnim.prototype._extrapState = function (lastState, lastStateData, t) { var s = {}; for (var e in lastStateData) { if (typeof lastStateData[e] === 'number') { s[e] = lastStateData[e]; } else if (typeof lastStateData[e] === 'function') { s[e] = lastStateData[e](lastState, t - lastState.realT); } } s.realT = t; s.t = t - lastState.realT; s.index = lastState.index; s.inTransition = lastState.inTransition; s.indefiniteHold = lastState.indefiniteHold; return s; }; /** Register a callback on animation sequence events. @param {string} seqName The sequence to register on. @param {Function} callback The callback(event, index, stateName) function. */ PrairieDrawAnim.prototype.registerSeqCallback = function (seqName, callback) { if (!(seqName in this._sequences)) { throw new Error('PrairieDraw: unknown sequence: ' + seqName); } var seq = this._sequences[seqName]; seq.callbacks.push(callback.bind(this)); if (seq.inTransition) { callback.apply(this, ['exit', seq.lastState.index, seq.lastState.name]); } else { callback.apply(this, ['enter', seq.lastState.index, seq.lastState.name]); } }; /** Make a two-state sequence transitioning to and from 0 and 1. @param {string} name The name of the sequence; @param {number} transTime The transition time between the two states. @return {number} The current state (0 to 1). */ PrairieDrawAnim.prototype.activationSequence = function (name, transTime, t) { var stateZero = { trans: 0 }; var stateOne = { trans: 1 }; var states = [stateZero, stateOne]; var transTimes = [transTime, transTime]; var holdTimes = [-1, -1]; var interps = {}; var names = ['zero', 'one']; var state = this.newSequence(name, states, transTimes, holdTimes, interps, names, t); return state.trans; }; PrairieDrawAnim.prototype.resetSequence = function (name) { var seq = this._sequences[name]; if (seq !== undefined) { seq.initialized = false; } }; PrairieDrawAnim.prototype.resetAllSequences = function () { for (var name in this._sequences) { this.resetSequence(name); } }; /*****************************************************************************/ PrairieDraw.prototype.drawImage = function (imgSrc, posDw, anchor, widthDw) { var img; if (imgSrc in this._images) { // FIXME: should check that the image is really loaded, in case we are fired beforehand (also for text images). img = this._images[imgSrc]; var posPx = this.pos2Px(posDw); var scale; if (widthDw === undefined) { scale = 1; } else { var offsetDw = $V([widthDw, 0]); var offsetPx = this.vec2Px(offsetDw); var widthPx = offsetPx.modulus(); scale = widthPx / img.width; } var xPx = (-(anchor.e(1) + 1) / 2) * img.width; var yPx = ((anchor.e(2) - 1) / 2) * img.height; this._ctx.save(); this._ctx.translate(posPx.e(1), posPx.e(2)); this._ctx.scale(scale, scale); this._ctx.translate(xPx, yPx); this._ctx.drawImage(img, 0, 0); this._ctx.restore(); } else { img = new Image(); var that = this; img.onload = function () { that.redraw(); if (that.trigger) { that.trigger('imgLoad'); } }; img.src = imgSrc; this._images[imgSrc] = img; } }; /*****************************************************************************/ PrairieDraw.prototype.mouseEventPx = function (event) { var element = this._canvas; var xPx = event.pageX; var yPx = event.pageY; do { xPx -= element.offsetLeft; yPx -= element.offsetTop; /* jshint boss: true */ // suppress warning for assignment on next line } while ((element = element.offsetParent)); xPx *= this._canvas.width / this._canvas.scrollWidth; yPx *= this._canvas.height / this._canvas.scrollHeight; var posPx = $V([xPx, yPx]); return posPx; }; PrairieDraw.prototype.mouseEventDw = function (event) { var posPx = this.mouseEventPx(event); var posDw = this.pos2Dw(posPx); return posDw; }; PrairieDraw.prototype.mouseEventOnCanvas = function (event) { var posPx = this.mouseEventPx(event); console.log(posPx.e(1), posPx.e(2), this._width, this._height); /* jshint laxbreak: true */ if ( posPx.e(1) >= 0 && posPx.e(1) <= this._width && posPx.e(2) >= 0 && posPx.e(2) <= this._height ) { console.log(true); return true; } console.log(false); return false; }; PrairieDraw.prototype.reportMouseSample = function (event) { var posDw = this.mouseEventDw(event); var numDecPlaces = 2; /* jshint laxbreak: true */ console.log( '$V([' + posDw.e(1).toFixed(numDecPlaces) + ', ' + posDw.e(2).toFixed(numDecPlaces) + ']),' ); }; PrairieDraw.prototype.activateMouseSampling = function () { this._canvas.addEventListener('click', this.reportMouseSample.bind(this)); }; /*****************************************************************************/ PrairieDraw.prototype.activateMouseLineDraw = function () { if (this._mouseLineDrawActive === true) { return; } this._mouseLineDrawActive = true; this.mouseLineDraw = false; this.mouseLineDrawing = false; if (this._mouseLineDrawInitialized !== true) { this._mouseLineDrawInitialized = true; if (this._mouseDrawCallbacks === undefined) { this._mouseDrawCallbacks = []; } this._canvas.addEventListener('mousedown', this.mouseLineDrawMousedown.bind(this), true); window.addEventListener('mouseup', this.mouseLineDrawMouseup.bind(this), true); window.addEventListener('mousemove', this.mouseLineDrawMousemove.bind(this), true); } /* for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); */ }; PrairieDraw.prototype.deactivateMouseLineDraw = function () { this._mouseLineDrawActive = false; this.mouseLineDraw = false; this.mouseLineDrawing = false; this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMousedown = function (event) { if (!this._mouseLineDrawActive) { return; } event.preventDefault(); var posDw = this.mouseEventDw(event); this.mouseLineDrawStart = posDw; this.mouseLineDrawEnd = posDw; this.mouseLineDrawing = true; this.mouseLineDraw = true; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMousemove = function (event) { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawEnd = this.mouseEventDw(event); for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); // FIXME: add rate-limiting }; PrairieDraw.prototype.mouseLineDrawMouseup = function () { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawing = false; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.mouseLineDrawMouseout = function (event) { if (!this._mouseLineDrawActive) { return; } if (!this.mouseLineDrawing) { return; } this.mouseLineDrawEnd = this.mouseEventDw(event); this.mouseLineDrawing = false; for (var i = 0; i < this._mouseDrawCallbacks.length; i++) { this._mouseDrawCallbacks[i](); } this.redraw(); }; PrairieDraw.prototype.registerMouseLineDrawCallback = function (callback) { if (this._mouseDrawCallbacks === undefined) { this._mouseDrawCallbacks = []; } this._mouseDrawCallbacks.push(callback.bind(this)); }; /*****************************************************************************/ /** Plot a line graph. @param {Array} data Array of vectors to plot. @param {Vector} originDw The lower-left position of the axes. @param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right). @param {Vector} originData The lower-left position of the axes in data coordinates. @param {Vector} sizeData The size of the axes in data coordinates. @param {string} xLabel The vertical axis label. @param {string} yLabel The vertical axis label. @param {string} type (Optional) The type of line being drawn. @param {string} drawAxes (Optional) Whether to draw the axes (default: true). @param {string} drawPoint (Optional) Whether to draw the last point (default: true). @param {string} pointLabel (Optional) Label for the last point (default: undefined). @param {string} pointAnchor (Optional) Anchor for the last point label (default: $V([0, -1])). @param {Object} options (Optional) Plotting options: horizAxisPos: "bottom", "top", or a numerical value in data coordinates (default: "bottom") vertAxisPos: "left", "right", or a numerical value in data coordinates (default: "left") */ PrairieDraw.prototype.plot = function ( data, originDw, sizeDw, originData, sizeData, xLabel, yLabel, type, drawAxes, drawPoint, pointLabel, pointAnchor, options ) { drawAxes = drawAxes === undefined ? true : drawAxes; drawPoint = drawPoint === undefined ? true : drawPoint; options = options === undefined ? {} : options; var horizAxisPos = options.horizAxisPos === undefined ? 'bottom' : options.horizAxisPos; var vertAxisPos = options.vertAxisPos === undefined ? 'left' : options.vertAxisPos; var drawXGrid = options.drawXGrid === undefined ? false : options.drawXGrid; var drawYGrid = options.drawYGrid === undefined ? false : options.drawYGrid; var dXGrid = options.dXGrid === undefined ? 1 : options.dXGrid; var dYGrid = options.dYGrid === undefined ? 1 : options.dYGrid; var drawXTickLabels = options.drawXTickLabels === undefined ? false : options.drawXTickLabels; var drawYTickLabels = options.drawYTickLabels === undefined ? false : options.drawYTickLabels; var xLabelPos = options.xLabelPos === undefined ? 1 : options.xLabelPos; var yLabelPos = options.yLabelPos === undefined ? 1 : options.yLabelPos; var xLabelAnchor = options.xLabelAnchor === undefined ? $V([1, 1.5]) : options.xLabelAnchor; var yLabelAnchor = options.yLabelAnchor === undefined ? $V([1.5, 1]) : options.yLabelAnchor; var yLabelRotate = options.yLabelRotate === undefined ? false : options.yLabelRotate; this.save(); this.translate(originDw); // grid var ix0 = Math.ceil(originData.e(1) / dXGrid); var ix1 = Math.floor((originData.e(1) + sizeData.e(1)) / dXGrid); var x0 = 0; var x1 = sizeDw.e(1); var iy0 = Math.ceil(originData.e(2) / dYGrid); var iy1 = Math.floor((originData.e(2) + sizeData.e(2)) / dYGrid); var y0 = 0; var y1 = sizeDw.e(2); var i, x, y; if (drawXGrid) { for (i = ix0; i <= ix1; i++) { x = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), i * dXGrid ); this.line($V([x, y0]), $V([x, y1]), 'grid'); } } if (drawYGrid) { for (i = iy0; i <= iy1; i++) { y = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), i * dYGrid ); this.line($V([x0, y]), $V([x1, y]), 'grid'); } } var label; if (drawXTickLabels) { for (i = ix0; i <= ix1; i++) { x = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), i * dXGrid ); label = String(i * dXGrid); this.text($V([x, y0]), $V([0, 1]), label); } } if (drawYTickLabels) { for (i = iy0; i <= iy1; i++) { y = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), i * dYGrid ); label = String(i * dYGrid); this.text($V([x0, y]), $V([1, 0]), label); } } // axes var axisX, axisY; if (vertAxisPos === 'left') { axisX = 0; } else if (vertAxisPos === 'right') { axisX = sizeDw.e(1); } else { axisX = PrairieGeom.linearMap( originData.e(1), originData.e(1) + sizeData.e(1), 0, sizeDw.e(1), vertAxisPos ); } if (horizAxisPos === 'bottom') { axisY = 0; } else if (horizAxisPos === 'top') { axisY = sizeDw.e(2); } else { axisY = PrairieGeom.linearMap( originData.e(2), originData.e(2) + sizeData.e(2), 0, sizeDw.e(2), horizAxisPos ); } if (drawAxes) { this.save(); this.setProp('arrowLineWidthPx', 1); this.setProp('arrowheadLengthRatio', 11); this.arrow($V([0, axisY]), $V([sizeDw.e(1), axisY])); this.arrow($V([axisX, 0]), $V([axisX, sizeDw.e(2)])); x = xLabelPos * sizeDw.e(1); y = yLabelPos * sizeDw.e(2); this.text($V([x, axisY]), xLabelAnchor, xLabel); var angle = yLabelRotate ? -Math.PI / 2 : 0; this.text($V([axisX, y]), yLabelAnchor, yLabel, undefined, angle); this.restore(); } var col = this._getColorProp(type); this.setProp('shapeOutlineColor', col); this.setProp('pointRadiusPx', '4'); var bottomLeftPx = this.pos2Px($V([0, 0])); var topRightPx = this.pos2Px(sizeDw); var offsetPx = topRightPx.subtract(bottomLeftPx); this.save(); this.scale(sizeDw); this.scale($V([1 / sizeData.e(1), 1 / sizeData.e(2)])); this.translate(originData.x(-1)); this.save(); this._ctx.beginPath(); this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height); this._ctx.clip(); this.polyLine(data, false); this.restore(); if (drawPoint) { this.point(data[data.length - 1]); if (pointLabel !== undefined) { if (pointAnchor === undefined) { pointAnchor = $V([0, -1]); } this.text(data[data.length - 1], pointAnchor, pointLabel); } } this.restore(); this.restore(); }; /*****************************************************************************/ return { PrairieDraw: PrairieDraw, PrairieDrawAnim: PrairieDrawAnim, }; });
PrairieLearn/PrairieLearn
public/localscripts/calculationQuestion/PrairieDraw.js
JavaScript
agpl-3.0
137,277
#-- # Copyright (C) 2007, 2008 Johan Sørensen <johan@johansorensen.com> # Copyright (C) 2008 David A. Cuadrado <krawek@gmail.com> # Copyright (C) 2008 Tim Dysinger <tim@dysinger.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ require File.dirname(__FILE__) + '/../spec_helper' describe Project do def create_project(options={}) Project.new({ :title => "foo project", :slug => "foo", :description => "my little project", :user => users(:johan) }.merge(options)) end it "should have valid associations" do create_project.should have_valid_associations end it "should have a title to be valid" do project = create_project(:title => nil) project.should_not be_valid project.title = "foo" project.should be_valid end it "should have a slug to be valid" do project = create_project(:slug => nil) project.should_not be_valid end it "should have a unique slug to be valid" do p1 = create_project p1.save! p2 = create_project(:slug => "FOO") p2.should_not be_valid p2.should have(1).error_on(:slug) end it "should have an alphanumeric slug" do project = create_project(:slug => "asd asd") project.valid? project.should_not be_valid end it "should downcase the slug before validation" do project = create_project(:slug => "FOO") project.valid? project.slug.should == "foo" end it "creates an initial repository for itself" do project = create_project project.save project.repositories.should_not == [] project.repositories.first.name.should == "mainline" project.repositories.first.user.should == project.user project.user.can_write_to?(project.repositories.first).should == true end it "creates the wiki repository on create" do project = create_project(:slug => "my-new-project") project.save! project.wiki_repository.should be_instance_of(Repository) project.wiki_repository.name.should == "my-new-project#{Repository::WIKI_NAME_SUFFIX}" project.wiki_repository.kind.should == Repository::KIND_WIKI project.repositories.should_not include(project.wiki_repository) end it "finds a project by slug or raises" do Project.find_by_slug!(projects(:johans).slug).should == projects(:johans) proc{ Project.find_by_slug!("asdasdasd") }.should raise_error(ActiveRecord::RecordNotFound) end it "has the slug as its params" do projects(:johans).to_param.should == projects(:johans).slug end it "knows if a user is a admin on a project" do projects(:johans).admin?(users(:johan)).should == true projects(:johans).admin?(users(:moe)).should == false projects(:johans).admin?(:false).should == false end it "knows if a user can delete the project" do project = projects(:johans) project.can_be_deleted_by?(users(:moe)).should == false project.can_be_deleted_by?(users(:johan)).should == false # since it has > 1 repos project.repositories.last.destroy project.reload.can_be_deleted_by?(users(:johan)).should == true end it "should strip html tags" do project = create_project(:description => "<h1>Project A</h1>\n<b>Project A</b> is a....") project.stripped_description.should == "Project A\nProject A is a...." end # it "should strip html tags, except highlights" do # project = create_project(:description => %Q{<h1>Project A</h1>\n<strong class="highlight">Project A</strong> is a....}) # project.stripped_description.should == %Q(Project A\n<strong class="highlight">Project A</strong> is a....) # end it "should have valid urls ( prepending http:// if needed )" do project = projects(:johans) [ :home_url, :mailinglist_url, :bugtracker_url ].each do |attr| project.should be_valid project.send("#{attr}=", 'http://blah.com') project.should be_valid project.send("#{attr}=", 'ftp://blah.com') project.should_not be_valid project.send("#{attr}=", 'blah.com') project.should be_valid project.send(attr).should == 'http://blah.com' end end it "should not prepend http:// to empty urls" do project = projects(:johans) [ :home_url, :mailinglist_url, :bugtracker_url ].each do |attr| project.send("#{attr}=", '') project.send(attr).should be_blank project.send("#{attr}=", nil) project.send(attr).should be_blank end end it "should find or create an associated wiki repo" do project = projects(:johans) repo = repositories(:johans) repo.kind = Repository::KIND_WIKI project.wiki_repository = repo project.save! project.reload.wiki_repository.should == repo end it "should have a wiki repository" do project = projects(:johans) project.wiki_repository.should == repositories(:johans_wiki) project.repositories.should_not include(repositories(:johans_wiki)) project.repository_clones.should_not include(repositories(:johans_wiki)) end describe "Project events" do before(:each) do @project = projects(:johans) @user = users(:johan) @repository = @project.repositories.first end it "should create an event from the action name" do @project.create_event(Action::CREATE_PROJECT, @repository, @user, "", "").should_not == nil end it "should create an event even without a valid id" do @project.create_event(52342, @repository, @user).should_not == nil end it "creates valid attributes on the event" do e = @project.create_event(Action::COMMIT, @repository, @user, "somedata", "a body") e.should be_valid e.new_record?.should == false e.reload e.action.should == Action::COMMIT e.target.should == @repository e.project.should == @project e.user.should == @user e.data.should == "somedata" e.body.should == "a body" end end end
almonteb/scoot
spec/models/project_spec.rb
Ruby
agpl-3.0
6,546
# # Bold - more than just blogging. # Copyright (C) 2015-2016 Jens Krämer <jk@jkraemer.net> # # This file is part of Bold. # # Bold is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Bold 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Bold. If not, see <http://www.gnu.org/licenses/>. # # Base class for controllers delivering content to the public # # Does site lookup by hostname / alias and runs requests in the context of the # site's configured time zone and locale. class FrontendController < BaseController layout :determine_layout prepend_before_action :set_site around_action :use_site_time_zone # in dev mode, Rails' standard error handling is fine. unless Rails.env.development? # order matters, least specific has to be first rescue_from Exception, with: :handle_error rescue_from Bold::SetupNeeded, with: :handle_404 rescue_from Bold::NotFound, with: :handle_404 rescue_from Bold::SiteNotFound, with: :handle_404_or_goto_admin rescue_from ActionController::InvalidAuthenticityToken, with: :handle_error rescue_from ActionController::UnknownFormat, with: :handle_404 end decorate_assigned :site, :content, :tag, :author, :category private def find_content if params[:path].blank? current_site.homepage elsif @permalink = current_site.permalinks.find_by_path(params[:path]) @destination = @permalink.destination (@destination.is_a?(Content) && @destination.published?) ? @destination : nil end end def render_content(content = @content, options = {}) original_content = @content @content = content options[:status] ||= :ok respond_to do |format| format.html do options[:template] = content.get_template.file render options end format.any { head options[:status] } end @content = original_content end def determine_layout current_site.theme.layout.present? ? 'content' : 'default_content' end def handle_404_or_goto_admin if request.host == Bold::Config['backend_host'] redirect_to bold_sites_url else handle_404 end end # Finds the current site based on http host or server_name header # # For the dev environment there is a fallback to the first site # found when none matched. Other environments will yield a # SiteNotFound error instead. # # Override #find_current_site or Site::for_request to customize the # detection of the current site. def set_site @site = Bold.current_site = find_current_site raise Bold::SiteNotFound unless site_selected? end def available_locales super.tap do |locales| if (site_locales = current_site.available_locales).present? locales &= site_locales end end end def auto_locale if current_site.detect_user_locale? return http_accept_language.compatible_language_from available_locales end end def use_site_time_zone(&block) if site_selected? current_site.in_time_zone &block else block.call end end def find_current_site Site.for_hostname(request.host) end def handle_404(*args) # we enforce rendering of html even if it was an image or something else # that wasn't found. if site = Bold.current_site and page = site.notfound_page render_content page, status: :not_found else respond_to do |format| format.html { render 'errors/404', layout: 'error', status: 404, formats: :html } format.any { head :not_found } end end end def handle_error(*args) unless performed? # avoid DoubleRenderError if site = Bold.current_site and page = site.error_page render_content page, status: 500, formats: :html else render 'errors/500', layout: 'error', status: 500, formats: :html end end if exception = args.first Rails.logger.warn exception Rails.logger.info exception.backtrace.join("\n") if defined? Airbrake Airbrake.notify exception end end end def do_not_track? request.headers['DNT'] == '1' end helper_method :do_not_track? end
bold-app/bold
app/controllers/frontend_controller.rb
Ruby
agpl-3.0
4,629
<?php declare(strict_types=1); /** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace OCA\Mail\Events; use Horde_Mime_Mail; use OCA\Mail\Account; use OCA\Mail\Model\IMessage; use OCA\Mail\Model\NewMessageData; use OCA\Mail\Model\RepliedMessageData; use OCP\EventDispatcher\Event; class MessageSentEvent extends Event { /** @var Account */ private $account; /** @var NewMessageData */ private $newMessageData; /** @var null|RepliedMessageData */ private $repliedMessageData; /** @var int|null */ private $draftUid; /** @var IMessage */ private $message; /** @var Horde_Mime_Mail */ private $mail; public function __construct(Account $account, NewMessageData $newMessageData, ?RepliedMessageData $repliedMessageData, ?int $draftUid = null, IMessage $message, Horde_Mime_Mail $mail) { parent::__construct(); $this->account = $account; $this->newMessageData = $newMessageData; $this->repliedMessageData = $repliedMessageData; $this->draftUid = $draftUid; $this->message = $message; $this->mail = $mail; } public function getAccount(): Account { return $this->account; } public function getNewMessageData(): NewMessageData { return $this->newMessageData; } public function getRepliedMessageData(): ?RepliedMessageData { return $this->repliedMessageData; } public function getDraftUid(): ?int { return $this->draftUid; } public function getMessage(): IMessage { return $this->message; } public function getMail(): Horde_Mime_Mail { return $this->mail; } }
ChristophWurst/mail
lib/Events/MessageSentEvent.php
PHP
agpl-3.0
2,380
<?php /** * plentymarkets shopware connector * Copyright © 2013-2014 plentymarkets GmbH * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License, supplemented by an additional * permission, and of our proprietary license can be found * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "plentymarkets" is a registered trademark of plentymarkets GmbH. * "shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, titles and interests in the * above trademarks remain entirely with the trademark owners. * * @copyright Copyright (c) 2014, plentymarkets GmbH (http://www.plentymarkets.com) * @author Daniel Bächtle <daniel.baechtle@plentymarkets.com> */ /** * I am a generated class and am required for communicating with plentymarkets. */ class PlentySoapRequest_GetMeasureUnitConfig { /** * @var string */ public $Lang; }
naturdrogerie/plentymarkets-shopware-connector
Components/Soap/Models/PlentySoapRequest/GetMeasureUnitConfig.php
PHP
agpl-3.0
1,411
import _ from 'underscore' import Base from '../graphs/base' import DayBinner from '../graphs/DayBinner' import WeekBinner from '../graphs/WeekBinner' import MonthBinner from '../graphs/MonthBinner' import ScaleByBins from '../graphs/ScaleByBins' import helpers from '../helpers' import I18n from 'i18n!page_views' // # // Parent class for all graphs that have a date-aligned x-axis. Note: Left // padding for this graph style is space from the frame to the start date's // tick mark, not the leading graph element's edge. Similarly, right padding // is space from the frame to the end date's tick, not the trailing graph // element's edge. This is necessary to keep the date graphs aligned. const defaultOptions = { // # // The date for the left end of the graph. Required. startDate: null, // # // The date for the right end of the graph. Required. endDate: null, // # // The size of the date tick marks, in pixels. tickSize: 5, // # // If any date is outside the bounds of the graph, we have a clipped date clippedDate: false } export default class DateAlignedGraph extends Base { // # // Takes an element and options, same as for Base. Recognizes the options // described above in addition to the options for Base. constructor(div, options) { super(...arguments) // mixin ScaleByBins functionality _.extend(this, ScaleByBins) // check for required options if (options.startDate == null) throw new Error('startDate is required') if (options.endDate == null) throw new Error('endDate is required') // copy in recognized options with defaults for (const key in defaultOptions) { const defaultValue = defaultOptions[key] this[key] = options[key] != null ? options[key] : defaultValue } this.initScale() } // # // Set up X-axis scale initScale() { const interior = this.width - this.leftPadding - this.rightPadding // mixin for the appropriate bin size // use a minimum of 10 pixels for bar width plus spacing before consolidating this.binner = new DayBinner(this.startDate, this.endDate) if (this.binner.count() * 10 > interior) this.binner = new WeekBinner(this.startDate, this.endDate) if (this.binner.count() * 10 > interior) this.binner = new MonthBinner(this.startDate, this.endDate) // scale the x-axis for the number of bins return this.scaleByBins(this.binner.count()) } // # // Reset the graph chrome. Adds an x-axis with daily ticks and weekly (on // Mondays) labels. reset() { super.reset(...arguments) if (this.startDate) this.initScale() return this.drawDateAxis() } // # // Convert a date to a bin index. dateBin(date) { return this.binner.bin(date) } // # // Convert a date to its bin's x-coordinate. binnedDateX(date) { return this.binX(this.dateBin(date)) } // # // Given a datetime, return the floor and ceil as calculated by the binner dateExtent(datetime) { const floor = this.binner.reduce(datetime) return [floor, this.binner.nextTick(floor)] } // # // Given a datetime and a datetime range, return a number from 0.0 to 1.0 dateFraction(datetime, floorDate, ceilDate) { const deltaSeconds = datetime.getTime() - floorDate.getTime() const totalSeconds = ceilDate.getTime() - floorDate.getTime() return deltaSeconds / totalSeconds } // # // Convert a date to an intra-bin x-coordinate. dateX(datetime) { const minX = this.leftMargin const maxX = this.leftMargin + this.width const [floorDate, ceilDate] = this.dateExtent(datetime) const floorX = this.binnedDateX(floorDate) const ceilX = this.binnedDateX(ceilDate) const fraction = this.dateFraction(datetime, floorDate, ceilDate) if (datetime.getTime() < this.startDate.getTime()) { // out of range, left this.clippedDate = true return minX } else if (datetime.getTime() > this.endDate.getTime()) { // out of range, right this.clippedDate = true return maxX } else { // in range return floorX + fraction * (ceilX - floorX) } } // # // Draw a guide along the x-axis. Each day gets a pair of ticks; one from // the top of the frame, the other from the bottom. The ticks are replaced // by a full vertical grid line on Mondays, accompanied by a label. drawDateAxis() { // skip if we haven't set start/end dates yet (@reset will be called by // Base's constructor before we set startDate or endDate) if (this.startDate == null || this.endDate == null) return return this.binner.eachTick((tick, chrome) => { const x = this.binnedDateX(tick) if (chrome && chrome.label) return this.dateLabel(x, this.topMargin + this.height, chrome.label) }) } // # // Draw label text at (x, y). dateLabel(x, y, text) { const label = this.paper.text(x, y, text) return label.attr({fill: this.frameColor}) } // # // Get date text for a bin binDateText(bin) { const lastDay = this.binner.nextTick(bin.date).addDays(-1) const daysBetween = helpers.daysBetween(bin.date, lastDay) if (daysBetween < 1) { // single-day bucket: label the date return I18n.l('date.formats.medium', bin.date) } else if (daysBetween < 7) { // one-week bucket: label the start and end days; include the year only with the end day unless they're different return I18n.t('%{start_date} - %{end_date}', { start_date: I18n.l( bin.date.getFullYear() === lastDay.getFullYear() ? 'date.formats.short' : 'date.formats.medium', bin.date ), end_date: I18n.l('date.formats.medium', lastDay) }) } else { // one-month bucket; label the month and year return I18n.l('date.formats.medium_month', bin.date) } } }
instructure/analytics
app/jsx/graphs/DateAlignedGraph.js
JavaScript
agpl-3.0
5,859
<?php /** * Output functions * Processing text for output such as pulling out URLs and extracting excerpts * * @package Elgg * @subpackage Core */ /** * Takes a string and turns any URLs into formatted links * * @param string $text The input string * * @return string The output string with formatted links **/ function parse_urls($text) { // @todo this causes problems with <attr = "val"> // must be in <attr="val"> format (no space). // By default htmlawed rewrites tags to this format. // if PHP supported conditional negative lookbehinds we could use this: // $r = preg_replace_callback('/(?<!=)(?<![ ])?(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', // // we can put , in the list of excluded char but need to keep . because of domain names. // it is removed in the callback. $r = preg_replace_callback('/(?<!=)(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', create_function( '$matches', ' $url = $matches[1]; $period = \'\'; if (substr($url, -1, 1) == \'.\') { $period = \'.\'; $url = trim($url, \'.\'); } $urltext = str_replace("/", "/<wbr />", $url); return "<a href=\"$url\" target=\"_blank\">$urltext</a>$period"; ' ), $text); return $r; } /** * Create paragraphs from text with line spacing * * @param string $pee The string * @deprecated Use elgg_autop instead * @todo Add deprecation warning in 1.9 * * @return string **/ function autop($pee) { return elgg_autop($pee); } /** * Create paragraphs from text with line spacing * * @param string $string The string * * @return string **/ function elgg_autop($string) { return ElggAutoP::getInstance()->process($string); } /** * Parse src variables to '//' instead of 'http(s)://' * * @param string $string The string * * @return string */ function minds_autosrc($string){ global $CONFIG; $replace = '//'; if($CONFIG->cdn_url){ $doc = new DOMDocument(); @$doc->loadHTML($string); $tags = $doc->getElementsByTagName('img'); foreach ($tags as $tag) { $src = $tag->getAttribute('src'); if($src){ $src = $CONFIG->cdn_url . 'thumbProxy?src='.urlencode($src).'&width=auto'; $tag->setAttribute('src', $src); } } $tags = $doc->getElementsByTagName('iframe'); foreach ($tags as $tag) { $src = $tag->getAttribute('src'); if($src){ $src = str_replace("http://", "//", $src); $tag->setAttribute('src', $src); } } return $doc->saveHTML(); } $output = str_replace( "src=\"http://", "src=\"$replace", $string ); return $output; } /** * Returns an excerpt. * Will return up to n chars stopping at the nearest space. * If no spaces are found (like in Japanese) will crop off at the * n char mark. Adds ... if any text was chopped. * * @param string $text The full text to excerpt * @param int $num_chars Return a string up to $num_chars long * * @return string * @since 1.7.2 */ function elgg_get_excerpt($text, $num_chars = 250) { $text = trim(elgg_strip_tags($text)); $string_length = elgg_strlen($text); if ($string_length <= $num_chars) { return $text; } // handle cases $excerpt = elgg_substr($text, 0, $num_chars); $space = elgg_strrpos($excerpt, ' ', 0); // don't crop if can't find a space. if ($space === FALSE) { $space = $num_chars; } $excerpt = trim(elgg_substr($excerpt, 0, $space)); if ($string_length != elgg_strlen($excerpt)) { $excerpt .= '...'; } return $excerpt; } /** * Handles formatting of ampersands in urls * * @param string $url The URL * * @return string * @since 1.7.1 */ function elgg_format_url($url) { return preg_replace('/&(?!amp;)/', '&amp;', $url); } /** * Converts an associative array into a string of well-formed attributes * * @note usually for HTML, but could be useful for XML too... * * @param array $attrs An associative array of attr => val pairs * * @return string HTML attributes to be inserted into a tag (e.g., <tag $attrs>) */ function elgg_format_attributes(array $attrs) { $attrs = elgg_clean_vars($attrs); $attributes = array(); if (isset($attrs['js'])) { //@todo deprecated notice? if (!empty($attrs['js'])) { $attributes[] = $attrs['js']; } unset($attrs['js']); } foreach ($attrs as $attr => $val) { $attr = strtolower($attr); if ($val === TRUE) { $val = $attr; //e.g. checked => TRUE ==> checked="checked" } // ignore $vars['entity'] => ElggEntity stuff if ($val !== NULL && $val !== false && (is_array($val) || !is_object($val))) { // allow $vars['class'] => array('one', 'two'); // @todo what about $vars['style']? Needs to be semi-colon separated... if (is_array($val)) { $val = implode(' ', $val); } $val = htmlspecialchars($val, ENT_QUOTES, 'UTF-8', false); $attributes[] = "$attr=\"$val\""; } } return implode(' ', $attributes); } /** * Preps an associative array for use in {@link elgg_format_attributes()}. * * Removes all the junk that {@link elgg_view()} puts into $vars. * Maintains backward compatibility with attributes like 'internalname' and 'internalid' * * @note This function is called automatically by elgg_format_attributes(). No need to * call it yourself before using elgg_format_attributes(). * * @param array $vars The raw $vars array with all it's dirtiness (config, url, etc.) * * @return array The array, ready to be used in elgg_format_attributes(). * @access private */ function elgg_clean_vars(array $vars = array()) { unset($vars['config']); unset($vars['url']); unset($vars['user']); // backwards compatibility code if (isset($vars['internalname'])) { $vars['name'] = $vars['internalname']; unset($vars['internalname']); } if (isset($vars['internalid'])) { $vars['id'] = $vars['internalid']; unset($vars['internalid']); } if (isset($vars['__ignoreInternalid'])) { unset($vars['__ignoreInternalid']); } if (isset($vars['__ignoreInternalname'])) { unset($vars['__ignoreInternalname']); } return $vars; } /** * Converts shorthand urls to absolute urls. * * If the url is already absolute or protocol-relative, no change is made. * * @example * elgg_normalize_url(''); // 'http://my.site.com/' * elgg_normalize_url('dashboard'); // 'http://my.site.com/dashboard' * elgg_normalize_url('http://google.com/'); // no change * elgg_normalize_url('//google.com/'); // no change * * @param string $url The URL to normalize * * @return string The absolute url */ function elgg_normalize_url($url) { // see https://bugs.php.net/bug.php?id=51192 // from the bookmarks save action. $php_5_2_13_and_below = version_compare(PHP_VERSION, '5.2.14', '<'); $php_5_3_0_to_5_3_2 = version_compare(PHP_VERSION, '5.3.0', '>=') && version_compare(PHP_VERSION, '5.3.3', '<'); if ($php_5_2_13_and_below || $php_5_3_0_to_5_3_2) { $tmp_address = str_replace("-", "", $url); $validated = filter_var($tmp_address, FILTER_VALIDATE_URL); } else { $validated = filter_var($url, FILTER_VALIDATE_URL); } // work around for handling absoluate IRIs (RFC 3987) - see #4190 if (!$validated && (strpos($url, 'http:') === 0) || (strpos($url, 'https:') === 0)) { $validated = true; } if ($validated) { // all normal URLs including mailto: return $url; } elseif (preg_match("#^(\#|\?|//)#i", $url)) { // '//example.com' (Shortcut for protocol.) // '?query=test', #target return $url; } elseif (stripos($url, 'javascript:') === 0 || stripos($url, 'mailto:') === 0) { // 'javascript:' and 'mailto:' // Not covered in FILTER_VALIDATE_URL return $url; } elseif (preg_match("#^[^/]*\.php(\?.*)?$#i", $url)) { // 'install.php', 'install.php?step=step' return elgg_get_site_url() . $url; } elseif (preg_match("#^[^/]*\.#i", $url)) { // 'example.com', 'example.com/subpage' return "http://$url"; } else { // 'page/handler', 'mod/plugin/file.php' // trim off any leading / because the site URL is stored // with a trailing / return elgg_get_site_url() . ltrim($url, '/'); } } /** * When given a title, returns a version suitable for inclusion in a URL * * @param string $title The title * * @return string The optimised title * @since 1.7.2 */ function elgg_get_friendly_title($title) { // return a URL friendly title to short circuit normal title formatting $params = array('title' => $title); $result = elgg_trigger_plugin_hook('format', 'friendly:title', $params, NULL); if ($result) { return $result; } // handle some special cases $title = str_replace('&amp;', 'and', $title); // quotes and angle brackets stored in the database as html encoded $title = htmlspecialchars_decode($title); $title = ElggTranslit::urlize($title); return $title; } /** * Formats a UNIX timestamp in a friendly way (eg "less than a minute ago") * * @see elgg_view_friendly_time() * * @param int $time A UNIX epoch timestamp * * @return string The friendly time string * @since 1.7.2 */ function elgg_get_friendly_time($time) { // return a time string to short circuit normal time formatting $params = array('time' => $time); $result = elgg_trigger_plugin_hook('format', 'friendly:time', $params, NULL); if ($result) { return $result; } $diff = time() - (int)$time; $minute = 60; $hour = $minute * 60; $day = $hour * 24; if ($diff < $minute) { return elgg_echo("friendlytime:justnow"); } else if ($diff < $hour) { $diff = round($diff / $minute); if ($diff == 0) { $diff = 1; } if ($diff > 1) { return elgg_echo("friendlytime:minutes", array($diff)); } else { return elgg_echo("friendlytime:minutes:singular", array($diff)); } } else { return date("F j, Y", $time); } /*} else if ($diff < $day) { $diff = round($diff / $hour); if ($diff == 0) { $diff = 1; } if ($diff > 1) { return elgg_echo("friendlytime:hours", array($diff)); } else { return elgg_echo("friendlytime:hours:singular", array($diff)); } } else { $diff = round($diff / $day); if ($diff == 0) { $diff = 1; } if ($diff > 1) { return elgg_echo("friendlytime:days", array($diff)); } else { return elgg_echo("friendlytime:days:singular", array($diff)); } }*/ } /** * Strip tags and offer plugins the chance. * Plugins register for output:strip_tags plugin hook. * Original string included in $params['original_string'] * * @param string $string Formatted string * * @return string String run through strip_tags() and any plugin hooks. */ function elgg_strip_tags($string) { $params['original_string'] = $string; $string = strip_tags($string); $string = elgg_trigger_plugin_hook('format', 'strip_tags', $params, $string); return $string; } /** * Apply html_entity_decode() to a string while re-entitising HTML * special char entities to prevent them from being decoded back to their * unsafe original forms. * * This relies on html_entity_decode() not translating entities when * doing so leaves behind another entity, e.g. &amp;gt; if decoded would * create &gt; which is another entity itself. This seems to escape the * usual behaviour where any two paired entities creating a HTML tag are * usually decoded, i.e. a lone &gt; is not decoded, but &lt;foo&gt; would * be decoded to <foo> since it creates a full tag. * * Note: This function is poorly explained in the manual - which is really * bad given its potential for misuse on user input already escaped elsewhere. * Stackoverflow is littered with advice to use this function in the precise * way that would lead to user input being capable of injecting arbitrary HTML. * * @param string $string * * @return string * * @author Pádraic Brady * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com) * @license Released under dual-license GPL2/MIT by explicit permission of Pádraic Brady * * @access private */ function _elgg_html_decode($string) { $string = str_replace( array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'), array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'), $string ); $string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8'); $string = str_replace( array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'), array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'), $string ); return $string; } /** * Unit tests for Output * * @param string $hook unit_test * @param string $type system * @param mixed $value Array of tests * @param mixed $params Params * * @return array * @access private */ function output_unit_test($hook, $type, $value, $params) { global $CONFIG; $value[] = $CONFIG->path . 'engine/tests/api/output.php'; return $value; } /** * Initialise the Output subsystem. * * @return void * @access private */ function output_init() { elgg_register_plugin_hook_handler('unit_test', 'system', 'output_unit_test'); } elgg_register_event_handler('init', 'system', 'output_init');
Minds/engine
lib/output.php
PHP
agpl-3.0
13,041
SavedSearchSelect.$inject = ['session', 'savedSearch']; export function SavedSearchSelect(session, savedSearch) { return { link: function(scope) { savedSearch.getUserSavedSearches(session.identity).then(function(res) { scope.searches = res; }); } }; }
lnogues/superdesk-client-core
scripts/superdesk-search/directives/SavedSearchSelect.js
JavaScript
agpl-3.0
316
import { Ability } from "./ability"; import { search } from "./utility/pathfinding"; import { Hex } from "./utility/hex"; import * as arrayUtils from "./utility/arrayUtils"; import { Drop } from "./drops"; import { Effect } from "./effect"; /** * Creature Class * * Creature contains all creatures properties and attacks */ export class Creature { /* Attributes * * NOTE : attributes and variables starting with $ are jquery element * and jquery function can be called dirrectly from them. * * // Jquery attributes * $display : Creature representation * $effects : Effects container (inside $display) * * // Normal attributes * x : Integer : Hex coordinates * y : Integer : Hex coordinates * pos : Object : Pos object for hex comparison {x,y} * * name : String : Creature name * id : Integer : Creature Id incrementing for each creature starting to 1 * size : Integer : Creature size in hexes (1,2 or 3) * type : Integer : Type of the creature stocked in the database * team : Integer : Owner's ID (0,1,2 or 3) * player : Player : Player object shortcut * hexagons : Array : Array containing the hexes where the creature is * * dead : Boolean : True if dead * stats : Object : Object containing stats of the creature * statsAlt : Object : Object containing the alteration value for each stat //todo * abilities : Array : Array containing the 4 abilities * remainingMove : Integer : Remaining moves allowed untill the end of turn * */ /* Constructor(obj) * * obj : Object : Object containing all creature stats * */ constructor(obj, game) { // Engine this.game = game; this.name = obj.name; this.id = game.creatureIdCounter++; this.x = obj.x - 0; this.y = obj.y - 0; this.pos = { x: this.x, y: this.y }; this.size = obj.size - 0; this.type = obj.type; this.level = obj.level - 0; this.realm = obj.realm; this.animation = obj.animation; this.display = obj.display; this.drop = obj.drop; this._movementType = "normal"; if (obj.movementType) { this._movementType = obj.movementType; } this.hexagons = []; // Game this.team = obj.team; // = playerID (0,1,2,3) this.player = game.players[obj.team]; this.dead = false; this.killer = undefined; this.hasWait = false; this.travelDist = 0; this.effects = []; this.dropCollection = []; this.protectedFromFatigue = (this.type == "--") ? true : false; this.turnsActive = 0; // Statistics this.baseStats = { health: obj.stats.health - 0, regrowth: obj.stats.regrowth - 0, endurance: obj.stats.endurance - 0, energy: obj.stats.energy - 0, meditation: obj.stats.meditation - 0, initiative: obj.stats.initiative - 0, offense: obj.stats.offense - 0, defense: obj.stats.defense - 0, movement: obj.stats.movement - 0, pierce: obj.stats.pierce - 0, slash: obj.stats.slash - 0, crush: obj.stats.crush - 0, shock: obj.stats.shock - 0, burn: obj.stats.burn - 0, frost: obj.stats.frost - 0, poison: obj.stats.poison - 0, sonic: obj.stats.sonic - 0, mental: obj.stats.mental - 0, moveable: true, fatigueImmunity: false, frozen: false, // Extra energy required for abilities reqEnergy: 0 }; this.stats = $j.extend({}, this.baseStats); //Copy this.health = obj.stats.health; this.endurance = obj.stats.endurance; this.energy = obj.stats.energy; this.remainingMove = 0; //Default value recovered each turn // Abilities this.abilities = [ new Ability(this, 0, game), new Ability(this, 1, game), new Ability(this, 2, game), new Ability(this, 3, game) ]; this.updateHex(); let dp = (this.type !== "--") ? "" : (this.team === 0) ? "red" : (this.team === 1) ? "blue" : (this.team === 2) ? "orange" : "green"; // Creature Container this.grp = game.Phaser.add.group(game.grid.creatureGroup, "creatureGrp_" + this.id); this.grp.alpha = 0; // Adding sprite this.sprite = this.grp.create(0, 0, this.name + dp + '_cardboard'); this.sprite.anchor.setTo(0.5, 1); // Placing sprite this.sprite.x = ((!this.player.flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2; this.sprite.y = this.display["offset-y"] + this.sprite.texture.height; // Placing Group this.grp.x = this.hexagons[this.size - 1].displayPos.x; this.grp.y = this.hexagons[this.size - 1].displayPos.y; this.facePlayerDefault(); // Hint Group this.hintGrp = game.Phaser.add.group(this.grp, "creatureHintGrp_" + this.id); this.hintGrp.x = 45 * this.size; this.hintGrp.y = -this.sprite.texture.height + 5; // Health indicator this.healthIndicatorGroup = game.Phaser.add.group(this.grp, "creatureHealthGrp_" + this.id); // Adding background sprite this.healthIndicatorSprite = this.healthIndicatorGroup.create( this.player.flipped ? 19 : 19 + 90 * (this.size - 1), 49, "p" + this.team + '_health'); // Add text this.healthIndicatorText = game.Phaser.add.text( this.player.flipped ? 45 : 45 + 90 * (this.size - 1), 63, this.health, { font: "bold 15pt Play", fill: "#fff", align: "center", stroke: "#000", strokeThickness: 6 }); this.healthIndicatorText.anchor.setTo(0.5, 0.5); this.healthIndicatorGroup.add(this.healthIndicatorText); // Hide it this.healthIndicatorGroup.alpha = 0; // State variable for displaying endurance/fatigue text this.fatigueText = ""; // Adding Himself to creature arrays and queue game.creatures[this.id] = this; this.delayable = true; this.delayed = false; this.materializationSickness = (this.type == "--") ? false : true; this.noActionPossible = false; } /* summon() * * Summon animation * */ summon() { let game = this.game; game.queue.addByInitiative(this); game.updateQueueDisplay(); game.grid.orderCreatureZ(); if (game.grid.materialize_overlay) { game.grid.materialize_overlay.alpha = 0.5; game.Phaser.add.tween(game.grid.materialize_overlay) .to({ alpha: 0 }, 500, Phaser.Easing.Linear.None) .start(); } game.Phaser.add.tween(this.grp) .to({ alpha: 1 }, 500, Phaser.Easing.Linear.None) .start(); // Reveal and position health indicator this.updateHealth(); this.healthShow(); // Trigger trap under this.hexagons.forEach((hex) => { hex.activateTrap(game.triggers.onStepIn, this); }); // Pickup drop this.pickupDrop(); } healthHide() { this.healthIndicatorGroup.alpha = 0; } healthShow() { this.healthIndicatorGroup.alpha = 1; } /* activate() * * Activate the creature by showing movement range and binding controls to this creature * */ activate() { this.travelDist = 0; this.oldEnergy = this.energy; this.oldHealth = this.health; this.noActionPossible = false; let game = this.game; let stats = this.stats; let varReset = function () { this.game.onReset(this); // Variables reset this.updateAlteration(); this.remainingMove = stats.movement; if (!this.materializationSickness) { // Fatigued creatures (endurance 0) should not regenerate, but fragile // ones (max endurance 0) should anyway if (!this.isFatigued()) { this.heal(stats.regrowth, true); if (stats.meditation > 0) { this.recharge(stats.meditation); } } else { if (stats.regrowth < 0) { this.heal(stats.regrowth, true); } else { this.hint("♦", 'damage'); } } } else { this.hint("♣", 'damage'); } setTimeout(() => { game.UI.energyBar.animSize(this.energy / stats.energy); game.UI.healthBar.animSize(this.health / stats.health); }, 1000); this.endurance = stats.endurance; this.abilities.forEach((ability) => { ability.reset(); }); }.bind(this); // Frozen effect if (stats.frozen) { varReset(); var interval = setInterval(() => { if (!game.turnThrottle) { clearInterval(interval); game.skipTurn({ tooltip: "Frozen" }); } }, 50); return; } if (!this.hasWait) { varReset(); // Trigger game.onStartPhase(this); } this.materializationSickness = false; var interval = setInterval(() => { if (!game.freezedInput) { clearInterval(interval); if (game.turn >= game.minimumTurnBeforeFleeing) { game.UI.btnFlee.changeState("normal"); } game.startTimer(); this.queryMove(); } }, 50); } /* deactivate(wait) * * wait : Boolean : Deactivate while waiting or not * * Preview the creature position at the given coordinates * */ deactivate(wait) { let game = this.game; this.hasWait = this.delayed = !!wait; this.stats.frozen = false; // Effects triggers if (!wait) { this.turnsActive += 1; game.onEndPhase(this); } this.delayable = false; } /* wait() * * Move the creature to the end of the queue * */ wait() { let abilityAvailable = false; if (this.delayed) { return; } // If at least one ability has not been used this.abilities.forEach((ability) => { abilityAvailable = abilityAvailable || !ability.used; }); if (this.remainingMove > 0 && abilityAvailable) { this.delay(this.game.activeCreature === this); this.deactivate(true); } } delay(excludeActiveCreature) { let game = this.game; game.queue.delay(this); this.delayable = false; this.delayed = true; this.hint("Delayed", "msg_effects"); game.updateQueueDisplay(excludeActiveCreature); } /* queryMove() * * launch move action query * */ queryMove(o) { let game = this.game; if (this.dead) { // Creatures can die during their turns from trap effects; make sure this // function doesn't do anything return; } // Once Per Damage Abilities recover game.creatures.forEach((creature) => { //For all Creature if (creature instanceof Creature) { creature.abilities.forEach((ability) => { if (game.triggers.oncePerDamageChain.test(ability.getTrigger())) { ability.setUsed(false); } }); } }); let remainingMove = this.remainingMove; // No movement range if unmoveable if (!this.stats.moveable) { remainingMove = 0; } o = $j.extend({ targeting:false, noPath: false, isAbility: false, ownCreatureHexShade: true, range: game.grid.getMovementRange( this.x, this.y, remainingMove, this.size, this.id), callback: function (hex, args) { if (hex.x == args.creature.x && hex.y == args.creature.y) { // Prevent null movement game.activeCreature.queryMove(); return; } game.gamelog.add({ action: "move", target: { x: hex.x, y: hex.y } }); args.creature.delayable = false; game.UI.btnDelay.changeState("disabled"); args.creature.moveTo(hex, { animation: args.creature.movementType() === "flying" ? "fly" : "walk", callback: function () { game.activeCreature.queryMove(); } }); } }, o); if (!o.isAbility) { if (game.UI.selectedAbility != -1) { this.hint("Canceled", 'gamehintblack'); } $j("#abilities .ability").removeClass("active"); game.UI.selectAbility(-1); game.UI.checkAbilities(); game.UI.updateQueueDisplay(); } game.grid.orderCreatureZ(); this.facePlayerDefault(); this.updateHealth(); if (this.movementType() === "flying") { o.range = game.grid.getFlyingRange( this.x, this.y, remainingMove, this.size, this.id); } let selectNormal = function (hex, args) { args.creature.tracePath(hex); }; let selectFlying = function (hex, args) { args.creature.tracePosition({ x: hex.x, y: hex.y, overlayClass: "creature moveto selected player" + args.creature.team }); }; let select = (o.noPath || this.movementType() === "flying") ? selectFlying : selectNormal; if (this.noActionPossible) { game.grid.querySelf({ fnOnConfirm: function () { game.UI.btnSkipTurn.click(); }, fnOnCancel: function () { }, confirmText: "Skip turn" }); } else { game.grid.queryHexes({ fnOnSelect: select, fnOnConfirm: o.callback, args: { creature: this, args: o.args }, // Optional args size: this.size, flipped: this.player.flipped, id: this.id, hexes:  o.range, ownCreatureHexShade: o.ownCreatureHexShade, targeting: o.targeting }); } } /* previewPosition(hex) * * hex : Hex : Position * * Preview the creature position at the given Hex * */ previewPosition(hex) { let game = this.game; game.grid.cleanOverlay("hover h_player" + this.team); if (!game.grid.hexes[hex.y][hex.x].isWalkable(this.size, this.id)) { return; // Break if not walkable } this.tracePosition({ x: hex.x, y: hex.y, overlayClass: "hover h_player" + this.team }); } /* cleanHex() * * Clean current creature hexagons * */ cleanHex() { this.hexagons.forEach((hex) => { hex.creature = undefined; }); this.hexagons = []; } /* updateHex() * * Update the current hexes containing the creature and their display * */ updateHex() { let count = this.size, i; for (i = 0; i < count; i++) { this.hexagons.push(this.game.grid.hexes[this.y][this.x - i]); } this.hexagons.forEach((hex) => { hex.creature = this; }); } /* faceHex(facefrom,faceto) * * facefrom : Hex or Creature : Hex to face from * faceto : Hex or Creature : Hex to face * * Face creature at given hex * */ faceHex(faceto, facefrom, ignoreCreaHex, attackFix) { if (!facefrom) { facefrom = (this.player.flipped) ? this.hexagons[this.size - 1] : this.hexagons[0]; } if (ignoreCreaHex && this.hexagons.indexOf(faceto) != -1 && this.hexagons.indexOf(facefrom) != -1) { this.facePlayerDefault(); return; } if (faceto instanceof Creature) { faceto = (faceto.size < 2) ? faceto.hexagons[0] : faceto.hexagons[1]; } if (faceto.x == facefrom.x && faceto.y == facefrom.y) { this.facePlayerDefault(); return; } if (attackFix && this.size > 1) { //only works on 2hex creature targeting the adjacent row if (facefrom.y % 2 === 0) { if (faceto.x - this.player.flipped == facefrom.x) { this.facePlayerDefault(); return; } } else { if (faceto.x + 1 - this.player.flipped == facefrom.x) { this.facePlayerDefault(); return; } } } if (facefrom.y % 2 === 0) { var flipped = (faceto.x <= facefrom.x); } else { var flipped = (faceto.x < facefrom.x); } if (flipped) { this.sprite.scale.setTo(-1, 1); } else { this.sprite.scale.setTo(1, 1); } this.sprite.x = ((!flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2; } /* facePlayerDefault() * * Face default direction * */ facePlayerDefault() { if (this.player.flipped) { this.sprite.scale.setTo(-1, 1); } else { this.sprite.scale.setTo(1, 1); } this.sprite.x = ((!this.player.flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2; } /* moveTo(hex,opts) * * hex : Hex : Destination Hex * opts : Object : Optional args object * * Move the creature along a calculated path to the given coordinates * */ moveTo(hex, opts) { let game = this.game, defaultOpt = { callback: function () { return true; }, callbackStepIn: function () { return true; }, animation: this.movementType() === "flying" ? "fly" : "walk", ignoreMovementPoint: false, ignorePath: false, customMovementPoint: 0, overrideSpeed: 0, turnAroundOnComplete: true }, path; opts = $j.extend(defaultOpt, opts); // Teleportation ignores moveable if (this.stats.moveable || opts.animation === "teleport") { let x = hex.x; let y = hex.y; if (opts.ignorePath || opts.animation == "fly") { path = [hex]; } else { path = this.calculatePath(x, y); } if (path.length === 0) { return; // Break if empty path } game.grid.xray(new Hex(0, 0, false, game)); // Clean Xray this.travelDist = 0; game.animations[opts.animation](this, path, opts); } else { game.log("This creature cannot be moved"); } let interval = setInterval(() => { if (!game.freezedInput) { clearInterval(interval); opts.callback(); } }, 100); } /* tracePath(hex) * * hex : Hex : Destination Hex * * Trace the path from the current possition to the given coordinates * */ tracePath(hex) { let game = this.game, x = hex.x, y = hex.y, path = this.calculatePath(x, y); // Store path in grid to be able to compare it later if (path.length === 0) { return; // Break if empty path } path.forEach((item) => { this.tracePosition({ x: item.x, y: item.y, displayClass: "adj", drawOverCreatureTiles: false }); }); // Trace path // Highlight final position var last = arrayUtils.last(path); this.tracePosition({ x: last.x, y: last.y, overlayClass: "creature moveto selected player" + this.team, drawOverCreatureTiles: false }); } tracePosition(args) { let defaultArgs = { x: this.x, y: this.y, overlayClass: "", displayClass: "", drawOverCreatureTiles: true }; args = $j.extend(defaultArgs, args); for (let i = 0; i < this.size; i++) { let canDraw = true; if(!args.drawOverCreatureTiles){ // then check to ensure this is not a creature tile for(let j = 0; j < this.hexagons.length;j++){ if(this.hexagons[j].x == args.x-i && this.hexagons[j].y == args.y){ canDraw = false; break; } } } if(canDraw){ let hex = this.game.grid.hexes[args.y][args.x - i]; this.game.grid.cleanHex(hex); hex.overlayVisualState(args.overlayClass); hex.displayVisualState(args.displayClass); } } } /* calculatePath(x,y) * * x : Integer : Destination coordinates * y : Integer : Destination coordinates * * return : Array : Array containing the path hexes * */ calculatePath(x, y) { let game = this.game; return search( game.grid.hexes[this.y][this.x], game.grid.hexes[y][x], this.size, this.id, this.game.grid ); // Calculate path } /* calcOffset(x,y) * * x : Integer : Destination coordinates * y : Integer : Destination coordinates * * return : Object : New position taking into acount the size, orientation and obstacle {x,y} * * Return the first possible position for the creature at the given coordinates * */ calcOffset(x, y) { let offset = (game.players[this.team].flipped) ? this.size - 1 : 0, mult = (game.players[this.team].flipped) ? 1 : -1, // For FLIPPED player game = this.game; for (let i = 0; i < this.size; i++) { // Try next hexagons to see if they fit if ((x + offset - i * mult >= game.grid.hexes[y].length) || (x + offset - i * mult < 0)) { continue; } if (game.grid.hexes[y][x + offset - i * mult].isWalkable(this.size, this.id)) { x += offset - i * mult; break; } } return { x: x, y: y }; } /* getInitiative() * * return : Integer : Initiative value to order the queue * */ getInitiative() { // To avoid 2 identical initiative return this.stats.initiative * 500 - this.id; } /* adjacentHexes(dist) * * dist : Integer : Distance in hexagons * * return : Array : Array of adjacent hexagons * */ adjacentHexes(dist, clockwise) { let game = this.game; // TODO Review this algo to allow distance if (!!clockwise) { let hexes = [], c; let o = (this.y % 2 === 0) ? 1 : 0; if (this.size == 1) { c = [{ y: this.y, x: this.x + 1 }, { y: this.y - 1, x: this.x + o }, { y: this.y - 1, x: this.x - 1 + o }, { y: this.y, x: this.x - 1 }, { y: this.y + 1, x: this.x - 1 + o }, { y: this.y + 1, x: this.x + o } ]; } if (this.size == 2) { c = [{ y: this.y, x: this.x + 1 }, { y: this.y - 1, x: this.x + o }, { y: this.y - 1, x: this.x - 1 + o }, { y: this.y - 1, x: this.x - 2 + o }, { y: this.y, x: this.x - 2 }, { y: this.y + 1, x: this.x - 2 + o }, { y: this.y + 1, x: this.x - 1 + o }, { y: this.y + 1, x: this.x + o } ]; } if (this.size == 3) { c = [{ y: this.y, x: this.x + 1 }, { y: this.y - 1, x: this.x + o }, { y: this.y - 1, x: this.x - 1 + o }, { y: this.y - 1, x: this.x - 2 + o }, { y: this.y - 1, x: this.x - 3 + o }, { y: this.y, x: this.x - 3 }, { y: this.y + 1, x: this.x - 3 + o }, { y: this.y + 1, x: this.x - 2 + o }, { y: this.y + 1, x: this.x - 1 + o }, { y: this.y + 1, x: this.x + o } ]; } let total = c.length; for (let i = 0; i < total; i++) { const { x, y } = c[i]; if (game.grid.hexExists(y, x)) { hexes.push(game.grid.hexes[y][x]); } } return hexes; } if (this.size > 1) { let hexes = this.hexagons[0].adjacentHex(dist); let lasthexes = this.hexagons[this.size - 1].adjacentHex(dist); hexes.forEach((hex) => { if (arrayUtils.findPos(this.hexagons, hex)) { arrayUtils.removePos(hexes, hex); } // Remove from array if own creature hex }); lasthexes.forEach((hex) => { // If node doesnt already exist in final collection and if it's not own creature hex if (!arrayUtils.findPos(hexes, hex) && !arrayUtils.findPos(this.hexagons, hex)) { hexes.push(hex); } }); return hexes; } else { return this.hexagons[0].adjacentHex(dist); } } /** * Restore energy up to the max limit * amount: amount of energy to restore */ recharge(amount) { this.energy = Math.min(this.stats.energy, this.energy + amount); } /* heal(amount) * * amount : Damage : Amount of health point to restore */ heal(amount, isRegrowth) { let game = this.game; // Cap health point amount = Math.min(amount, this.stats.health - this.health); if (this.health + amount < 1) { amount = this.health - 1; // Cap to 1hp } this.health += amount; // Health display Update this.updateHealth(isRegrowth); if (amount > 0) { if (isRegrowth) { this.hint("+" + amount + " ♥", 'healing d' + amount); } else { this.hint("+" + amount, 'healing d' + amount); } game.log("%CreatureName" + this.id + "% recovers +" + amount + " health"); } else if (amount === 0) { if (isRegrowth) { this.hint("♦", 'msg_effects'); } else { this.hint("!", 'msg_effects'); } } else { if (isRegrowth) { this.hint(amount + " ♠", 'damage d' + amount); } else { this.hint(amount, 'damage d ' + amount); } game.log("%CreatureName" + this.id + "% loses " + amount + " health"); } game.onHeal(this, amount); } /* takeDamage(damage) * * damage : Damage : Damage object * * return : Object : Contains damages dealed and if creature is killed or not */ takeDamage(damage, o) { let game = this.game; if (this.dead) { game.log("%CreatureName" + this.id + "% is already dead, aborting takeDamage call."); return; } let defaultOpt = { ignoreRetaliation: false, isFromTrap: false }; o = $j.extend(defaultOpt, o); // Determine if melee attack damage.melee = false; this.adjacentHexes(1).forEach((hex) => { if (damage.attacker == hex.creature) { damage.melee = true; } }); damage.target = this; damage.isFromTrap = o.isFromTrap; // Trigger game.onUnderAttack(this, damage); game.onAttack(damage.attacker, damage); // Calculation if (damage.status === "") { // Damages let dmg = damage.applyDamage(); let dmgAmount = dmg.total; if (!isFinite(dmgAmount)) { // Check for Damage Errors this.hint("Error", 'damage'); game.log("Oops something went wrong !"); return { damages: 0, kill: false }; } this.health -= dmgAmount; this.health = (this.health < 0) ? 0 : this.health; // Cap this.addFatigue(dmgAmount); // Display let nbrDisplayed = (dmgAmount) ? "-" + dmgAmount : 0; this.hint(nbrDisplayed, 'damage d' + dmgAmount); if (!damage.noLog) { game.log("%CreatureName" + this.id + "% is hit : " + nbrDisplayed + " health"); } // If Health is empty if (this.health <= 0) { this.die(damage.attacker); return { damages: dmg, damageObj: damage, kill: true }; // Killed } // Effects damage.effects.forEach((effect) => { this.addEffect(effect); }); // Unfreeze if taking non-zero damage if (dmgAmount > 0) { this.stats.frozen = false; } // Health display Update // Note: update health after adding effects as some effects may affect // health display this.updateHealth(); game.UI.updateFatigue(); // Trigger if (!o.ignoreRetaliation) { game.onDamage(this, damage); } return { damages: dmg, damageObj: damage, kill: false }; // Not Killed } else { if (damage.status == "Dodged") { // If dodged if (!damage.noLog) { game.log("%CreatureName" + this.id + "% dodged the attack"); } } if (damage.status == "Shielded") { // If Shielded if (!damage.noLog) { game.log("%CreatureName" + this.id + "% shielded the attack"); } } if (damage.status == "Disintegrated") { // If Disintegrated if (!damage.noLog) { game.log("%CreatureName" + this.id + "% has been disintegrated"); } this.die(damage.attacker); } // Hint this.hint(damage.status, 'damage ' + damage.status.toLowerCase()); } return { damageObj: damage, kill: false }; // Not killed } updateHealth(noAnimBar) { let game = this.game; if (this == game.activeCreature && !noAnimBar) { game.UI.healthBar.animSize(this.health / this.stats.health); } // Dark Priest plasma shield when inactive if (this.type == "--") { if (this.hasCreaturePlayerGotPlasma() && this !== game.activeCreature) { this.displayPlasmaShield(); } else { this.displayHealthStats() } } else { this.displayHealthStats(); } } displayHealthStats() { if (this.stats.frozen) { this.healthIndicatorSprite.loadTexture("p" + this.team + "_frozen"); } else { this.healthIndicatorSprite.loadTexture("p" + this.team + "_health"); } this.healthIndicatorText.setText(this.health); } displayPlasmaShield() { this.healthIndicatorSprite.loadTexture("p" + this.team + "_plasma"); this.healthIndicatorText.setText(this.player.plasma); } hasCreaturePlayerGotPlasma() { return this.player.plasma > 0; } addFatigue(dmgAmount) { if (!this.stats.fatigueImmunity) { this.endurance -= dmgAmount; this.endurance = this.endurance < 0 ? 0 : this.endurance; // Cap } this.game.UI.updateFatigue(); } /* addEffect(effect) * * effect : Effect : Effect object * */ addEffect(effect, specialString, specialHint) { let game = this.game; if (!effect.stackable && this.findEffect(effect.name).length !== 0) { //G.log(this.player.name+"'s "+this.name+" is already affected by "+effect.name); return false; } effect.target = this; this.effects.push(effect); game.onEffectAttach(this, effect); this.updateAlteration(); if (effect.name !== "") { if (specialHint || effect.specialHint) { this.hint(specialHint, 'msg_effects'); } else { this.hint(effect.name, 'msg_effects'); } if (specialString) { game.log(specialString); } else { game.log("%CreatureName" + this.id + "% is affected by " + effect.name); } } } /** * Add effect, but if the effect is already attached, replace it with the new * effect. * Note that for stackable effects, this is the same as addEffect() * * effect - the effect to add */ replaceEffect(effect) { if (!effect.stackable && this.findEffect(effect.name).length !== 0) { this.removeEffect(effect.name); } this.addEffect(effect); } /** * Remove an effect by name * * name - name of effect */ removeEffect(name) { let totalEffects = this.effects.length; for (var i = 0; i < totalEffects; i++) { if (this.effects[i].name === name) { this.effects.splice(i, 1); break; } } } hint(text, cssClass) { let game = this.game, tooltipSpeed = 250, tooltipDisplaySpeed = 500, tooltipTransition = Phaser.Easing.Linear.None; let hintColor = { confirm: { fill: "#ffffff", stroke: "#000000" }, gamehintblack: { fill: "#ffffff", stroke: "#000000" }, healing: { fill: "#00ff00" }, msg_effects: { fill: "#ffff00" } }; let style = $j.extend({ font: "bold 20pt Play", fill: "#ff0000", align: "center", stroke: "#000000", strokeThickness: 2 }, hintColor[cssClass]); // Remove constant element this.hintGrp.forEach((grpHintElem) => { if (grpHintElem.cssClass == 'confirm') { grpHintElem.cssClass = "confirm_deleted"; grpHintElem.tweenAlpha = game.Phaser.add.tween(grpHintElem).to({ alpha: 0 }, tooltipSpeed, tooltipTransition).start(); grpHintElem.tweenAlpha.onComplete.add(function () { this.destroy(); }, grpHintElem); } }, this, true); var hint = game.Phaser.add.text(0, 50, text, style); hint.anchor.setTo(0.5, 0.5); hint.alpha = 0; hint.cssClass = cssClass; if (cssClass == 'confirm') { hint.tweenAlpha = game.Phaser.add.tween(hint) .to({ alpha: 1 }, tooltipSpeed, tooltipTransition) .start(); } else { hint.tweenAlpha = game.Phaser.add.tween(hint) .to({ alpha: 1 }, tooltipSpeed, tooltipTransition) .to({ alpha: 1 }, tooltipDisplaySpeed, tooltipTransition) .to({ alpha: 0 }, tooltipSpeed, tooltipTransition).start(); hint.tweenAlpha.onComplete.add(function () { this.destroy(); }, hint); } this.hintGrp.add(hint); // Stacking this.hintGrp.forEach((grpHintElem) => { let index = this.hintGrp.total - this.hintGrp.getIndex(grpHintElem) - 1; let offset = -50 * index; if (grpHintElem.tweenPos) { grpHintElem.tweenPos.stop(); } grpHintElem.tweenPos = game.Phaser.add.tween(grpHintElem).to({ y: offset }, tooltipSpeed, tooltipTransition).start(); }, this, true); } /* updateAlteration() * * Update the stats taking into account the effects' alteration * */ updateAlteration() { this.stats = $j.extend({}, this.baseStats); // Copy let buffDebuffArray = this.effects; buffDebuffArray.forEach((buff) => { $j.each(buff.alterations, (key, value) => { if (typeof value == "string") { // Multiplication Buff if (value.match(/\*/)) { this.stats[key] = eval(this.stats[key] + value); } // Division Debuff if (value.match(/\//)) { this.stats[key] = eval(this.stats[key] + value); } } // Usual Buff/Debuff if ((typeof value) == "number") { this.stats[key] += value; } // Boolean Buff/Debuff if ((typeof value) == "boolean") { this.stats[key] = value; } }); }); this.stats.endurance = Math.max(this.stats.endurance, 0); this.endurance = Math.min(this.endurance, this.stats.endurance); this.energy = Math.min(this.energy, this.stats.energy); this.remainingMove = Math.min(this.remainingMove, this.stats.movement); } /* die() * * kill animation. remove creature from queue and from hexes * * killer : Creature : Killer of this creature * */ die(killer) { let game = this.game; game.log("%CreatureName" + this.id + "% is dead"); this.dead = true; // Triggers game.onCreatureDeath(this); this.killer = killer.player; let isDeny = (this.killer.flipped == this.player.flipped); // Drop item if (game.unitDrops == 1 && this.drop) { var offsetX = (this.player.flipped) ? this.x - this.size + 1 : this.x; new Drop(this.drop.name, this.drop.health, this.drop.energy, offsetX, this.y, game); } if (!game.firstKill && !isDeny) { // First Kill this.killer.score.push({ type: "firstKill" }); game.firstKill = true; } if (this.type == "--") { // If Dark Priest if (isDeny) { // TEAM KILL (DENY) this.killer.score.push({ type: "deny", creature: this }); } else { // Humiliation this.killer.score.push({ type: "humiliation", player: this.team }); } } if (!this.undead) { // Only if not undead if (isDeny) { // TEAM KILL (DENY) this.killer.score.push({ type: "deny", creature: this }); } else { // KILL this.killer.score.push({ type: "kill", creature: this }); } } if (this.player.isAnnihilated()) { // Remove humiliation as annihilation is an upgrade let total = this.killer.score.length; for (let i = 0; i < total; i++) { var s = this.killer.score[i]; if (s.type == "humiliation") { if (s.player == this.team) { this.killer.score.splice(i, 1); } break; } } // ANNIHILATION this.killer.score.push({ type: "annihilation", player: this.team }); } if (this.type == "--") { this.player.deactivate(); // Here because of score calculation } // Kill animation var tweenSprite = game.Phaser.add.tween(this.sprite).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None).start(); var tweenHealth = game.Phaser.add.tween(this.healthIndicatorGroup).to({ alpha: 0 }, 500, Phaser.Easing.Linear.None).start(); tweenSprite.onComplete.add(() => { this.sprite.destroy(); }); tweenHealth.onComplete.add(() => { this.healthIndicatorGroup.destroy(); }); this.cleanHex(); game.queue.remove(this); game.updateQueueDisplay(); game.grid.updateDisplay(); if (game.activeCreature === this) { game.nextCreature(); return; } //End turn if current active creature die // As hex occupation changes, path must be recalculated for the current creature not the dying one game.activeCreature.queryMove(); // Queue cleaning game.UI.updateActivebox(); game.UI.updateQueueDisplay(); // Just in case } isFatigued() { return this.endurance === 0 && !this.isFragile(); } isFragile() { return this.stats.endurance === 0; } /* getHexMap() * * shortcut convenience function to grid.getHexMap */ getHexMap(map, invertFlipped) { var x = (this.player.flipped ? !invertFlipped : invertFlipped) ? this.x + 1 - this.size : this.x; return this.game.grid.getHexMap(x, this.y - map.origin[1], 0 - map.origin[0], (this.player.flipped ? !invertFlipped : invertFlipped), map); } getBuffDebuff(stat) { let buffDebuffArray = this.effects.concat(this.dropCollection), buff = 0, debuff = 0, buffObjs = { effects: [], drops: [] }; let addToBuffObjs = function (obj) { if (obj instanceof Effect) { buffObjs.effects.push(obj); } else if (obj instanceof Drop) { buffObjs.drops.push(obj); } }; buffDebuffArray.forEach((buff) => { let o = buff; $j.each(buff.alterations, (key, value) => { if (typeof value == "string") { if (key === stat || stat === undefined) { // Multiplication Buff if (value.match(/\*/)) { addToBuffObjs(o); let base = this.stats[key]; let result = eval(this.stats[key] + value); if (result > base) { buff += result - base; } else { debuff += result - base; } } // Division Debuff if (value.match(/\//)) { addToBuffObjs(o); let base = this.stats[key]; let result = eval(this.stats[key] + value); if (result > base) { buff += result - base; } else { debuff += result - base; } } } } // Usual Buff/Debuff if ((typeof value) == "number") { if (key === stat || stat === undefined) { addToBuffObjs(o); if (value > 0) { buff += value; } else { debuff += value; } } } }); }); return { buff: buff, debuff: debuff, objs: buffObjs }; } findEffect(name) { let ret = []; this.effects.forEach((effect) => { if (effect.name == name) { ret.push(effect); } }); return ret; } // Make units transparent xray(enable) { let game = this.game; if (enable) { game.Phaser.add.tween(this.grp) .to({ alpha: 0.5 }, 250, Phaser.Easing.Linear.None) .start(); } else { game.Phaser.add.tween(this.grp) .to({ alpha: 1 }, 250, Phaser.Easing.Linear.None) .start(); } } pickupDrop() { this.hexagons.forEach((hex) => { hex.pickupDrop(this); }); } /** * Get movement type for this creature * @return {string} "normal", "hover", or "flying" */ movementType() { let totalAbilities = this.abilities.length; // If the creature has an ability that modifies movement type, use that, // otherwise use the creature's base movement type for (let i = 0; i < totalAbilities; i++) { if ('movementType' in this.abilities[i]) { return this.abilities[i].movementType(); } } return this._movementType; } }
ShaneWalsh/AncientBeast
src/creature.js
JavaScript
agpl-3.0
37,616
class GroupSerializer < ActiveModel::Serializer embed :ids, include: true attributes :id, :organisation_id, :cohort_id, :key, :name, :created_at, :description, :members_can_add_members, :members_can_create_subgroups, :members_can_start_discussions, :members_can_edit_discussions, :members_can_edit_comments, :members_can_raise_proposals, :members_can_vote, :memberships_count, :members_count, :visible_to, :membership_granted_upon, :discussion_privacy_options, :logo_url_medium, :cover_url_desktop, :has_discussions, :has_multiple_admins has_one :parent, serializer: GroupSerializer, root: 'groups' def logo_url_medium object.logo.url(:medium) end def include_logo_url_medium? object.logo.present? end def cover_url_desktop object.cover_photo.url(:desktop) end def include_cover_url_desktop? object.cover_photo.present? end def members_can_raise_proposals object.members_can_raise_motions end def has_discussions object.discussions_count > 0 end def has_multiple_admins object.admins.count > 1 end end
kimihito/loomio
app/serializers/group_serializer.rb
Ruby
agpl-3.0
1,358
/* sb0t ares chat server Copyright (C) 2017 AresChat This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace core.Udp { class UdpNode { public IPAddress IP { get; set; } public ushort Port { get; set; } public int Ack { get; set; } public int Try { get; set; } public ulong LastConnect { get; set; } public ulong LastSentIPS { get; set; } public EndPoint EndPoint { get { return new IPEndPoint(this.IP, this.Port); } } } }
AresChat/sb0t
core/Udp/UdpNode.cs
C#
agpl-3.0
1,310
class Admin::AdminSerializer < ActiveModel::Serializer attributes :id, :name, :email, :teachers def teachers teacher_ids = User.find(object.id).teacher_ids teachers_data = TeachersData.run(teacher_ids) teachers_data.map{|t| Admin::TeacherSerializer.new(t, root: false) } end end
ddmck/Empirical-Core
app/serializers/admin/admin_serializer.rb
Ruby
agpl-3.0
299
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later # version. # # Skarphed 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with Skarphed. # If not, see http://www.gnu.org/licenses/. ########################################################### import os from daemon import Daemon from time import sleep from StringIO import StringIO from traceback import print_exc from skarphedcore.configuration import Configuration from skarphedcore.database import Database from skarphedcore.core import Core from skarphedcore.module import Module from common.errors import OperationException class Operation(object): """ Contais everything necessary to Handle Operations """ STATUS_PENDING = 0 STATUS_ACTIVE = 1 STATUS_FAILED = 2 VALID_STORAGE_TYPES = ('int','bool','str','unicode') def __init__(self, parent_id = None): """ """ self._id = None self._parent = parent_id self._values = {} @classmethod def drop_operation(cls,operation_id): """ Drops an Operation, identified by it's Operation Id and it's children recursively Drop deletes the Operations from Database """ db = Database() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;" cur = db.query(stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.drop_operation(row["OPE_ID"]) stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS IN (0, 2) ;" db.query(stmnt,(operation_id,),commit=True) @classmethod def retry_operation(cls,operation_id): """ Resets the state of an operation and it's children recursively to 0 (PENDING) The operation is identified by a given operationId """ db = Database() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 2 ;" cur = db.query(stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.retry_operation(row["OPE_ID"]) stmnt = "UPDATE OPERATIONS SET OPE_STATUS = 0 WHERE OPE_ID = ? AND OPE_STATUS = 2 ;" db.query(stmnt,(operation_id,),commit=True) @classmethod def cancel_operation(cls,operation_id): """ Cancels an Operation, identified by it's Operation Id and it's children recursively Cancel Deletes the Operation from Database """ db = Database() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;" cur = db.query(stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.cancel_operation(row["OPE_ID"]) stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS = 0 ;" db.query(stmnt,(operation_id,),commit=True) @classmethod def restore_operation(cls, operation_record): """ Restore an Operationobject stored in the database by a Dataset consisting of the operation's ID and the operation's TYPE: For example: {"OPE_ID": 100, "OPE_TYPE": "TestOperation"} Restores the Operationobject's _values-attribute by the data saved in the DB-Table OPERATIONDATA """ classname = operation_record["OPE_TYPE"] module = "" #TODO Implement modulename from database if Operation belongs to Module is_operation_of_module = False exec """ try: type(%(class)s) except NameError,e: is_operation_of_module = True"""%{'class':classname} if is_operation_of_module: exec """ from %(module)s import %(class)s operation = %(class)s()"""%{'class':classname,'module':module} else: exec """ operation = %(class)s()"""%{'class':classname} operation.set_id(operation_record['OPE_ID']) db = Database() stmnt = "SELECT OPD_KEY, OPD_VALUE, OPD_TYPE FROM OPERATIONDATA WHERE OPD_OPE_ID = ? ;" cur = db.query(stmnt,(operation_record["OPE_ID"],)) for row in cur.fetchallmap(): val = row["OPD_VALUE"] exec """val = %s(val)"""%row["OPD_TYPE"] operation.set_value(row["OPD_KEY"], val) return operation @classmethod def process_children(cls, operation): """ Recursively executes the workloads of Operation's Childoperations It hereby catches exceptions in the workloads, sets the OPE_STATUS to 2 (FAILED) if a catch occurs, then passes the exception on to the higher layer. If an Operation succeeds, it's entry in DB gets deleted """ db = Database() stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT = ? ORDER BY OPE_INVOKED ;" stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 WHERE OPE_ID = ? ;" cur = db.query(stmnt,(operation.get_id(),)) for row in cur.fetchallmap(): child_operation = cls.restore_operation(row) db.query(stmnt_lock,(child_operation.get_id(),),commit=True) try: cls.process_children(child_operation) child_operation.do_workload() except Exception,e: stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;" db.query(stmnt_err,(int(row["OPE_ID"]),),commit=True) #TODO GENERATE ERROR IN LOG raise e stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_ID = ?;" db.query(stmnt_delete,(child_operation.get_id(),),commit=True) @classmethod def process_next(cls): """ Sets the status of the next toplevel operation to 1 (ACTIVE) Fetches the next toplevel-operation from the database, applies a FILESYSTEMLOCK! Which is /tmp/scv_operating.lck !!! """ db = Database() configuration = Configuration() if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"): return False lockfile = open(configuration.get_entry("core.webpath")+"/scv_operating.lck","w") lockfile.close() stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 \ WHERE OPE_ID IN ( \ SELECT OPE_ID FROM OPERATIONS \ WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0 \ AND OPE_INVOKED = ( \ SELECT MIN(OPE_INVOKED) FROM OPERATIONS \ WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0) \ ) ;" stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 1 ;" db.query(stmnt_lock,commit=True) cur = db.query(stmnt) res = cur.fetchallmap() if len(res) > 0: operation = cls.restore_operation(res[0]) try: cls.process_children(operation) operation.do_workload() except Exception, e: stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;" db.query(stmnt_err,(operation.get_id(),),commit=True) error = StringIO() print_exc(None,error) Core().log(error.getvalue()) ret = True else: ret = False stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_STATUS = 1 ;" db.query(stmnt_delete,commit=True) db.commit() try: os.unlink(configuration.get_entry("core.webpath")+"/scv_operating.lck") except OSError,e : raise OperationException(OperationException.get_msg(0)) return ret @classmethod def get_current_operations_for_gui(cls, operation_types=None): """ Returns all Operations in an associative array. The array's indices are the operationIDs The Objects contain all information about the operations, including the Data """ db = Database() #TODO CHECK HOW LISTS ARE HANDLED IN FDB if operation_types is not None and type(operation_types) == list: stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS WHERE OPE_TYPE IN (?) ORDER BY OPE_INVOKED ;" cur = db.query(stmnt,(operation_types)) else: stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS ORDER BY OPE_INVOKED ;" cur = db.query(stmnt) ret = {} for row in cur.fetchallmap(): operation = cls.restore_operation(row) custom_values = operation.get_values() ret[row["OPE_ID"]] = {"id":row["OPE_ID"], "parent":row["OPE_OPE_PARENT"], "invoked":str(row["OPE_INVOKED"]), "type":row["OPE_TYPE"], "status":row["OPE_STATUS"], "data":custom_values} return ret def get_values(self): """ trivial """ return self._values def get_value(self,key): """ trivial """ return self._values(key) def set_value(self,key,value): """ trivial """ self._values[key] = value def set_parent(self,parent_id): """ trivial """ self._parent = parent_id def get_parent(self): """ trivial """ return self._parent def set_db_id(self): """ Get a new Operation Id from the Database and assign it to this Operation if this Operation's id is null. Afterwards return the new Id """ if self._id is None: self._id = Database().get_seq_next('OPE_GEN') return self._id def set_id(self, nr): """ trivial """ self._id = nr def get_id(self): """ trivial """ return self._id def store(self): """ Stores this Operation to database. Also saves every user defined value in $_values as long as it is a valid type """ db = Database() self.set_db_id() stmnt = "UPDATE OR INSERT INTO OPERATIONS (OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE) \ VALUES (?,?,CURRENT_TIMESTAMP,?) MATCHING (OPE_ID);" db.query(stmnt,(self._id,self._parent,self.__class__.__name__),commit=True) stmnt = "UPDATE OR INSERT INTO OPERATIONDATA (OPD_OPE_ID, OPD_KEY, OPD_VALUE, OPD_TYPE) \ VALUES ( ?, ?, ?, ?) MATCHING(OPD_OPE_ID,OPD_KEY);" for key, value in self._values.items(): typ = str(type(value)).replace("<type '","",1).replace("'>","",1) if typ not in Operation.VALID_STORAGE_TYPES: continue db.query(stmnt,(self._id,key,value,typ),commit=True) def do_workload(self): """ This method must be overridden by inheriting classes. The code inside this method will be executed when the Operation is processed by Operation.processNext or Operation.processChild """ pass #MODULEINVOLVED class ModuleOperation(Operation): """ Abstracts Operations that have to do with modules """ def __init__(self): """ trivial """ Operation.__init__(self) def set_values(self,module): """ Sets this operations values from module metadata """ if type(module) == dict: self.set_value("name",module["name"]) self.set_value("hrname",module["hrname"]) self.set_value("version_major",module["version_major"]) self.set_value("version_minor",module["version_minor"]) self.set_value("revision",module["revision"]) if module.has_key("signature"): self.set_value("signature",module["signature"]) elif module.__class__.__name__ == "Module": pass #TODO IMPLEMENT / DISCUSS AFTER IMPLEMENTING MODULE-SUBSYSTEM def get_meta(self): """ trivial """ return self._values @classmethod def get_currently_processed_modules(cls): """ Returns an Array of ModuleOperation-Objects that are currently listedin the queue """ db = Database() stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_TYPE FROM OPERATIONS \ WHERE OPE_TYPE = 'ModuleInstallOperation' \ or OPE_TYPE = 'ModuleUninstallOperation' ;" cur = db.query(stmnt); ret = [] for row in cur.fetchallmap(): ret.append(Operation.restore_operation(row).get_meta()) return ret def optimize_queue(self): """ abtract """ pass #MODULEINVOLVED class ModuleInstallOperation(ModuleOperation): """ Manages the process to install a module to this server """ def __init__(self): """ trivial """ ModuleOperation.__init__(self) def do_workload(self): """ tell the module manager to install a specific module. """ Module.install_module(self.get_meta()) def optimize_queue(self): """ optimizes the queue. """ pass #TODO Implement #MODULEINVOLVED class ModuleUninstallOperation(ModuleOperation): """ Manages the process to uninstall a module to this server """ def __init__(self): """ trivial """ ModuleOperation.__init__(self) def do_workload(self): """ tell the module manager to install a specific module. """ module = Module.get_module_by_name(self._values["name"]) module_manager.uninstall_module(module) def optimize_queue(self): """ optimizes the queue. """ pass #TODO Implement #MODULEINVOLVED class ModuleUpdateOperation(ModuleOperation): """ Manages the process to uninstall a module to this server """ def __init__(self): """ trivial """ ModuleOperation.__init__(self) def do_workload(self): """ tell the module manager to install a specific module. """ module = Module.get_module_by_name(self._values["name"]) module_manager.update_module(module) def optimize_queue(self): """ optimizes the queue. """ pass #TODO Implement class FailOperation(Operation): """ For unittest purposes: An Operation that always fails """ def __init__(self): """ trivial """ Operation.__init__(self) def do_workload(self): """ simply fail """ raise Exception("Failoperation failed") class TestOperation(Operation): """ For unittest purposes: An Operation that always succeds """ def __init__(self): """ trivial """ Operation.__init__(self) def do_workload(self): """ simply succeed """ pass class OperationDaemon(Daemon): """ This is the deamon that runs to actually execute the scheduled operations """ def __init__(self, pidfile): """ Initialize the deamon """ Daemon.__init__(self,pidfile) def stop(self): configuration = Configuration() if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"): os.remove(configuration.get_entry("core.webpath")+"/scv_operating.lck") Daemon.stop(self) def run(self): """ Do work if there is work to do, otherwise check every two seconds for new work. """ while True: while Operation.process_next(): pass sleep(2)
skarphed/skarphed
core/lib/operation.py
Python
agpl-3.0
16,724
<?php /* This file is part of Incipio. Incipio is an enterprise resource planning for Junior Enterprise Copyright (C) 2012-2014 Florian Lefevre. Incipio is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Incipio 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Incipio as the file LICENSE. If not, see <http://www.gnu.org/licenses/>. */ namespace mgate\PersonneBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use JMS\SecurityExtraBundle\Annotation\Secure; use mgate\PersonneBundle\Entity\Poste; use mgate\PersonneBundle\Entity\Personne; use mgate\PersonneBundle\Form\PosteType; class PosteController extends Controller { /** * @Secure(roles="ROLE_SUIVEUR") */ public function ajouterAction() { $em = $this->getDoctrine()->getManager(); $poste = new Poste; $form = $this->createForm(new PosteType, $poste); if( $this->get('request')->getMethod() == 'POST' ) { $form->bind($this->get('request')); if( $form->isValid() ) { $em->persist($poste); $em->flush(); return $this->redirect( $this->generateUrl('mgatePersonne_poste_voir', array('id' => $poste->getId())) ); } } return $this->render('mgatePersonneBundle:Poste:ajouter.html.twig', array( 'form' => $form->createView(), )); } /** * Affiche la liste des pages et permet aux admin d'ajouter un poste * @Secure(roles="ROLE_MEMBRE") */ public function indexAction($page) { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('mgatePersonneBundle:Poste')->findAll(); // On récupère le service $security = $this->get('security.context'); // On récupère le token $token = $security->getToken(); // on récupère l'utilisateur $user = $token->getUser(); if($security->isGranted('ROLE_ADMIN')){ $poste = new Poste; $form = $this->createForm(new PosteType, $poste); return $this->render('mgatePersonneBundle:Poste:index.html.twig', array( 'postes' => $entities, 'form' => $form->createView() )); } return $this->render('mgatePersonneBundle:Poste:index.html.twig', array( 'postes' => $entities, )); } /** * @Secure(roles="ROLE_MEMBRE") */ public function voirAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('mgatePersonneBundle:Poste')->find($id); if (!$entity) { throw $this->createNotFoundException('Le poste demandé n\'existe pas !'); } //$deleteForm = $this->createDeleteForm($id); return $this->render('mgatePersonneBundle:Poste:voir.html.twig', array( 'poste' => $entity, /*'delete_form' => $deleteForm->createView(), */)); } /** * @Secure(roles="ROLE_SUIVEUR") */ public function modifierAction($id) { $em = $this->getDoctrine()->getManager(); if( ! $poste = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) ) throw $this->createNotFoundException('Le poste demandé n\'existe pas !'); // On passe l'$article récupéré au formulaire $form = $this->createForm(new PosteType, $poste); $deleteForm = $this->createDeleteForm($id); if( $this->get('request')->getMethod() == 'POST' ) { $form->bind($this->get('request')); if( $form->isValid() ) { $em->persist($poste); $em->flush(); return $this->redirect( $this->generateUrl('mgatePersonne_poste_voir', array('id' => $poste->getId())) ); } } return $this->render('mgatePersonneBundle:Poste:modifier.html.twig', array( 'form' => $form->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * @Secure(roles="ROLE_SUIVEUR") */ public function deleteAction($id) { $form = $this->createDeleteForm($id); $request = $this->getRequest(); $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); if( ! $entity = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) ) throw $this->createNotFoundException('Le poste demandé n\'existe pas !'); foreach($entity->getMembres() as $membre) $membre->setPoste(null); //$entity->setMembres(null); $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('mgatePersonne_poste_homepage')); } private function createDeleteForm($id) { return $this->createFormBuilder(array('id' => $id)) ->add('id', 'hidden') ->getForm() ; } }
Emagine-JE/Incipio
src/mgate/PersonneBundle/Controller/PosteController.php
PHP
agpl-3.0
5,768
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package state import ( "math/big" "github.com/ethereumproject/go-ethereum/common" ) type journalEntry interface { undo(*StateDB) } type journal []journalEntry type ( // Changes to the account trie. createObjectChange struct { account *common.Address } resetObjectChange struct { prev *StateObject } suicideChange struct { account *common.Address prev bool // whether account had already suicided prevbalance *big.Int } // Changes to individual accounts. balanceChange struct { account *common.Address prev *big.Int } nonceChange struct { account *common.Address prev uint64 } storageChange struct { account *common.Address key, prevalue common.Hash } codeChange struct { account *common.Address prevcode, prevhash []byte } // Changes to other state values. refundChange struct { prev *big.Int } addLogChange struct { txhash common.Hash } ) func (ch createObjectChange) undo(s *StateDB) { s.GetStateObject(*ch.account).deleted = true delete(s.stateObjects, *ch.account) delete(s.stateObjectsDirty, *ch.account) } func (ch resetObjectChange) undo(s *StateDB) { s.setStateObject(ch.prev) } func (ch suicideChange) undo(s *StateDB) { obj := s.GetStateObject(*ch.account) if obj != nil { obj.suicided = ch.prev obj.setBalance(ch.prevbalance) } } func (ch balanceChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setBalance(ch.prev) } func (ch nonceChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setNonce(ch.prev) } func (ch codeChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setCode(common.BytesToHash(ch.prevhash), ch.prevcode) } func (ch storageChange) undo(s *StateDB) { s.GetStateObject(*ch.account).setState(ch.key, ch.prevalue) } func (ch refundChange) undo(s *StateDB) { s.refund = ch.prev } func (ch addLogChange) undo(s *StateDB) { logs := s.logs[ch.txhash] if len(logs) == 1 { delete(s.logs, ch.txhash) } else { s.logs[ch.txhash] = logs[:len(logs)-1] } }
adrianbrink/tendereum
vendor/github.com/ethereumproject/go-ethereum/core/state/journal.go
GO
agpl-3.0
2,808
using NetEOC.Auth.Data; using NetEOC.Auth.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NetEOC.Auth.Services { public class OrganizationService { public OrganizationRepository OrganizationRepository { get; set; } public OrganizationMemberRepository OrganizationMemberRepository { get; set; } public OrganizationAdminRepository OrganizationAdminRepository { get; set; } public OrganizationService() { OrganizationRepository = new OrganizationRepository(); OrganizationAdminRepository = new OrganizationAdminRepository(); OrganizationMemberRepository = new OrganizationMemberRepository(); } public async Task<Organization> Create(Organization organization) { if (!ValidateOrganization(organization)) throw new ArgumentException("Invalid Organization!"); if(organization.Id != Guid.Empty) { Organization existing = await Update(organization); if (existing != null) return existing; } return await OrganizationRepository.Create(organization); } public async Task<Organization> GetById(Guid id) { return await OrganizationRepository.Get(id); } public async Task<Organization[]> GetByOwnerId(Guid ownerId) { return await OrganizationRepository.GetByOwnerId(ownerId); } public async Task<Organization> Update(Organization organization) { if (!ValidateOrganization(organization)) throw new ArgumentException("Invalid Organization!"); if (organization.Id == Guid.Empty) throw new ArgumentException("Organization has no id!"); //merge organization Organization existing = await GetById(organization.Id); if (existing == null) return null; if (!string.IsNullOrWhiteSpace(organization.Name)) existing.Name = organization.Name; if (!string.IsNullOrWhiteSpace(organization.Description)) existing.Description = organization.Description; if (organization.Data != null) { foreach (var kv in organization.Data) { if (existing.Data.ContainsKey(kv.Key)) { existing.Data[kv.Key] = kv.Value; } else { existing.Data.Add(kv.Key, kv.Value); } } } return await OrganizationRepository.Update(existing); } public async Task<bool> Delete(Guid organizationId) { return await OrganizationRepository.Delete(organizationId); } public async Task<Guid[]> GetOrganizationMembers(Guid organizationId) { return (await OrganizationMemberRepository.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray(); } public async Task<Guid[]> GetOrganizationAdmins(Guid organizationId) { return (await OrganizationAdminRepository.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray(); } public async Task<OrganizationMember> AddMemberToOrganization(Guid organizationId, Guid userId) { OrganizationMember[] memberships = await OrganizationMemberRepository.GetByUserId(userId); OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); if (membership == null) { membership = new OrganizationMember { OrganizationId = organizationId, UserId = userId }; membership = await OrganizationMemberRepository.Create(membership); } return membership; } public async Task<bool> RemoveMemberFromOrganization(Guid organizationId, Guid userId) { OrganizationMember[] memberships = await OrganizationMemberRepository.GetByUserId(userId); OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); bool success = false; if (membership != null) { success = await OrganizationMemberRepository.Delete(membership.Id); } return success; } public async Task<OrganizationAdmin> AddAdminToOrganization(Guid organizationId, Guid userId) { OrganizationAdmin[] memberships = await OrganizationAdminRepository.GetByUserId(userId); OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); if (membership == null) { membership = new OrganizationAdmin { OrganizationId = organizationId, UserId = userId }; membership = await OrganizationAdminRepository.Create(membership); } return membership; } public async Task<bool> RemoveAdminFromOrganization(Guid organizationId, Guid userId) { OrganizationAdmin[] memberships = await OrganizationAdminRepository.GetByUserId(userId); OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId); bool success = false; if (membership != null) { success = await OrganizationAdminRepository.Delete(membership.Id); } return success; } private bool ValidateOrganization(Organization organization) { if (organization.OwnerId == Guid.Empty) throw new ArgumentException("Organization must have an owner!"); if (string.IsNullOrWhiteSpace(organization.Name)) throw new ArgumentException("Organization must have a name!"); return true; } } }
neteoc/neteoc-server
Source/Services/NetEOC.Auth/Services/OrganizationService.cs
C#
agpl-3.0
6,031
<?php class m151218_144423_update_et_operationnote_biometry_view extends CDbMigration { public function up() { $this->execute('CREATE OR REPLACE VIEW et_ophtroperationnote_biometry AS SELECT eol.id, eol.eye_id, eol.last_modified_date, target_refraction_left, target_refraction_right, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_left, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_description_left, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) AS lens_acon_left, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_right, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_description_right, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) AS lens_acon_right, k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right, snr_left, snr_right, iol_power_left, iol_power_right, predicted_refraction_left, predicted_refraction_right, patient_id, k2_axis_left, k2_axis_right, delta_k_left, delta_k_right, delta_k_axis_left, delta_k_axis_right, acd_left, acd_right, (SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_left) as status_left, (SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_right) as status_right, comments, eoc.event_id FROM et_ophinbiometry_measurement eol JOIN et_ophinbiometry_calculation eoc ON eoc.event_id=eol.event_id JOIN et_ophinbiometry_selection eos ON eos.event_id=eol.event_id JOIN event ev ON ev.id=eol.event_id JOIN episode ep ON ep.id=ev.episode_id ORDER BY eol.last_modified_date;'); } public function down() { $this->execute('CREATE OR REPLACE VIEW et_ophtroperationnote_biometry AS SELECT eol.id, eol.eye_id, eol.last_modified_date, target_refraction_left, target_refraction_right, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_left, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_description_left, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) AS lens_acon_left, (SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_right, (SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_description_right, (SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) AS lens_acon_right, k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right, snr_left, snr_right, iol_power_left, iol_power_right, predicted_refraction_left, predicted_refraction_right, patient_id FROM et_ophinbiometry_measurement eol JOIN et_ophinbiometry_calculation eoc ON eoc.event_id=eol.event_id JOIN et_ophinbiometry_selection eos ON eos.event_id=eol.event_id JOIN event ev ON ev.id=eol.event_id JOIN episode ep ON ep.id=ev.episode_id ORDER BY eol.last_modified_date;'); } }
FiviumAustralia/OpenEyes
protected/modules/OphInBiometry/migrations/m151218_144423_update_et_operationnote_biometry_view.php
PHP
agpl-3.0
3,374
/* * dmroom.cpp * Staff functions related to rooms. * ____ _ * | _ \ ___ __ _| |_ __ ___ ___ * | |_) / _ \/ _` | | '_ ` _ \/ __| * | _ < __/ (_| | | | | | | \__ \ * |_| \_\___|\__,_|_|_| |_| |_|___/ * * Permission to use, modify and distribute is granted via the * GNU Affero General Public License v3 or later * * Copyright (C) 2007-2021 Jason Mitchell, Randi Mitchell * Contributions by Tim Callahan, Jonathan Hseu * Based on Mordor (C) Brooke Paul, Brett J. Vickers, John P. Freeman * */ #include <dirent.h> // for opendir, readdir, dirent #include <fmt/format.h> // for format #include <libxml/parser.h> // for xmlDocSetRootElement #include <unistd.h> // for unlink #include <boost/algorithm/string/replace.hpp> // for replace_all #include <boost/iterator/iterator_traits.hpp> // for iterator_value<>::type #include <cstdio> // for sprintf #include <cstdlib> // for atoi, exit #include <cstring> // for strcmp, strlen, strcpy #include <ctime> // for time, ctime, time_t #include <deque> // for _Deque_iterator #include <iomanip> // for operator<<, setw #include <iostream> // for operator<<, char_traits #include <list> // for operator==, list, _Lis... #include <map> // for operator==, map, map<>... #include <string> // for string, operator== #include <string_view> // for operator==, string_view #include <utility> // for pair #include "area.hpp" // for Area, MapMarker, AreaZone #include "async.hpp" // for Async, AsyncExternal #include "catRef.hpp" // for CatRef #include "catRefInfo.hpp" // for CatRefInfo #include "cmd.hpp" // for cmd #include "commands.hpp" // for getFullstrText, cmdNoAuth #include "config.hpp" // for Config, gConfig, Deity... #include "deityData.hpp" // for DeityData #include "dice.hpp" // for Dice #include "dm.hpp" // for dmAddMob, dmAddObj #include "effects.hpp" // for EffectInfo, Effects #include "factions.hpp" // for Faction #include "flags.hpp" // for R_TRAINING_ROOM, R_SHO... #include "free_crt.hpp" // for free_crt #include "global.hpp" // for CreatureClass, Creatur... #include "hooks.hpp" // for Hooks #include "lasttime.hpp" // for crlasttime #include <libxml/xmlstring.h> // for BAD_CAST #include "location.hpp" // for Location #include "monType.hpp" // for getHitdice, getName #include "money.hpp" // for Money, GOLD #include "mudObjects/areaRooms.hpp" // for AreaRoom #include "mudObjects/creatures.hpp" // for Creature #include "mudObjects/exits.hpp" // for Exit, getDir, getDirName #include "mudObjects/monsters.hpp" // for Monster #include "mudObjects/objects.hpp" // for Object #include "mudObjects/players.hpp" // for Player #include "mudObjects/rooms.hpp" // for BaseRoom, ExitList #include "mudObjects/uniqueRooms.hpp" // for UniqueRoom #include "os.hpp" // for merror #include "paths.hpp" // for checkDirExists, AreaRoom #include "proc.hpp" // for ChildType, ChildType::... #include "property.hpp" // for Property #include "proto.hpp" // for log_immort, low, needU... #include "raceData.hpp" // for RaceData #include "range.hpp" // for Range #include "server.hpp" // for Server, gServer #include "size.hpp" // for getSizeName, getSize #include "startlocs.hpp" // for StartLoc #include "stats.hpp" // for Stat #include "swap.hpp" // for SwapRoom #include "track.hpp" // for Track #include "traps.hpp" // for TRAP_ACID, TRAP_ALARM #include "utils.hpp" // for MAX, MIN #include "wanderInfo.hpp" // for WanderInfo #include "xml.hpp" // for loadRoom, loadMonster //********************************************************************* // checkTeleportRange //********************************************************************* void checkTeleportRange(const Player* player, const CatRef& cr) { // No warning for the test range if(cr.isArea("test")) return; const CatRefInfo* cri = gConfig->getCatRefInfo(cr.area); if(!cri) { player->printColor("^yNo CatRefInfo zone found for this room's area. Contact a dungeonmaster to fix this.\n"); return; } if(cr.id > cri->getTeleportWeight()) { player->printColor("^yThis room is outside the CatRefInfo zone's teleport range.\n"); return; } } //********************************************************************* // isCardinal //********************************************************************* bool isCardinal(std::string_view xname) { return( xname == "north" || xname == "east" || xname == "south" || xname == "west" || xname == "northeast" || xname == "northwest" || xname == "southeast" || xname == "southwest" ); } //********************************************************************* // wrapText //********************************************************************* std::string wrapText(std::string_view text, int wrap) { if(text.empty()) return(""); std::string wrapped = ""; int len = text.length(), i=0, sp=0, spLast=0, spLen=0; char ch, chLast; // find our starting position while(text.at(i) == ' ' || text.at(i) == '\n' || text.at(i) == '\r') i++; for(; i < len; i++) { ch = text.at(i); // convert linebreaks to spaces if(ch == '\r') ch = ' '; if(ch == '\n') ch = ' '; // skiping 2x spacing (or greater) if(ch == ' ' && chLast == ' ') { do { i++; } while(i+1 < len && (text.at(i+1) == ' ' || text.at(i+1) == '\n' || text.at(i+1) == '\r')); if(i < len) ch = text.at(i); } // don't add trailing spaces if(ch != ' ' || i+1 < len) { // If there is color in the room description, the color characters // shouldn't count toward string length. if(ch == '^') spLen += 2; // wrap if(ch == ' ') { // We went over! spLast points to the last non-overboard space. if(wrap <= (sp - spLen)) { wrapped.replace(spLast, 1, "\n"); spLen = spLast; } spLast = sp; } wrapped += ch; sp++; chLast = ch; } } return(wrapped); } //********************************************************************* // expand_exit_name //********************************************************************* std::string expand_exit_name(const std::string &name) { if(name == "n") return("north"); if(name == "s") return("south"); if(name == "e") return("east"); if(name == "w") return("west"); if(name == "sw") return("southwest"); if(name == "nw") return("northwest"); if(name == "se") return("southeast"); if(name == "ne") return("northeast"); if(name == "d") return("door"); if(name == "o") return("out"); if(name == "p") return("passage"); if(name == "t") return("trap door"); if(name == "a") return("arch"); if(name == "g") return("gate"); if(name == "st") return("stairs"); return(name); } //********************************************************************* // opposite_exit_name //********************************************************************* std::string opposite_exit_name(const std::string &name) { if(name == "south") return("north"); if(name == "north") return("south"); if(name == "west") return("east"); if(name == "east") return("west"); if(name == "northeast") return("southwest"); if(name == "southeast") return("northwest"); if(name == "northwest") return("southeast"); if(name == "southwest") return("northeast"); if(name == "up") return("down"); if(name == "down") return("up"); return(name); } //********************************************************************* // dmPurge //********************************************************************* // This function allows staff to purge a room of all its objects and // monsters. int dmPurge(Player* player, cmd* cmnd) { BaseRoom* room = player->getRoomParent(); if(!player->canBuildMonsters() && !player->canBuildObjects()) return(cmdNoAuth(player)); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: this room is out of your range; you cannot *purge here.\n"); return(0); } room->purge(false); player->print("Purged.\n"); if(!player->isDm()) log_immort(false,player, "%s purged room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); return(0); } //********************************************************************* // dmEcho //********************************************************************* // This function allows a staff specified by the socket descriptor in // the first parameter to echo the rest of their command line to all // the other people in the room. int dmEcho(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: room number not in any of your allotted ranges.\n"); return(0); } std::string text = getFullstrText(cmnd->fullstr, 1); if(text.empty() || Pueblo::is(text)) { player->print("Echo what?\n"); return(0); } if(!player->isCt()) broadcast(isStaff, "^G*** %s (%s) echoed: %s", player->getCName(), player->getRoomParent()->fullName().c_str(), text.c_str()); broadcast(nullptr, player->getRoomParent(), "%s", text.c_str()); return(0); } //********************************************************************* // dmReloadRoom //********************************************************************* // This function allows a staff to reload a room from disk. int dmReloadRoom(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: this room is out of your range; you cannot reload this room.\n"); return(0); } if(gServer->reloadRoom(player->getRoomParent())) player->print("Ok.\n"); else player->print("Reload failed.\n"); return(0); } //********************************************************************* // resetPerms //********************************************************************* // This function allows a staff to reset perm timeouts in the room int dmResetPerms(Player* player, cmd* cmnd) { std::map<int, crlasttime>::iterator it; crlasttime* crtm=nullptr; std::map<int, long> tempMonsters; std::map<int, long> tempObjects; UniqueRoom *room = player->getUniqueRoomParent(); //long temp_obj[10], temp_mon[10]; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: this room is out of your range; you cannot reload this room.\n"); return(0); } for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) { crtm = &(*it).second; tempMonsters[(*it).first] = crtm->interval; crtm->ltime = time(nullptr); crtm->interval = 0; } for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) { crtm = &(*it).second; tempObjects[(*it).first] = crtm->interval; crtm->ltime = time(nullptr); crtm->interval = 0; } player->print("Permanent object and creature timeouts reset.\n"); room->addPermCrt(); for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) { crtm = &(*it).second; crtm->interval = tempMonsters[(*it).first]; crtm->ltime = time(nullptr); } for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) { crtm = &(*it).second; crtm->interval = tempObjects[(*it).first]; crtm->ltime = time(nullptr); } log_immort(true, player, "%s reset perm timeouts in room %s\n", player->getCName(), player->getRoomParent()->fullName().c_str()); if(gServer->resaveRoom(room->info) < 0) player->print("Room fail saved.\n"); else player->print("Room saved.\n"); return(0); } //********************************************************************* // stat_rom_exits //********************************************************************* // Display information on room given to staff. void stat_rom_exits(Creature* player, BaseRoom* room) { char str[1024], temp[25], tempstr[32]; int i=0, flagcount=0; UniqueRoom* uRoom = room->getAsUniqueRoom(); if(room->exits.empty()) return; player->print("Exits:\n"); for(Exit* exit : room->exits) { if(!exit->getLevel()) player->print(" %s: ", exit->getCName()); else player->print(" %s(L%d): ", exit->getCName(), exit->getLevel()); if(!exit->target.mapmarker.getArea()) player->printColor("%s ", exit->target.room.str(uRoom ? uRoom->info.area : "", 'y').c_str()); else player->print(" A:%d X:%d Y:%d Z:%d ", exit->target.mapmarker.getArea(), exit->target.mapmarker.getX(), exit->target.mapmarker.getY(), exit->target.mapmarker.getZ()); *str = 0; strcpy(str, "Flags: "); for(i=0; i<MAX_EXIT_FLAGS; i++) { if(exit->flagIsSet(i)) { sprintf(tempstr, "%s(%d), ", gConfig->getXFlag(i).c_str(), i+1); strcat(str, tempstr); flagcount++; } } if(flagcount) { str[strlen(str) - 2] = '.'; str[strlen(str) - 1] = 0; } if(flagcount) player->print("%s", str); if(exit->flagIsSet(X_LOCKABLE)) { player->print(" Key#: %d ", exit->getKey()); if(!exit->getKeyArea().empty()) player->printColor(" Area: ^y%s^x ", exit->getKeyArea().c_str()); } if(exit->flagIsSet(X_TOLL_TO_PASS)) player->print(" Toll: %d ", exit->getToll()); player->print("\n"); if(!exit->getDescription().empty()) player->print(" Description: \"%s\"\n", exit->getDescription().c_str()); if( (exit->flagIsSet(X_CAN_LOOK) || exit->flagIsSet(X_LOOK_ONLY)) && exit->flagIsSet(X_NO_SCOUT) ) player->printColor("^rExit is flagged as no-scout, but it flagged as lookable.\n"); if(exit->flagIsSet(X_PLEDGE_ONLY)) { for(i=1; i<15; i++) if(exit->flagIsSet(i+40)) { sprintf(temp, "Clan: %d, ",i); strcat(str, temp); } player->print(" Clan: %s\n", temp); } if(exit->flagIsSet(X_PORTAL)) { player->printColor(" Owner: ^c%s^x Uses: ^c%d^x\n", exit->getPassPhrase().c_str(), exit->getKey()); } else if(!exit->getPassPhrase().empty()) { player->print(" Passphrase: \"%s\"\n", exit->getPassPhrase().c_str()); if(exit->getPassLanguage()) player->print(" Passlang: %s\n", get_language_adj(exit->getPassLanguage())); } if(!exit->getEnter().empty()) player->print(" OnEnter: \"%s\"\n", exit->getEnter().c_str()); if(!exit->getOpen().empty()) player->print(" OnOpen: \"%s\"\n", exit->getOpen().c_str()); if(exit->getSize() || exit->getDirection()) { if(exit->getSize()) player->print(" Size: %s", getSizeName(exit->getSize()).c_str()); if(exit->getDirection()) { player->print(" Direction: %s", getDirName(exit->getDirection()).c_str()); if(getDir(exit->getName()) != NoDirection) player->printColor("\n^rThis exit has a direction set, but the exit is a cardinal exit."); } player->print("\n"); } if(!exit->effects.effectList.empty()) player->printColor(" Effects:\n%s", exit->effects.getEffectsString(player).c_str()); player->printColor("%s", exit->hooks.display().c_str()); } } //********************************************************************* // trainingFlagSet //********************************************************************* bool trainingFlagSet(const BaseRoom* room, const TileInfo *tile, const AreaZone *zone, int flag) { return( (room && room->flagIsSet(flag)) || (tile && tile->flagIsSet(flag)) || (zone && zone->flagIsSet(flag)) ); } //********************************************************************* // whatTraining //********************************************************************* // determines what class can train here int whatTraining(const BaseRoom* room, const TileInfo *tile, const AreaZone *zone, int extra) { int i = 0; if(R_TRAINING_ROOM - 1 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM - 1)) i += 16; if(R_TRAINING_ROOM == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM)) i += 8; if(R_TRAINING_ROOM + 1 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 1)) i += 4; if(R_TRAINING_ROOM + 2 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 2)) i += 2; if(R_TRAINING_ROOM + 3 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 3)) i += 1; return(i > static_cast<int>(CreatureClass::CLASS_COUNT) - 1 ? 0 : i); } bool BaseRoom::hasTraining() const { return(whatTraining() != CreatureClass::NONE); } CreatureClass BaseRoom::whatTraining(int extra) const { return(static_cast<CreatureClass>(::whatTraining(this, (const TileInfo*)nullptr, (const AreaZone*)nullptr, extra))); } //********************************************************************* // showRoomFlags //********************************************************************* void showRoomFlags(const Player* player, const BaseRoom* room, const TileInfo *tile, const AreaZone *zone) { bool flags=false; int i=0; std::ostringstream oStr; oStr << "^@Flags set: "; for(; i<MAX_ROOM_FLAGS; i++) { if(i >=2 && i <= 6) // skips training flags continue; if( (room && room->flagIsSet(i)) || (tile && tile->flagIsSet(i)) || (zone && zone->flagIsSet(i)) ) { if(flags) oStr << ", "; flags = true; oStr << gConfig->getRFlag(i) << "(" << (int)(i+1) << ")"; } } if(!flags) oStr << "None"; oStr << ".^x\n"; i = whatTraining(room, tile, zone, 0); if(i) oStr << "^@Training: " << get_class_string(i) << "^x\n"; player->printColor("%s", oStr.str().c_str()); // inform user of redundant flags if(room && room->getAsConstUniqueRoom()) { bool hasTraining = room->hasTraining(); bool limboOrCoven = room->flagIsSet(R_LIMBO) || room->flagIsSet(R_VAMPIRE_COVEN); if(room->flagIsSet(R_NO_TELEPORT)) { if( limboOrCoven || room->flagIsSet(R_JAIL) || room->flagIsSet(R_ETHEREAL_PLANE) || hasTraining ) player->printColor("^rThis room does not need flag 13-No Teleport set.\n"); } if(room->flagIsSet(R_NO_SUMMON_OUT)) { if( room->flagIsSet(R_IS_STORAGE_ROOM) || room->flagIsSet(R_LIMBO) ) player->printColor("^rThis room does not need flag 29-No Summon Out set.\n"); } if(room->flagIsSet(R_NO_LOGIN)) { if( room->flagIsSet(R_LOG_INTO_TRAP_ROOM) || hasTraining ) player->printColor("^rThis room does not need flag 34-No Log set.\n"); } if(room->flagIsSet(R_NO_CLAIR_ROOM)) { if(limboOrCoven) player->printColor("^rThis room does not need flag 43-No Clair set.\n"); } if(room->flagIsSet(R_NO_TRACK_TO)) { if( limboOrCoven || room->flagIsSet(R_IS_STORAGE_ROOM) || room->flagIsSet(R_NO_TELEPORT) || hasTraining ) player->printColor("^rThis room does not need flag 52-No Track To set.\n"); } if(room->flagIsSet(R_NO_SUMMON_TO)) { if( limboOrCoven || room->flagIsSet(R_NO_TELEPORT) || room->flagIsSet(R_ONE_PERSON_ONLY) || hasTraining ) player->printColor("^rThis room does not need flag 54-No Summon To set.\n"); } if(room->flagIsSet(R_NO_TRACK_OUT)) { if( room->flagIsSet(R_LIMBO) || room->flagIsSet(R_ETHEREAL_PLANE) ) player->printColor("^rThis room does not need flag 54-No Summon To set.\n"); } if(room->flagIsSet(R_OUTLAW_SAFE)) { if( limboOrCoven || hasTraining ) player->printColor("^rThis room does not need flag 57-Outlaw Safe set.\n"); } if(room->flagIsSet(R_LOG_INTO_TRAP_ROOM)) { if(hasTraining) player->printColor("^rThis room does not need flag 63-Log To Trap Exit set.\n"); } if(room->flagIsSet(R_LIMBO)) { if(room->flagIsSet(R_POST_OFFICE)) player->printColor("^rThis room does not need flag 11-Post Office set.\n"); if(room->flagIsSet(R_FAST_HEAL)) player->printColor("^rThis room does not need flag 14-Fast Heal set.\n"); if(room->flagIsSet(R_NO_POTION)) player->printColor("^rThis room does not need flag 32-No Potion set.\n"); if(room->flagIsSet(R_NO_CAST_TELEPORT)) player->printColor("^rThis room does not need flag 38-No Cast Teleport set.\n"); if(room->flagIsSet(R_NO_FLEE)) player->printColor("^rThis room does not need flag 44-No Flee set.\n"); if(room->flagIsSet(R_BANK)) player->printColor("^rThis room does not need flag 58-Bank set.\n"); if(room->flagIsSet(R_MAGIC_MONEY_MACHINE)) player->printColor("^rThis room does not need flag 59-Magic Money Machine set.\n"); } } } //********************************************************************* // stat_rom //********************************************************************* int stat_rom(Player* player, AreaRoom* room) { std::list<AreaZone*>::iterator it; AreaZone* zone=nullptr; TileInfo* tile=nullptr; if(!player->checkBuilder(nullptr)) return(0); if(player->getClass() == CreatureClass::CARETAKER) log_immort(false,player, "%s statted room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->print("Room: %s %s\n\n", room->area->name.c_str(), room->fullName().c_str()); tile = room->area->getTile(room->area->getTerrain(nullptr, &room->mapmarker, 0, 0, 0, true), false); for(it = room->area->zones.begin() ; it != room->area->zones.end() ; it++) { zone = (*it); if(zone->inside(room->area, &room->mapmarker)) { player->printColor("^yZone:^x %s\n", zone->name.c_str()); if(zone->wander.getTraffic()) { zone->wander.show(player); } else { player->print(" No monsters come in this zone.\n"); } player->print("\n"); } } if(room->getSize()) player->printColor("Size: ^y%s\n", getSizeName(room->getSize()).c_str()); if(tile->wander.getTraffic()) tile->wander.show(player); player->print("Terrain: %c\n", tile->getDisplay()); if(room->isWater()) player->printColor("Water: ^gyes\n"); if(room->isRoad()) player->printColor("Road: ^gyes\n"); player->printColor("Generic Room: %s\n", room->canSave() ? "^rNo" : "^gYes"); if(room->unique.id) { player->printColor("Links to unique room ^y%s^x.\n", room->unique.str().c_str()); player->printColor("needsCompass: %s^x decCompass: %s", room->getNeedsCompass() ? "^gYes" : "^rNo", room->getDecCompass() ? "^gYes" : "^rNo"); } player->print("\n"); showRoomFlags(player, room, nullptr, nullptr); if(!room->effects.effectList.empty()) player->printColor("Effects:\n%s", room->effects.getEffectsString(player).c_str()); player->printColor("%s", room->hooks.display().c_str()); stat_rom_exits(player, room); return(0); } //********************************************************************* // validateShop //********************************************************************* void validateShop(const Player* player, const UniqueRoom* shop, const UniqueRoom* storage) { // basic checks if(!shop) { player->printColor("^rThe shop associated with this storage room does not exist.\n"); return; } if(!storage) { player->printColor("^rThe storage room associated with this shop does not exist.\n"); return; } if(shop->info == storage->info) { player->printColor("^rThe shop and the storage room cannot be the same room. Set the shop's trap exit appropriately.\n"); return; } CatRef cr = shopStorageRoom(shop); if(shop->info == cr) { player->printColor("^rThe shop and the storage room cannot be the same room. Set the shop's trap exit appropriately.\n"); return; } std::string name = "Storage: "; name += shop->getName(); if(cr != storage->info) player->printColor("^rThe shop's storage room of %s does not match the storage room %s.\n", cr.str().c_str(), storage->info.str().c_str()); if(storage->getTrapExit() != shop->info) player->printColor("^yThe storage room's trap exit of %s does not match the shop room %s.\n", storage->info.str().c_str(), shop->info.str().c_str()); if(!shop->flagIsSet(R_SHOP)) player->printColor("^rThe shop's flag 1-Shoppe is not set.\n"); if(!storage->flagIsSet(R_SHOP_STORAGE)) player->printColor("^rThe storage room's flag 97-Shop Storage is not set.\n"); // what DOESN'T the storage room need? if(storage->flagIsSet(R_NO_LOGIN)) player->printColor("^rThe storage room does not need flag 34-No Log set.\n"); if(storage->flagIsSet(R_LOG_INTO_TRAP_ROOM)) player->printColor("^rThe storage room does not need flag 63-Log To Trap Exit set.\n"); if(storage->flagIsSet(R_NO_TELEPORT)) player->printColor("^rThe storage room does not need flag 13-No Teleport set.\n"); if(storage->flagIsSet(R_NO_SUMMON_TO)) player->printColor("^rThe storage room does not need flag 54-No Summon To set.\n"); if(storage->flagIsSet(R_NO_TRACK_TO)) player->printColor("^rThe storage room does not need flag 52-No Track To set.\n"); if(storage->flagIsSet(R_NO_CLAIR_ROOM)) player->printColor("^rThe storage room does not need flag 43-No Clair set.\n"); if(storage->exits.empty()) { player->printColor("^yThe storage room does not have an out exit pointing to the shop.\n"); } else { const Exit* exit = storage->exits.front(); if( exit->target.room != shop->info || exit->getName() != "out") player->printColor("^yThe storage room does not have an out exit pointing to the shop.\n"); else if(storage->exits.size() > 1) player->printColor("^yThe storage room has more than one exit - it only needs one out exit pointing to the shop.\n"); } } //********************************************************************* // stat_rom //********************************************************************* int stat_rom(Player* player, UniqueRoom* room) { std::map<int, crlasttime>::iterator it; crlasttime* crtm=nullptr; CatRef cr; Monster* monster=nullptr; Object* object=nullptr; UniqueRoom* shop=nullptr; time_t t = time(nullptr); if(!player->checkBuilder(room)) return(0); if(player->getClass() == CreatureClass::CARETAKER) log_immort(false,player, "%s statted room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->printColor("Room: %s", room->info.str("", 'y').c_str()); if(gConfig->inSwapQueue(room->info, SwapRoom, true)) player->printColor(" ^eThis room is being swapped."); player->print("\nTimes People have entered this room: %d\n", room->getBeenHere()); player->print("Name: %s\n", room->getCName()); Property *p = gConfig->getProperty(room->info); if(p) { player->printColor("Property Belongs To: ^y%s^x\nProperty Type: ^y%s\n", p->getOwner().c_str(), p->getTypeStr().c_str()); } if(player->isCt()) { if(room->last_mod[0]) player->printColor("^cLast modified by: %s on %s\n", room->last_mod, stripLineFeeds(room->lastModTime)); if(room->lastPly[0]) player->printColor("^cLast player here: %s on %s\n", room->lastPly, stripLineFeeds(room->lastPlyTime)); } else player->print("\n"); if(room->getSize()) player->printColor("Size: ^y%s\n", getSizeName(room->getSize()).c_str()); if(room->getRoomExperience()) player->print("Experience for entering this room: %d\n", room->getRoomExperience()); if(!room->getFaction().empty()) player->printColor("Faction: ^g%s^x\n", room->getFaction().c_str()); if(!room->getFishingStr().empty()) player->printColor("Fishing: ^g%s^x\n", room->getFishingStr().c_str()); if(room->getMaxMobs() > 0) player->print("Max mob allowance: %d\n", room->getMaxMobs()); room->wander.show(player, room->info.area); player->print("\n"); player->print("Perm Objects:\n"); for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) { crtm = &(*it).second; loadObject((*it).second.cr, &object); player->printColor("^y%2d) ^x%14s ^y::^x %-30s ^yInterval:^x %-5d ^yTime Until Spawn:^x %-5d", (*it).first+1, crtm->cr.str("", 'y').c_str(), object ? object->getCName() : "", crtm->interval, MAX<long>(0, crtm->ltime + crtm->interval-t)); if(room->flagIsSet(R_SHOP_STORAGE) && object) player->printColor(" ^yCost:^x %s", object->value.str().c_str()); player->print("\n"); // warning about deeds in improper areas if(object && object->deed.low.id && !object->deed.isArea(room->info.area)) player->printColor(" ^YCaution:^x this object's deed area does not match the room's area.\n"); if(object) { delete object; object = nullptr; } } player->print("\n"); player->print("Perm Monsters:\n"); for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) { crtm = &(*it).second; loadMonster((*it).second.cr, &monster); player->printColor("^m%2d) ^x%14s ^m::^x %-30s ^mInterval:^x %d ^yTime until Spawn:^x %-5d\n", (*it).first+1, crtm->cr.str("", 'm').c_str(), monster ? monster->getCName() : "", crtm->interval, MAX<long>(0, crtm->ltime + crtm->interval-t)); if(monster) { free_crt(monster); monster = nullptr; } } player->print("\n"); if(!room->track.getDirection().empty() && room->flagIsSet(R_PERMENANT_TRACKS)) player->print("Perm Tracks: %s.\n", room->track.getDirection().c_str()); if(room->getLowLevel() || room->getHighLevel()) { player->print("Level Boundary: "); if(room->getLowLevel()) player->print("%d+ level ", room->getLowLevel()); if(room->getHighLevel()) player->print("%d- level ", room->getHighLevel()); player->print("\n"); } if( room->flagIsSet(R_LOG_INTO_TRAP_ROOM) || room->flagIsSet(R_SHOP_STORAGE) || room->hasTraining() ) { if(room->getTrapExit().id) player->print("Players will relog into room %s from here.\n", room->getTrapExit().str(room->info.area).c_str()); else player->printColor("^rTrap exit needs to be set to %s room number.\n", room->flagIsSet(R_SHOP_STORAGE) ? "shop" : "relog"); } if( room->getSize() == NO_SIZE && ( room->flagIsSet(R_INDOORS) || room->flagIsSet(R_UNDERGROUND) ) ) player->printColor("^yThis room does not have a size set.\n"); checkTeleportRange(player, room->info); // isShopValid if(room->flagIsSet(R_SHOP)) { cr = shopStorageRoom(room); player->print("Shop storage room: %s (%s)\n", cr.str().c_str(), cr.id == room->info.id+1 && cr.isArea(room->info.area) ? "default" : "trapexit"); if(room->getFaction().empty() && room->info.area != "shop") player->printColor("^yThis shop does not have a faction set.\n"); loadRoom(cr, &shop); validateShop(player, room, shop); } else if(room->flagIsSet(R_PAWN_SHOP)) { if(room->getFaction().empty()) player->printColor("^yThis pawn shop does not have a faction set.\n"); } if(room->flagIsSet(R_SHOP_STORAGE)) { loadRoom(room->getTrapExit(), &shop); validateShop(player, shop, room); } if(room->getTrap()) { if(room->getTrapWeight()) player->print("Trap weight: %d/%d lbs\n", room->getWeight(), room->getTrapWeight()); player->print("Trap type: "); switch(room->getTrap()) { case TRAP_PIT: player->print("Pit Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_DART: player->print("Poison Dart Trap\n"); break; case TRAP_BLOCK: player->print("Falling Block Trap\n"); break; case TRAP_MPDAM: player->print("MP Damage Trap\n"); break; case TRAP_RMSPL: player->print("Negate Spell Trap\n"); break; case TRAP_NAKED: player->print("Naked Trap\n"); break; case TRAP_TPORT: player->print("Teleport Trap\n"); break; case TRAP_ARROW: player->print("Arrow Trap\n"); break; case TRAP_SPIKED_PIT: player->print("Spiked Pit Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_WORD: player->print("Word of Recall Trap\n"); break; case TRAP_FIRE: player->print("Fire Trap\n"); break; case TRAP_FROST: player->print("Frost Trap\n"); break; case TRAP_ELEC: player->print("Electricity Trap\n"); break; case TRAP_ACID: player->print("Acid Trap\n"); break; case TRAP_ROCKS: player->print("Rockslide Trap\n"); break; case TRAP_ICE: player->print("Icicle Trap\n"); break; case TRAP_SPEAR: player->print("Spear Trap\n"); break; case TRAP_CROSSBOW: player->print("Crossbow Trap\n"); break; case TRAP_GASP: player->print("Poison Gas Trap\n"); break; case TRAP_GASB: player->print("Blinding Gas Trap\n"); break; case TRAP_GASS: player->print("Stun Gas Trap\n"); break; case TRAP_MUD: player->print("Mud Trap\n"); break; case TRAP_DISP: player->print("Room Displacement Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_FALL: player->print("Deadly Fall Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_CHUTE: player->print("Chute Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_ALARM: player->print("Alarm Trap (guard rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_BONEAV: player->print("Bone Avalanche Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str()); break; case TRAP_PIERCER: player->print("Piercer trap (%d piercers)\n", room->getTrapStrength()); break; case TRAP_ETHEREAL_TRAVEL: player->print("Ethereal travel trap.\n"); break; case TRAP_WEB: player->print("Sticky spider web trap.\n"); break; default: player->print("Invalid trap #\n"); break; } } if(room->flagIsSet(R_CAN_SHOPLIFT)) player->print("Store guardroom: rm %s\n", cr.str(room->info.area).c_str()); showRoomFlags(player, room, nullptr, nullptr); if(!room->effects.effectList.empty()) player->printColor("Effects:\n%s", room->effects.getEffectsString(player).c_str()); player->printColor("%s", room->hooks.display().c_str()); stat_rom_exits(player, room); return(0); } //********************************************************************* // dmAddRoom //********************************************************************* // This function allows staff to add a new, empty room to the current // database of rooms. int dmAddRoom(Player* player, cmd* cmnd) { UniqueRoom *newRoom=nullptr; char file[80]; int i=1; if(!strcmp(cmnd->str[1], "c") && (cmnd->num > 1)) { dmAddMob(player, cmnd); return(0); } if(!strcmp(cmnd->str[1], "o") && (cmnd->num > 1)) { dmAddObj(player, cmnd); return(0); } CatRef cr; bool extra = !strcmp(cmnd->str[1], "r"); getCatRef(getFullstrText(cmnd->fullstr, extra ? 2 : 1), &cr, player); if(cr.id < 1) { player->print("Index error: please specify room number.\n"); return(0); } if(!player->checkBuilder(cr, false)) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } if(gConfig->moveRoomRestrictedArea(cr.area)) { player->print("Error: ""%s"" is a restricted range. You cannot create unique rooms in that area.\n"); return(0); } Path::checkDirExists(cr.area, roomPath); if(!strcmp(cmnd->str[extra ? 3 : 2], "loop")) i = MAX(1, MIN(100, (int)cmnd->val[extra ? 3 : 2])); for(; i; i--) { if(!player->checkBuilder(cr, false)) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } sprintf(file, "%s", roomPath(cr)); if(file_exists(file)) { player->print("Room already exists.\n"); return(0); } newRoom = new UniqueRoom; if(!newRoom) merror("dmAddRoom", FATAL); newRoom->info = cr; newRoom->setFlag(R_CONSTRUCTION); newRoom->setName("New Room"); if(newRoom->saveToFile(0) < 0) { player->print("Write failed.\n"); return(0); } delete newRoom; log_immort(true, player, "%s created room %s.\n", player->getCName(), cr.str().c_str()); player->print("Room %s created.\n", cr.str().c_str()); checkTeleportRange(player, cr); cr.id++; } return(0); } //********************************************************************* // dmSetRoom //********************************************************************* // This function allows staff to set a characteristic of a room. int dmSetRoom(Player* player, cmd* cmnd) { BaseRoom *room = player->getRoomParent(); int a=0, num=0; CatRef cr; if(cmnd->num < 3) { player->print("Syntax: *set r [option] [<value>]\n"); return(0); } if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } switch(low(cmnd->str[2][0])) { case 'b': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(low(cmnd->str[2][1]) == 'l') { player->getUniqueRoomParent()->setLowLevel(cmnd->val[2]); player->print("Low level boundary %d\n", player->getUniqueRoomParent()->getLowLevel()); } else if(low(cmnd->str[2][1]) == 'h') { player->getUniqueRoomParent()->setHighLevel(cmnd->val[2]); player->print("Upper level boundary %d\n", player->getUniqueRoomParent()->getHighLevel()); } break; case 'd': if(!player->inAreaRoom()) { player->print("Error: You need to be in an area room to do that.\n"); return(0); } if(!player->getAreaRoomParent()->unique.id) { player->print("Error: The area room must have the unique field set [*set r unique #].\n"); return(0); } player->getAreaRoomParent()->setDecCompass(!player->getAreaRoomParent()->getDecCompass()); player->printColor("DecCompass toggled, set to %s^x.\n", player->getAreaRoomParent()->getDecCompass() ? "^gYes" : "^rNo"); log_immort(true, player, "%s set decCompass to %s in room %s.\n", player->getCName(), player->getAreaRoomParent()->getDecCompass() ? "true" : "false", room->fullName().c_str()); break; case 'e': if(cmnd->str[2][1] == 'f') { if(cmnd->num < 4) { player->print("Set what effect to what?\n"); return(0); } long duration = -1; int strength = 1; std::string txt = getFullstrText(cmnd->fullstr, 4); if(!txt.empty()) duration = atoi(txt.c_str()); txt = getFullstrText(cmnd->fullstr, 5); if(!txt.empty()) strength = atoi(txt.c_str()); if(duration > EFFECT_MAX_DURATION || duration < -1) { player->print("Duration must be between -1 and %d.\n", EFFECT_MAX_DURATION); return(0); } if(strength < 0 || strength > EFFECT_MAX_STRENGTH) { player->print("Strength must be between 0 and %d.\n", EFFECT_MAX_STRENGTH); return(0); } std::string effectStr = cmnd->str[3]; EffectInfo* toSet = nullptr; if((toSet = room->getExactEffect(effectStr))) { // We have an existing effect we're modifying if(duration == 0) { // Duration is 0, so remove it room->removeEffect(toSet, true); player->print("Effect '%s' (room) removed.\n", effectStr.c_str()); } else { // Otherwise modify as appropriate toSet->setDuration(duration); if(strength != -1) toSet->setStrength(strength); player->print("Effect '%s' (room) set to duration %d and strength %d.\n", effectStr.c_str(), toSet->getDuration(), toSet->getStrength()); } break; } else { // No existing effect, add a new one if(strength == -1) strength = 1; if(room->addEffect(effectStr, duration, strength, nullptr, true) != nullptr){ player->print("Effect '%s' (room) added with duration %d and strength %d.\n", effectStr.c_str(), duration, strength); } else { player->print("Unable to add effect '%s' (room)\n", effectStr.c_str()); } break; } } else if(cmnd->str[2][1] == 'x') { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->setRoomExperience(cmnd->val[2]); player->print("Room experience set to %d.\n", player->getUniqueRoomParent()->getRoomExperience()); log_immort(true, player, "%s set roomExp to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getRoomExperience(), room->fullName().c_str()); } else { player->print("Invalid option.\n"); return(0); } break; case 'f': if(low(cmnd->str[2][1]) == 'i') { if(!strcmp(cmnd->str[3], "")) { player->getUniqueRoomParent()->setFishing(""); player->print("Fishing list cleared.\n"); log_immort(true, player, "%s cleared fishing list in room %s.\n", player->getCName(), room->fullName().c_str()); } else { const Fishing* list = gConfig->getFishing(cmnd->str[3]); if(!list) { player->print("Fishing list \"%s\" does not exist!\n", cmnd->str[3]); return(0); } player->getUniqueRoomParent()->setFishing(cmnd->str[3]); player->print("Fishing list set to %s.\n", player->getUniqueRoomParent()->getFishingStr().c_str()); log_immort(true, player, "%s set fishing list to %s in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getFishingStr().c_str(), room->fullName().c_str()); } } else if(low(cmnd->str[2][1]) == 'a') { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(cmnd->num < 3) { player->print("Set faction to what?\n"); return(0); } else if(cmnd->num == 3) { player->getUniqueRoomParent()->setFaction(""); player->print("Faction cleared.\n"); log_immort(true, player, "%s cleared faction in room %s.\n", player->getCName(), room->fullName().c_str()); return(0); } Property* p = gConfig->getProperty(player->getUniqueRoomParent()->info); if(p && p->getType() == PROP_SHOP) { player->print("You can't set room faction on player shops!\n"); return(0); } const Faction* faction = gConfig->getFaction(cmnd->str[3]); if(!faction) { player->print("'%s' is an invalid faction.\n", cmnd->str[3]); return(0); } player->getUniqueRoomParent()->setFaction(faction->getName()); player->print("Faction set to %s.\n", player->getUniqueRoomParent()->getFaction().c_str()); log_immort(true, player, "%s set faction to %s in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getFaction().c_str(), room->fullName().c_str()); break; } else { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } num = cmnd->val[2]; if(num < 1 || num > MAX_ROOM_FLAGS) { player->print("Error: outside of range.\n"); return(0); } if(!player->isCt() && num == R_CONSTRUCTION+1) { player->print("Error: you cannot set/clear that flag.\n"); return(0); } if(!strcmp(cmnd->str[3], "del")) { for(a=0;a<MAX_ROOM_FLAGS;a++) player->getUniqueRoomParent()->clearFlag(a); player->print("All room flags cleared.\n"); log_immort(true, player, "%s cleared all flags in room %s.\n", player->getCName(), room->fullName().c_str()); break; } if(player->getUniqueRoomParent()->flagIsSet(num - 1)) { player->getUniqueRoomParent()->clearFlag(num - 1); player->print("Room flag #%d(%s) off.\n", num, gConfig->getRFlag(num-1).c_str()); log_immort(true, player, "%s cleared flag #%d(%s) in room %s.\n", player->getCName(), num, gConfig->getRFlag(num-1).c_str(), room->fullName().c_str()); } else { if(num >= R_TRAINING_ROOM && num - 4 <= R_TRAINING_ROOM) { // setting a training flag - do we let them? if(player->getUniqueRoomParent()->whatTraining(num-1) == CreatureClass::NONE) { player->print("You are setting training for a class that does not exist.\n"); return(0); } } player->getUniqueRoomParent()->setFlag(num - 1); player->print("Room flag #%d(%s) on.\n", num, gConfig->getRFlag(num-1).c_str()); log_immort(true, player, "%s set flag #%d(%s) in room %s.\n", player->getCName(), num, gConfig->getRFlag(num-1).c_str(), room->fullName().c_str()); if(num-1 == R_SHOP) player->printColor("^YNote:^x you must set the Shop Storage (97) to use this room as a shop.\n"); if((num-1 == R_INDOORS || num-1 == R_VAMPIRE_COVEN || num-1 == R_UNDERGROUND) && player->getUniqueRoomParent()->getSize() == NO_SIZE) player->printColor("^YNote:^x don't forget to set the size for this room.\n"); } // try and be smart if( num-1 == R_SHOP_STORAGE && player->getUniqueRoomParent()->getName() == "New Room" && player->getUniqueRoomParent()->exits.empty()) { cr = player->getUniqueRoomParent()->info; UniqueRoom* shop=nullptr; std::string storageName = "Storage: "; cr.id--; if(loadRoom(cr, &shop)) { if( shop->flagIsSet(R_SHOP) && (!shop->getTrapExit().id || shop->getTrapExit() == cr) ) { player->printColor("^ySetting up this storage room for you...\n"); player->printColor("^y * ^xSetting the trap exit to %s...\n", cr.str().c_str()); player->getUniqueRoomParent()->setTrapExit(cr); player->printColor("^y * ^xCreating exit ""out"" to %s...\n", cr.str().c_str()); link_rom(player->getUniqueRoomParent(), cr, "out"); player->getUniqueRoomParent()->setTrapExit(cr); player->printColor("^y * ^xNaming this room...\n"); storageName += shop->getName(); player->getUniqueRoomParent()->setName(storageName); player->print("Done!\n"); } } } } break; case 'l': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(strcmp(cmnd->str[3], "clear") != 0) { player->print("Are you sure?\nType \"*set r last clear\" to clear last-arrived info.\n"); return(0); } strcpy(player->getUniqueRoomParent()->lastPly, ""); strcpy(player->getUniqueRoomParent()->lastPlyTime, ""); player->print("Last-arrived info cleared.\n"); break; case 'm': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->setMaxMobs(cmnd->val[2]); if(!player->getUniqueRoomParent()->getMaxMobs()) player->print("The limit on the number of creatures that can be here has been removed.\n"); else player->print("Only %d creature%s can now be in here at a time.\n", player->getUniqueRoomParent()->getMaxMobs(), player->getUniqueRoomParent()->getMaxMobs() != 1 ? "s" : ""); log_immort(true, player, "%s set max %d mobs in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getMaxMobs(), room->fullName().c_str()); break; case 'n': if(!player->inAreaRoom()) { player->print("Error: You need to be in an area room to do that.\n"); return(0); } if(!player->getAreaRoomParent()->unique.id) { player->print("Error: The area room must have the unique field set [*set r unique #].\n"); return(0); } player->getAreaRoomParent()->setNeedsCompass(!player->getAreaRoomParent()->getNeedsCompass()); player->printColor("NeedsCompass toggled, set to %s^x.\n", player->getAreaRoomParent()->getNeedsCompass() ? "^gYes" : "^rNo"); log_immort(true, player, "%s set needsCompass to %s in room %s.\n", player->getCName(), player->getAreaRoomParent()->getNeedsCompass() ? "true" : "false", room->fullName().c_str()); break; case 'r': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } num = atoi(&cmnd->str[2][1]); if(num < 1 || num > NUM_RANDOM_SLOTS) { player->print("Error: outside of range.\n"); return(PROMPT); } getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player); if(!cr.id) { player->getUniqueRoomParent()->wander.random.erase(num-1); player->print("Random #%d has been cleared.\n", num); } else { player->getUniqueRoomParent()->wander.random[num-1] = cr; player->print("Random #%d is now %s.\n", num, cr.str().c_str()); } log_immort(false,player, "%s set mob slot %d to mob %s in room %s.\n", player->getCName(), num, cr.str().c_str(), room->fullName().c_str()); break; case 's': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->setSize(getSize(cmnd->str[3])); player->print("Size set to %s.\n", getSizeName(player->getUniqueRoomParent()->getSize()).c_str()); log_immort(true, player, "%s set room %s's %s to %s.\n", player->getCName(), room->fullName().c_str(), "Size", getSizeName(player->getUniqueRoomParent()->getSize()).c_str()); break; case 't': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } player->getUniqueRoomParent()->wander.setTraffic(cmnd->val[2]); log_immort(true, player, "%s set room %s's traffic to %ld.\n", player->getCName(), player->getUniqueRoomParent()->info.str().c_str(), player->getUniqueRoomParent()->wander.getTraffic()); player->print("Traffic is now %d%%.\n", player->getUniqueRoomParent()->wander.getTraffic()); break; case 'x': if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(low(cmnd->str[2][1]) == 'x') { getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player); if(!player->checkBuilder(cr)) { player->print("Trap's exit must be within an assigned range.\n"); return(0); } player->getUniqueRoomParent()->setTrapExit(cr); player->print("Room's trap exit is now %s.\n", player->getUniqueRoomParent()->getTrapExit().str().c_str()); log_immort(true, player, "%s set trapexit to %s in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapExit().str().c_str(), room->fullName().c_str()); } else if(low(cmnd->str[2][1]) == 'w') { num = (int)cmnd->val[2]; if(num < 0 || num > 5000) { player->print("Trap weight cannot be less than 0 or greater than 5000.\n"); return(0); } player->getUniqueRoomParent()->setTrapWeight(num); player->print("Room's trap weight is now %d.\n", player->getUniqueRoomParent()->getTrapWeight()); log_immort(true, player, "%s set trapweight to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapWeight(), room->fullName().c_str()); } else if(low(cmnd->str[2][1]) == 's') { num = (int)cmnd->val[2]; if(num < 0 || num > 5000) { player->print("Trap strength cannot be less than 0 or greater than 5000.\n"); return(0); } player->getUniqueRoomParent()->setTrapStrength(num); player->print("Room's trap strength is now %d.\n", player->getUniqueRoomParent()->getTrapStrength()); log_immort(true, player, "%s set trapstrength to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapStrength(), room->fullName().c_str()); } else { player->getUniqueRoomParent()->setTrap(cmnd->val[2]); player->print("Room has trap #%d set.\n", player->getUniqueRoomParent()->getTrap()); log_immort(true, player, "%s set trap #%d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrap(), room->fullName().c_str()); } break; case 'u': if(!player->inAreaRoom()) { player->print("Error: You need to be in an area room to do that.\n"); return(0); } getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player); player->getAreaRoomParent()->unique = cr; player->print("Unique room set to %s.\n", player->getAreaRoomParent()->unique.str().c_str()); if(player->getAreaRoomParent()->unique.id) player->print("You'll need to use *teleport to get to this room in the future.\n"); log_immort(true, player, "%s set unique room to %s in room %s.\n", player->getCName(), player->getAreaRoomParent()->unique.str().c_str(), room->fullName().c_str()); break; default: player->print("Invalid option.\n"); return(0); } if(player->inUniqueRoom()) player->getUniqueRoomParent()->escapeText(); room_track(player); return(0); } //********************************************************************* // dmSetExit //********************************************************************* // This function allows staff to set a characteristic of an exit. int dmSetExit(Player* player, cmd* cmnd) { BaseRoom* room = player->getRoomParent(); int num=0; //char orig_exit[30]; short n=0; if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } // setting something on the exit if(cmnd->str[1][1]) { if(cmnd->num < 3) { player->print("Invalid syntax.\n"); return(0); } Exit* exit = findExit(player, cmnd->str[2], 1); if(!exit) { player->print("Exit not found.\n"); return(0); } switch(cmnd->str[1][1]) { case 'd': { if(cmnd->str[1][2] == 'i') { Direction dir = getDir(cmnd->str[3]); if(getDir(exit->getName()) != NoDirection && dir != NoDirection) { player->print("This exit does not need a direction set on it.\n"); return(0); } exit->setDirection(dir); player->printColor("%s^x's %s set to %s.\n", exit->getCName(), "Direction", getDirName(exit->getDirection()).c_str()); log_immort(true, player, "%s set %s %s^g's %s to %s.\n", player->getCName(), "exit", exit->getCName(), "Direction", getDirName(exit->getDirection()).c_str()); } else if(cmnd->str[1][2] == 'e') { std::string desc = getFullstrText(cmnd->fullstr, 3); boost::replace_all(desc, "*CR*", "\n"); exit->setDescription(desc); if(exit->getDescription().empty()) { player->print("Description cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Description"); } else { player->print("Description set to \"%s\".\n", exit->getDescription().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Description", exit->getDescription().c_str()); } } else { player->print("Description or direction?\n"); return(0); } break; } case 'e': if(cmnd->str[1][2] == 'f') { if(cmnd->num < 4) { player->print("Set what effect to what?\n"); return(0); } long duration = -1; int strength = 1; std::string txt = getFullstrText(cmnd->fullstr, 4); if(!txt.empty()) duration = atoi(txt.c_str()); txt = getFullstrText(cmnd->fullstr, 5); if(!txt.empty()) strength = atoi(txt.c_str()); if(duration > EFFECT_MAX_DURATION || duration < -1) { player->print("Duration must be between -1 and %d.\n", EFFECT_MAX_DURATION); return(0); } if(strength < 0 || strength > EFFECT_MAX_STRENGTH) { player->print("Strength must be between 0 and %d.\n", EFFECT_MAX_STRENGTH); return(0); } std::string effectStr = cmnd->str[3]; EffectInfo* toSet = nullptr; if((toSet = exit->getExactEffect(effectStr))) { // We have an existing effect we're modifying if(duration == 0) { // Duration is 0, so remove it exit->removeEffect(toSet, true); player->print("Effect '%s' (exit) removed.\n", effectStr.c_str()); } else { // Otherwise modify as appropriate toSet->setDuration(duration); if(strength != -1) toSet->setStrength(strength); player->print("Effect '%s' (exit) set to duration %d and strength %d.\n", effectStr.c_str(), toSet->getDuration(), toSet->getStrength()); } } else { // No existing effect, add a new one if(strength == -1) strength = 1; if(exit->addEffect(effectStr, duration, strength, nullptr, true) != nullptr) { player->print("Effect '%s' (exit) added with duration %d and strength %d.\n", effectStr.c_str(), duration, strength); } else { player->print("Unable to add effect '%s' (exit)\n", effectStr.c_str()); } } break; } else { exit->setEnter(getFullstrText(cmnd->fullstr, 3)); if(exit->getEnter().empty() || Pueblo::is(exit->getEnter())) { exit->setEnter(""); player->print("OnEnter cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "OnEnter"); } else { player->print("OnEnter set to \"%s\".\n", exit->getEnter().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "OnEnter", exit->getEnter().c_str()); } } break; case 'f': num = cmnd->val[2]; if(num < 1 || num > MAX_EXIT_FLAGS) { player->print("Error: flag out of range.\n"); return(PROMPT); } if(exit->flagIsSet(num - 1)) { exit->clearFlag(num - 1); player->printColor("%s^x exit flag #%d off.\n", exit->getCName(), num); log_immort(true, player, "%s cleared %s^g exit flag #%d(%s) in room %s.\n", player->getCName(), exit->getCName(), num, gConfig->getXFlag(num-1).c_str(), room->fullName().c_str()); } else { exit->setFlag(num - 1); player->printColor("%s^x exit flag #%d on.\n", exit->getCName(), num); log_immort(true, player, "%s turned on %s^g exit flag #%d(%s) in room %s.\n", player->getCName(), exit->getCName(), num, gConfig->getXFlag(num-1).c_str(), room->fullName().c_str()); } break; case 'k': if(cmnd->str[1][2] == 'a') { exit->setKeyArea(cmnd->str[3]); if(exit->getKeyArea().empty()) { player->print("Key Area cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Key Area"); } else { player->print("Key Area set to \"%s\".\n", exit->getKeyArea().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Key Area", exit->getKeyArea().c_str()); } } else { if(cmnd->val[2] > 255 || cmnd->val[2] < 0) { player->print("Error: key out of range.\n"); return(0); } exit->setKey(cmnd->val[2]); player->printColor("Exit %s^x key set to %d.\n", exit->getCName(), exit->getKey()); log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Key", exit->getKey()); } break; case 'l': if(cmnd->val[2] > MAXALVL || cmnd->val[2] < 0) { player->print("Level must be from 0 to %d.\n", MAXALVL); return(0); } exit->setLevel(cmnd->val[2]); player->printColor("Exit %s^x's level is now set to %d.\n", exit->getCName(), exit->getLevel()); log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Pick Level", exit->getLevel()); break; case 'o': exit->setOpen(getFullstrText(cmnd->fullstr, 3)); if(exit->getOpen().empty() || Pueblo::is(exit->getOpen())) { exit->setOpen(""); player->print("OnOpen cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "OnOpen"); } else { player->print("OnOpen set to \"%s\".\n", exit->getOpen().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "OnOpen", exit->getOpen().c_str()); } break; case 'p': if(low(cmnd->str[1][2]) == 'p') { exit->setPassPhrase(getFullstrText(cmnd->fullstr, 3)); if(exit->getPassPhrase().empty()) { player->print("Passphrase cleared.\n"); log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Passphrase"); } else { player->print("Passphrase set to \"%s\".\n", exit->getPassPhrase().c_str()); log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Passphrase", exit->getPassPhrase().c_str()); } } else if(low(cmnd->str[1][2]) == 'l') { n = cmnd->val[2]; if(n < 0 || n > LANGUAGE_COUNT) { player->print("Error: pass language out of range.\n"); return(0); } n--; if(n < 0) n = 0; exit->setPassLanguage(n); player->print("Pass language %s.\n", n ? "set" : "cleared"); log_immort(true, player, "%s set %s^g's %s to %s(%ld).\n", player->getCName(), exit->getCName(), "Passlang", n ? get_language_adj(n) : "Nothing", n+1); } else { player->print("Passphrase (xpp) or passlang (xpl)?\n"); return(0); } break; case 's': exit->setSize(getSize(cmnd->str[3])); player->printColor("%s^x's %s set to %s.\n", exit->getCName(), "Size", getSizeName(exit->getSize()).c_str()); log_immort(true, player, "%s set %s %s^g's %s to %s.\n", player->getCName(), "exit", exit->getCName(), "Size", getSizeName(exit->getSize()).c_str()); break; case 't': n = (short)cmnd->val[2]; if(n > 30000 || n < 0) { player->print("Must be between 0-30000.\n"); return(0); } exit->setToll(n); player->printColor("Exit %s^x's toll is now set to %d.\n", exit->getCName(), exit->getToll()); log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Toll", exit->getToll()); break; default: player->print("Invalid syntax.\n"); return(0); } if(player->inUniqueRoom()) player->getUniqueRoomParent()->escapeText(); room_track(player); return(0); } // otherwise, we have other plans for this function if(cmnd->num < 3) { player->print("Syntax: *set x <name> <#> [. or name]\n"); return(0); } // we need more variables to continue our work MapMarker mapmarker; BaseRoom* room2=nullptr; AreaRoom* aRoom=nullptr; UniqueRoom *uRoom=nullptr; Area *area=nullptr; CatRef cr; std::string returnExit = getFullstrText(cmnd->fullstr, 4); getDestination(getFullstrText(cmnd->fullstr, 3).c_str(), &mapmarker, &cr, player); if(!mapmarker.getArea() && !cr.id) { // if the expanded exit wasnt found // and the exit was expanded, check to delete the original if(room->delExit(cmnd->str[2])) player->print("Exit %s deleted.\n", cmnd->str[2]); else player->print("Exit %s not found.\n", cmnd->str[2]); return(0); } if(cr.id) { if(!player->checkBuilder(cr)) return(0); if(!loadRoom(cr, &uRoom)) { player->print("Room %s does not exist.\n", cr.str().c_str()); return(0); } room2 = uRoom; } else { if(player->getClass() == CreatureClass::BUILDER) { player->print("Sorry, builders cannot link exits to the overland.\n"); return(0); } area = gServer->getArea(mapmarker.getArea()); if(!area) { player->print("Area does not exist.\n"); return(0); } aRoom = area->loadRoom(nullptr, &mapmarker, false); room2 = aRoom; } std::string newName = getFullstrText(cmnd->fullstr, 2, ' ', false, true); if(newName.length() > 20) { player->print("Exit names must be 20 characters or less in length.\n"); return(0); } newName = expand_exit_name(newName); if(!returnExit.empty()) { if(returnExit == ".") returnExit = opposite_exit_name(newName); if(cr.id) { link_rom(room, cr, newName); if(player->inUniqueRoom()) link_rom(uRoom, player->getUniqueRoomParent()->info, returnExit); else link_rom(uRoom, &player->getAreaRoomParent()->mapmarker, returnExit); gServer->resaveRoom(cr); } else { link_rom(room, &mapmarker, newName); if(player->inUniqueRoom()) link_rom(aRoom, player->getUniqueRoomParent()->info, returnExit); else link_rom(aRoom, &player->getAreaRoomParent()->mapmarker, returnExit); aRoom->save(); } log_immort(true, player, "%s linked room %s to room %s in %s^g direction, both ways.\n", player->getCName(), room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); player->printColor("Room %s linked to room %s in %s^x direction, both ways.\n", room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); } else { if(cr.id) link_rom(room, cr, newName); else link_rom(room, &mapmarker, newName); player->printColor("Room %s linked to room %s in %s^x direction.\n", room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); log_immort(true, player, "%s linked room %s to room %s in %s^g direction.\n", player->getCName(), room->fullName().c_str(), room2->fullName().c_str(), newName.c_str()); } if(player->inUniqueRoom()) gServer->resaveRoom(player->getUniqueRoomParent()->info); if(aRoom && aRoom->canDelete()) area->remove(aRoom); room_track(player); return(0); } //********************************************************************* // room_track //********************************************************************* int room_track(Creature* player) { long t = time(nullptr); if(player->isMonster() || !player->inUniqueRoom()) return(0); strcpy(player->getUniqueRoomParent()->last_mod, player->getCName()); strcpy(player->getUniqueRoomParent()->lastModTime, ctime(&t)); return(0); } //********************************************************************* // dmReplace //********************************************************************* // this command lets staff replace words or phrases in a room description int dmReplace(Player* player, cmd* cmnd) { UniqueRoom *room = player->getUniqueRoomParent(); int n=0, skip=0, skPos=0; std::string::size_type i=0, pos=0; char delim = ' '; bool sdesc=false, ldesc=false; std::string search = "", temp = ""; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 3) { player->print("syntax: *replace [-SL#<num>] <search> <replace>\n"); return(0); } // we have flags! // let's find out what they are if(cmnd->str[1][0] == '-') { i=1; while(i < strlen(cmnd->str[1])) { switch(cmnd->str[1][i]) { case 'l': ldesc = true; break; case 's': sdesc = true; break; case '#': skip = atoi(&cmnd->str[1][++i]); break; default: break; } i++; } } // we need to get fullstr into a nicer format i = strlen(cmnd->str[0]); if(ldesc || sdesc || skip) i += strlen(cmnd->str[1]) + 1; // which deliminator should we use? if(cmnd->fullstr[i+1] == '\'' || cmnd->fullstr[i+1] == '"' || cmnd->fullstr[i+1] == '*') { delim = cmnd->fullstr[i+1]; i++; } // fullstr is now our search text and replace text seperated by a space cmnd->fullstr = cmnd->fullstr.substr(i+1); //strcpy(cmnd->fullstr, &cmnd->fullstr[i+1]); // we search until we find the deliminator we're looking for pos=0; i = cmnd->fullstr.length(); while(pos < i) { if(cmnd->fullstr[pos] == delim) break; pos++; } if(pos == i) { if(delim != ' ') player->print("Deliminator not found.\n"); else player->print("No replace text found.\n"); return(0); } // cut the string apart cmnd->fullstr[pos] = 0; search = cmnd->fullstr; // if it's not a space, we need to add 2 to get rid of the space and // next deliminator if(delim != ' ') { pos += 2; // although we don't have to, we're enforcing that the deliminators // equal each other so people are consistent with the usage of this function if(cmnd->fullstr[pos] != delim) { player->print("Deliminators do not match up.\n"); return(0); } } // fullstr now has our replace text //strcpy(cmnd->fullstr, &cmnd->fullstr[pos+1]); cmnd->fullstr = cmnd->fullstr.substr(pos+1); if(delim != ' ') { if(cmnd->fullstr[cmnd->fullstr.length()-1] != delim) { player->print("Deliminators do not match up.\n"); return(0); } cmnd->fullstr[cmnd->fullstr.length()-1] = 0; } // the text we are searching for is in "search" // the text we are replacing it with is in "fullstr" // we will use i to help us reuse code // 0 = sdesc, 1 = ldesc i = 0; // if only long desc, skip short desc if(ldesc && !sdesc) i++; // loop for the short and long desc do { // loop for skip do { if(!i) n = room->getShortDescription().find(search.c_str(), skPos); else n = room->getLongDescription().find(search.c_str(), skPos); if(n >= 0) { if(--skip > 0) skPos = n + 1; else { if(!i) { temp = room->getShortDescription().substr(0, n); temp += cmnd->fullstr; temp += room->getShortDescription().substr(n + search.length(), room->getShortDescription().length()); room->setShortDescription(temp); } else { temp = room->getLongDescription().substr(0, n); temp += cmnd->fullstr; temp += room->getLongDescription().substr(n + search.length(), room->getLongDescription().length()); room->setLongDescription(temp); } player->print("Replaced.\n"); room->escapeText(); return(0); } } } while(n >= 0 && skip); // if we're on long desc (i=1), we'll stop after this, so no worries // if we're on short desc and not doing long desc, we need to stop if(sdesc && !ldesc) i++; i++; } while(i<2); player->print("Pattern not found.\n"); return(0); } //********************************************************************* // dmDelete //********************************************************************* // Allows staff to delete some/all of the room description int dmDelete(Player* player, cmd* cmnd) { UniqueRoom *room = player->getUniqueRoomParent(); int pos=0; int unsigned i=0; bool sdesc=false, ldesc=false, phrase=false, after=false; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 2) { player->print("syntax: *delete [-ASLPE] <delete_word>\n"); return(0); } // take care of the easy one if(!strcmp(cmnd->str[1], "-a")) { room->setShortDescription(""); room->setLongDescription(""); } else { // determine our flags i=1; while(i < strlen(cmnd->str[1])) { switch(cmnd->str[1][i]) { case 'l': ldesc = true; break; case 's': sdesc = true; break; case 'p': phrase = true; break; case 'e': after = true; break; default: break; } i++; } // a simple delete operation if(!phrase && !after) { if(sdesc) room->setShortDescription(""); if(ldesc) room->setLongDescription(""); if(!sdesc && !ldesc) { player->print("Invalid syntax.\n"); return(0); } } else { // we need to figure out what our phrase is // turn fullstr into what we want to delete i = strlen(cmnd->str[0]) + strlen(cmnd->str[1]) + 1; if( i >= cmnd->fullstr.length() ) { player->print("Pattern not found.\n"); return(0); } // fullstr is now our phrase cmnd->fullstr = cmnd->fullstr.substr(i+1); // we will use i to help us reuse code // 0 = sdesc, 1 = ldesc i = 0; // if only long desc, skip short desc if(ldesc && !sdesc) i++; // loop! do { if(!i) pos = room->getShortDescription().find(cmnd->fullstr); else pos = room->getLongDescription().find(cmnd->fullstr); if(pos >= 0) break; // if we're on long desc (i=1), we'll stop after this, so no worries // if we're on short desc and not doing long desc, we need to stop if(sdesc && !ldesc) i++; i++; } while(i<2); // did we find it? if(pos < 0) { player->print("Pattern not found.\n"); return(0); } // we delete everything after the phrase if(after) { if(!phrase) pos += cmnd->fullstr.length(); // if it's in the short desc, and they wanted to delete // from both short and long, then delete all of long if(!i && !(sdesc ^ ldesc)) room->setLongDescription(""); if(!i) room->setShortDescription(room->getShortDescription().substr(0, pos)); else room->setLongDescription(room->getLongDescription().substr(0, pos)); // only delete the phrase } else { if(!i) room->setShortDescription(room->getShortDescription().substr(0, pos) + room->getShortDescription().substr(pos + cmnd->fullstr.length(), room->getShortDescription().length())); else room->setLongDescription(room->getLongDescription().substr(0, pos) + room->getLongDescription().substr(pos + cmnd->fullstr.length(), room->getLongDescription().length())); } } // phrase && after } // *del -A log_immort(true, player, "%s deleted description in room %s.\n", player->getCName(), player->getUniqueRoomParent()->info.str().c_str()); player->print("Deleted.\n"); return(0); } //********************************************************************* // dmNameRoom //********************************************************************* int dmNameRoom(Player* player, cmd* cmnd) { if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } std::string name = getFullstrText(cmnd->fullstr, 1); if(name.empty() || Pueblo::is(name)) { player->print("Rename room to what?\n"); return(0); } if(name.length() > 79) name = name.substr(0, 79); player->getUniqueRoomParent()->setName(name); log_immort(true, player, "%s renamed room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->print("Done.\n"); return(0); } //********************************************************************* // dmDescription //********************************************************************* // Allows a staff to add the given text to the room description. int dmDescription(Player* player, cmd* cmnd, bool append) { UniqueRoom *room = player->getUniqueRoomParent(); int unsigned i=0; bool sdesc=false, newline=false; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 2) { player->print("syntax: *%s [-sn] <text>\n", append ? "append" : "prepend"); return(0); } // turn fullstr into what we want to append i = strlen(cmnd->str[0]); sdesc = cmnd->str[1][0] == '-' && (cmnd->str[1][1] == 's' || cmnd->str[1][2] == 's'); newline = !(cmnd->str[1][0] == '-' && (cmnd->str[1][1] == 'n' || cmnd->str[1][2] == 'n')); // keep chopping if(sdesc || !newline) i += strlen(cmnd->str[1]) + 1; cmnd->fullstr = cmnd->fullstr.substr(i+1); // strcpy(cmnd->fullstr, &cmnd->fullstr[i+1]); if(cmnd->fullstr.find(" ") != std::string::npos) player->printColor("Do not use double spaces in room descriptions! Use ^W*wrap^x to fix this.\n"); if(sdesc) { // short descriptions newline = newline && !room->getShortDescription().empty(); if(append) { room->appendShortDescription(newline ? "\n" : ""); room->appendShortDescription(cmnd->fullstr); } else { if(newline) cmnd->fullstr += "\n"; room->setShortDescription(cmnd->fullstr + room->getShortDescription()); } player->print("Short description %s.\n", append ? "appended" : "prepended"); } else { // long descriptions newline = newline && !room->getLongDescription().empty(); if(append) { room->appendLongDescription(newline ? "\n" : ""); room->appendLongDescription(cmnd->fullstr); } else { if(newline) cmnd->fullstr += "\n"; room->setLongDescription(cmnd->fullstr + room->getLongDescription()); } player->print("Long description %s.\n", append ? "appended" : "prepended"); } player->getUniqueRoomParent()->escapeText(); log_immort(true, player, "%s descripted in room %s.\n", player->getCName(), player->getUniqueRoomParent()->info.str().c_str()); return(0); } //********************************************************************* // dmAppend //********************************************************************* int dmAppend(Player* player, cmd* cmnd) { return(dmDescription(player, cmnd, true)); } //********************************************************************* // dmPrepend //********************************************************************* int dmPrepend(Player* player, cmd* cmnd) { return(dmDescription(player, cmnd, false)); } //********************************************************************* // dmMobList //********************************************************************* // Display information about what mobs will randomly spawn. void showMobList(Player* player, WanderInfo *wander, std::string_view type) { std::map<int, CatRef>::iterator it; Monster *monster=nullptr; bool found=false, maybeAggro=false; std::ostringstream oStr; for(it = wander->random.begin(); it != wander->random.end() ; it++) { if(!found) oStr << "^cTraffic = " << wander->getTraffic() << "\n"; found=true; if(!(*it).second.id) continue; if(!loadMonster((*it).second, &monster)) continue; if(monster->flagIsSet(M_AGGRESSIVE)) oStr << "^r"; else { maybeAggro = monster->flagIsSet(M_AGGRESSIVE_EVIL) || monster->flagIsSet(M_AGGRESSIVE_GOOD) || monster->flagIsSet(M_AGGRESSIVE_AFTER_TALK) || monster->flagIsSet(M_CLASS_AGGRO_INVERT) || monster->flagIsSet(M_RACE_AGGRO_INVERT) || monster->flagIsSet(M_DEITY_AGGRO_INVERT); if(!maybeAggro) { RaceDataMap::iterator rIt; for(rIt = gConfig->races.begin() ; rIt != gConfig->races.end() ; rIt++) { if(monster->isRaceAggro((*rIt).second->getId(), false)) { maybeAggro = true; break; } } } if(!maybeAggro) { for(int n=1; n<static_cast<int>(STAFF); n++) { if(monster->isClassAggro(n, false)) { maybeAggro = true; break; } } } if(!maybeAggro) { DeityDataMap::iterator dIt; for(dIt = gConfig->deities.begin() ; dIt != gConfig->deities.end() ; dIt++) { if(monster->isDeityAggro((*dIt).second->getId(), false)) { maybeAggro = true; break; } } } if(maybeAggro) oStr << "^y"; else oStr << "^g"; } oStr << "Slot " << std::setw(2) << (*it).first+1 << ": " << monster->getName() << " " << "[" << monType::getName(monster->getType()) << ":" << monType::getHitdice(monster->getType()) << "HD]\n" << " ^x[I:" << monster->info.str() << " L:" << monster->getLevel() << " X:" << monster->getExperience() << " G:" << monster->coins[GOLD] << " H:" << monster->hp.getMax() << " M:" << monster->mp.getMax() << " N:" << (monster->getNumWander() ? monster->getNumWander() : 1) << (monster->getAlignment() > 0 ? "^g" : "") << (monster->getAlignment() < 0 ? "^r" : "") << " A:" << monster->getAlignment() << "^x D:" << monster->damage.average() << "]\n"; free_crt(monster); } if(!found) oStr << " No random monsters currently come in this " << type << "."; player->printColor("%s\n", oStr.str().c_str()); } int dmMobList(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } player->print("Random monsters which come in this room:\n"); if(player->inUniqueRoom()) showMobList(player, &player->getUniqueRoomParent()->wander, "room"); else if(player->inAreaRoom()) { Area* area = player->getAreaRoomParent()->area; std::list<AreaZone*>::iterator it; AreaZone *zone=nullptr; for(it = area->zones.begin() ; it != area->zones.end() ; it++) { zone = (*it); if(zone->inside(area, &player->getAreaRoomParent()->mapmarker)) { player->print("Zone: %s\n", zone->name.c_str()); showMobList(player, &zone->wander, "zone"); } } TileInfo* tile = area->getTile(area->getTerrain(nullptr, &player->getAreaRoomParent()->mapmarker, 0, 0, 0, true), area->getSeasonFlags(&player->getAreaRoomParent()->mapmarker)); if(tile && tile->wander.getTraffic()) { player->print("Tile: %s\n", tile->getName().c_str()); showMobList(player, &tile->wander, "tile"); } } return(0); } //********************************************************************* // dmWrap //********************************************************************* // dmWrap will either wrap the short or long desc of a room to the // specified length, for sanity, a range of 60 - 78 chars is the limit. int dmWrap(Player* player, cmd* cmnd) { UniqueRoom *room = player->getUniqueRoomParent(); int wrap=0; bool err=false, which=false; std::string text = ""; if(!needUniqueRoom(player)) return(0); if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } // parse the input command for syntax/range problems if(cmnd->num < 2) err = true; else { switch(cmnd->str[1][0]) { case 'l': which = true; text = room->getLongDescription(); break; case 's': which = false; text = room->getShortDescription(); break; default: err = true; break; } if(!err) { wrap = cmnd->val[1]; if(wrap < 60 || wrap > 78) err = true; } } if(err) { player->print("*wrap <s | l> <len> where len is between 60 and 78 >\n"); return(0); } if((!which && room->getShortDescription().empty()) || (which && room->getLongDescription().empty())) { player->print("No text to wrap!\n"); return(0); } // adjust! wrap++; // replace! if(!which) room->setShortDescription(wrapText(room->getShortDescription(), wrap)); else room->setLongDescription(wrapText(room->getLongDescription(), wrap)); player->print("Text wrapped.\n"); player->getUniqueRoomParent()->escapeText(); log_immort(false, player, "%s wrapped the description in room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); return(0); } //********************************************************************* // dmDeleteAllExits //********************************************************************* int dmDeleteAllExits(Player* player, cmd* cmnd) { if(player->getRoomParent()->exits.empty()) { player->print("No exits to delete.\n"); return(0); } player->getRoomParent()->clearExits(); // sorry, can't delete exits in overland if(player->inAreaRoom()) player->getAreaRoomParent()->updateExits(); player->print("All exits deleted.\n"); log_immort(true, player, "%s deleted all exits in room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); room_track(player); return(0); } //********************************************************************* // exit_ordering //********************************************************************* // 1 mean exit2 goes in front of exit1 // 0 means keep looking int exit_ordering(const char *exit1, const char *exit2) { // always skip if they're the same name if(!strcmp(exit1, exit2)) return(0); // north east south west if(!strcmp(exit1, "north")) return(0); if(!strcmp(exit2, "north")) return(1); if(!strcmp(exit1, "east")) return(0); if(!strcmp(exit2, "east")) return(1); if(!strcmp(exit1, "south")) return(0); if(!strcmp(exit2, "south")) return(1); if(!strcmp(exit1, "west")) return(0); if(!strcmp(exit2, "west")) return(1); // northeast northwest southeast southwest if(!strcmp(exit1, "northeast")) return(0); if(!strcmp(exit2, "northeast")) return(1); if(!strcmp(exit1, "northwest")) return(0); if(!strcmp(exit2, "northwest")) return(1); if(!strcmp(exit1, "southeast")) return(0); if(!strcmp(exit2, "southeast")) return(1); if(!strcmp(exit1, "southwest")) return(0); if(!strcmp(exit2, "southwest")) return(1); if(!strcmp(exit1, "up")) return(0); if(!strcmp(exit2, "up")) return(1); if(!strcmp(exit1, "down")) return(0); if(!strcmp(exit2, "down")) return(1); // alphabetic return strcmp(exit1, exit2) > 0 ? 1 : 0; } //********************************************************************* // dmArrangeExits //********************************************************************* bool exitCompare( const Exit* left, const Exit* right ){ return(!exit_ordering(left->getCName(), right->getCName())); } void BaseRoom::arrangeExits(Player* player) { if(exits.size() <= 1) { if(player) player->print("No exits to rearrange!\n"); return; } exits.sort(exitCompare); if(player) player->print("Exits rearranged!\n"); } int dmArrangeExits(Player* player, cmd* cmnd) { if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Error: Room number not inside any of your alotted ranges.\n"); return(0); } player->getRoomParent()->arrangeExits(player); return(0); } //********************************************************************* // link_rom //********************************************************************* // from this room to unique room void link_rom(BaseRoom* room, const Location& l, std::string_view str) { for(Exit* ext : room->exits) { if(ext->getName() == str) { ext->target = l; return; } } Exit* exit = new Exit; exit->setRoom(room); exit->setName(str); exit->target = l; room->exits.push_back(exit); } void link_rom(BaseRoom* room, short tonum, std::string_view str) { Location l; l.room.id = tonum; link_rom(room, l, str); } void link_rom(BaseRoom* room, const CatRef& cr, std::string_view str) { Location l; l.room = cr; link_rom(room, l, str); } void link_rom(BaseRoom* room, MapMarker *mapmarker, std::string_view str) { Location l; l.mapmarker = *mapmarker; link_rom(room, l, str); } //********************************************************************* // dmFix //********************************************************************* int dmFix(Player* player, cmd* cmnd, std::string_view name, char find, char replace) { Exit *exit=nullptr; int i=0; bool fixed=false; if(cmnd->num < 2) { player->bPrint(fmt::format("Syntax: *{}up <exit>\n", name)); return(0); } exit = findExit(player, cmnd); if(!exit) { player->print("You don't see that exit.\n"); return(0); } std::string newName = exit->getName(); for(i=newName.length(); i>0; i--) { if(newName[i] == find) { newName[i] = replace; fixed = true; } } if(fixed) { exit->setName(newName); log_immort(true, player, fmt::format("{} {}ed the exit '{}' in room {}.\n", player->getName(), name, exit->getName(), player->getRoomParent()->fullName()).c_str()); player->print("Done.\n"); } else player->print("Couldn't find any underscores.\n"); return(0); } //********************************************************************* // dmUnfixExit //********************************************************************* int dmUnfixExit(Player* player, cmd* cmnd) { return(dmFix(player, cmnd, "unfix", ' ', '_')); } //********************************************************************* // dmFixExit //********************************************************************* int dmFixExit(Player* player, cmd* cmnd) { return(dmFix(player, cmnd, "fix", '_', ' ')); } //********************************************************************* // dmRenameExit //********************************************************************* int dmRenameExit(Player* player, cmd* cmnd) { Exit *exit=nullptr; if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if(cmnd->num < 3) { player->print("Syntax: *xrename <old exit>[#] <new exit>\n"); return(0); } exit = findExit(player, cmnd); if(!exit) { player->print("There is no exit here by that name.\n"); return(0); } std::string newName = getFullstrText(cmnd->fullstr, 2); if(newName.length() > 20) { player->print("New exit name must be 20 characters or less in length.\n"); return(0); } player->printColor("Exit \"%s^x\" renamed to \"%s^x\".\n", exit->getCName(), newName.c_str()); log_immort(false, player, "%s renamed exit %s^g to %s^g in room %s.\n", player->getCName(), exit->getCName(), newName.c_str(), player->getRoomParent()->fullName().c_str()); room_track(player); if(getDir(newName) != NoDirection) exit->setDirection(NoDirection); exit->setName( newName.c_str()); return(0); } //********************************************************************* // dmDestroyRoom //********************************************************************* int dmDestroyRoom(Player* player, cmd* cmnd) { if(!player->inUniqueRoom()) { player->print("Error: You need to be in a unique room to do that.\n"); return(0); } if(!player->checkBuilder(player->getUniqueRoomParent())) { player->print("Room is not in any of your alotted room ranges.\n"); return(0); } if( player->getUniqueRoomParent()->info.isArea("test") && player->getUniqueRoomParent()->info.id == 1 ) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is the Builder Waiting Room.\n"); return(0); } if(player->bound.room == player->currentLocation.room) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is your bound room.\n"); return(0); } std::map<std::string, StartLoc*>::iterator sIt; for(sIt = gConfig->start.begin() ; sIt != gConfig->start.end() ; sIt++) { if( player->getUniqueRoomParent()->info == (*sIt).second->getBind().room || player->getUniqueRoomParent()->info == (*sIt).second->getRequired().room ) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is important to starting locations.\n"); return(0); } } std::list<CatRefInfo*>::const_iterator crIt; for(crIt = gConfig->catRefInfo.begin() ; crIt != gConfig->catRefInfo.end() ; crIt++) { if(player->getUniqueRoomParent()->info.isArea((*crIt)->getArea())) { if((*crIt)->getLimbo() == player->getUniqueRoomParent()->info.id) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is a Limbo room.\n"); return(0); } if((*crIt)->getRecall() == player->getUniqueRoomParent()->info.id) { player->print("Sorry, you cannot destroy this room.\n"); player->print("It is a recall room.\n"); return(0); } } } log_immort(true, player, "%s destroyed room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str()); player->getUniqueRoomParent()->destroy(); return(0); } //********************************************************************* // findRoomsWithFlag //********************************************************************* void findRoomsWithFlag(const Player* player, const Range& range, int flag) { Async async; if(async.branch(player, ChildType::PRINT) == AsyncExternal) { std::ostringstream oStr; bool found = false; if(range.low.id <= range.high) { UniqueRoom* room=nullptr; CatRef cr; int high = range.high; cr.setArea(range.low.area); cr.id = range.low.id; if(range.low.id == -1 && range.high == -1) { cr.id = 1; high = RMAX; } for(; cr.id < high; cr.id++) { if(!loadRoom(cr, &room)) continue; if(room->flagIsSet(flag)) { if(player->isStaff()) oStr << room->info.rstr() << " - "; oStr << room->getName() << "^x\n"; found = true; } } } std::cout << "^YLocations found:^x\n"; if(!found) { std::cout << "No available locations were found."; } else { std::cout << oStr.str(); } exit(0); } } void findRoomsWithFlag(const Player* player, CatRef area, int flag) { Async async; if(async.branch(player, ChildType::PRINT) == AsyncExternal) { struct dirent *dirp=nullptr; DIR *dir=nullptr; std::ostringstream oStr; bool found = false; char filename[250]; UniqueRoom *room=nullptr; // This tells us just to get the path, not the file, // and tells loadRoomFromFile to ignore the CatRef area.id = -1; std::string path = roomPath(area); if((dir = opendir(path.c_str())) != nullptr) { while((dirp = readdir(dir)) != nullptr) { // is this a room file? if(dirp->d_name[0] == '.') continue; sprintf(filename, "%s/%s", path.c_str(), dirp->d_name); if(!loadRoomFromFile(area, &room, filename)) continue; if(room->flagIsSet(flag)) { if(player->isStaff()) oStr << room->info.rstr() << " - "; oStr << room->getName() << "^x\n"; found = true; } // TODO: Memleak (even though it is forked), room is not deleted } } std::cout << "^YLocations found:^x\n"; if(!found) { std::cout << "No available locations were found."; } else { std::cout << oStr.str(); } exit(0); } } //********************************************************************* // dmFind //********************************************************************* int dmFind(Player* player, cmd* cmnd) { std::string type = getFullstrText(cmnd->fullstr, 1); CatRef cr; if(player->inUniqueRoom()) cr = player->getUniqueRoomParent()->info; else cr.setArea("area"); if(type == "r") type = "room"; else if(type == "o") type = "object"; else if(type == "m") type = "monster"; if(type.empty() || (type != "room" && type != "object" && type != "monster")) { if(!type.empty()) player->print("\"%s\" is not a valid type.\n", type.c_str()); player->print("Search for next available of the following: room, object, monster.\n"); return(0); } if(!player->checkBuilder(cr)) { player->print("Error: this area is out of your range; you cannot *find here.\n"); return(0); } if(type == "monster" && !player->canBuildMonsters()) { player->print("Error: you cannot work with monsters.\n"); return(0); } if(type == "object" && !player->canBuildObjects()) { player->print("Error: you cannot work with objects.\n"); return(0); } Async async; if(async.branch(player, ChildType::PRINT) == AsyncExternal) { cr = findNextEmpty(type, cr.area); std::cout << "^YNext available " << type << " in area " << cr.area << "^x\n"; if(cr.id == -1) std::cout << "No empty %ss found.", type.c_str(); else { std::cout << cr.rstr(); } exit(0); } else { player->printColor("Searching for next available %s in ^W%s^x.\n", type.c_str(), cr.area.c_str()); } return(0); } //********************************************************************* // findNextEmpty //********************************************************************* // searches for the next empty room/object/monster in the area CatRef findNextEmpty(const std::string &type, const std::string &area) { CatRef cr; cr.setArea(area); if(type == "room") { UniqueRoom* room=nullptr; for(cr.id = 1; cr.id < RMAX; cr.id++) if(!loadRoom(cr, &room)) return(cr); } else if(type == "object") { Object *object=nullptr; for(cr.id = 1; cr.id < OMAX; cr.id++) { if(!loadObject(cr, &object)) return(cr); else delete object; } } else if(type == "monster") { Monster *monster=nullptr; for(cr.id = 1; cr.id < MMAX; cr.id++) { if(!loadMonster(cr, &monster)) return(cr); else free_crt(monster); } } // -1 indicates failure cr.id = -1; return(cr); } //********************************************************************* // save //********************************************************************* void AreaRoom::save(Player* player) const { char filename[256]; sprintf(filename, "%s/%d/", Path::AreaRoom, area->id); Path::checkDirExists(filename); strcat(filename, mapmarker.filename().c_str()); if(!canSave()) { if(file_exists(filename)) { if(player) player->print("Restoring this room to generic status.\n"); unlink(filename); } else { if(player) player->print("There is no reason to save this room!\n\n"); } return; } // record rooms saved during swap if(gConfig->swapIsInteresting(this)) gConfig->swapLog((std::string)"a" + mapmarker.str(), false); xmlDocPtr xmlDoc; xmlNodePtr rootNode, curNode; xmlDoc = xmlNewDoc(BAD_CAST "1.0"); rootNode = xmlNewDocNode(xmlDoc, nullptr, BAD_CAST "AreaRoom", nullptr); xmlDocSetRootElement(xmlDoc, rootNode); unique.save(rootNode, "Unique", false); xml::saveNonZeroNum(rootNode, "NeedsCompass", needsCompass); xml::saveNonZeroNum(rootNode, "DecCompass", decCompass); effects.save(rootNode, "Effects"); hooks.save(rootNode, "Hooks"); curNode = xml::newStringChild(rootNode, "MapMarker"); mapmarker.save(curNode); curNode = xml::newStringChild(rootNode, "Exits"); saveExitsXml(curNode); xml::saveFile(filename, xmlDoc); xmlFreeDoc(xmlDoc); if(player) player->print("Room saved.\n"); }
RealmsMud/RealmsCode
staff/dmroom.cpp
C++
agpl-3.0
114,289
import React from 'react'; import { Card } from 'bm-kit'; import './_pillar.schedule.source.scss'; const friday = [ { start: '6:00 PM', name: '📋 Check in begins' }, { start: '8:00 PM', name: '🎤 Opening Ceremonies' }, { start: '9:00 PM', name: '🤝 Team assembly' }, { start: '9:30 PM', name: '🌮 Dinner' }, { start: '10:00 PM', name: '💻 Hacking Begins' }, { start: '10:00 PM', name: '🤖 Fundamentals of AI with Intel' }, { start: '12:00 AM', name: '🥋 Ninja' } ]; let saturday = [ { start: '3:00 AM', name: '🍿 Late Night Snack' }, { start: '8:00 AM', name: '🥓 Breakfast' }, { start: '9:00 AM', name: '🏗 Workshop' }, { start: '12:30 PM', name: '🍝 Lunch' }, { start: '1:00 PM', name: '👪 Facebook Tech Talk' }, { start: '2:00 PM', name: '🐶 Doggos/Woofers' }, { start: '2:30 PM', name: '✈️ Rockwell Collins Talk' }, { start: '3:00 PM', name: '🍿 Snack' }, { start: '3:00 PM', name: '🚣🏽 Activity' }, { start: '4:00 PM', name: '📈 Startups with T.A. MaCann' }, { start: '6:00 PM', name: '🍕 Dinner' }, { start: '9:00 PM', name: '🥤 Cup stacking with MLH' }, { start: '10:00 PM', name: '🍩 Donuts and Kona Ice' }, { start: '10:00 PM', name: '🏗️ Jenga' } ]; let sunday = [ { start: '1:00 AM', name: '🍿 Late Night Snack' }, { start: '8:00 AM', name: '🍳 Breakfast' }, { start: '9:30 AM', name: '🛑 Hacking Ends' }, { start: '10:00 AM', name: '📔 Expo Begins' }, { start: '11:30 AM', name: '🍞 Lunch' }, { start: '1:00 PM', name: '🎭 Closing Ceremonies' }, { start: '2:30 PM', name: '🚌 Buses Depart' } ]; const ScheduleDay = ({ dayData, title }) => ( <Card className="p-schedule__day"> <h3 className="text-center">{title}</h3> {dayData.map(item => ( <div className="p-schedule__item" key={item.name + item.start}> <div className="p-schedule__item_about"> <span className="p-schedule__item_time">{item.start}</span> <span className="p-schedule__item_title">{item.name}</span> </div> <div className="p-schedule__item_info">{item.info}</div> </div> ))} </Card> ); const Schedule = ({ small }) => ( <div className="p-schedule"> {small ? <h3 style={{ marginTop: 0 }}>Schedule</h3> : <h1>Schedule</h1>} <div className="p-schedule__days"> <ScheduleDay dayData={friday} title="Friday (10/19)" /> <ScheduleDay dayData={saturday} title="Saturday (10/20)" /> <ScheduleDay dayData={sunday} title="Sunday (10/21)" /> </div> </div> ); export default Schedule;
BoilerMake/frontend
src/components/Schedule/index.js
JavaScript
agpl-3.0
2,859
window.addEventListener("DOMContentLoaded", () => { let watchers = {}; new DOM('@Dialog').forEach((dialog) => { dialogPolyfill.registerDialog(dialog); if (dialog.querySelector('Button[Data-Action="Dialog_Submit"]')) { dialog.addEventListener("keydown", (event) => { if (event.ctrlKey && event.keyCode == 13) dialog.querySelector('Button[Data-Action="Dialog_Submit"]').click(); }); } dialog.querySelectorAll('Dialog *[Required]').forEach((input) => { input.addEventListener("input", () => { let result = true; dialog.querySelectorAll('Dialog *[Required]').forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); if (result) { dialog.querySelector('Button[Data-Action="Dialog_Submit"]').classList.remove("mdl-button--disabled"); } else { dialog.querySelector('Button[Data-Action="Dialog_Submit"]').classList.add("mdl-button--disabled"); } }); }); dialog.querySelectorAll('Dialog Button[Data-Action="Dialog_Close"]').forEach((btn) => { btn.addEventListener("click", () => { btn.offsetParent.close(); }); }); }); new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").addEventListener("input", () => { if (new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").value == base.user.email) { new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").classList.remove("mdl-button--disabled"); } else { new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").classList.add("mdl-button--disabled"); } }); new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").addEventListener("click", (event) => { if (new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").value == base.user.email) { base.delete(); } else { new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email").classList.add("is-invalid"); } }); watchers["Dialogs_Profile_InfoViewer_UID"] = { valueObj: { value: "" }, watcher: null }; watchers["Dialogs_Profile_InfoViewer_UID"].watcher = new DOM.Watcher({ target: watchers["Dialogs_Profile_InfoViewer_UID"].valueObj, onGet: () => { watchers["Dialogs_Profile_InfoViewer_UID"].valueObj.value = new DOM("#Dialogs_Profile_InfoViewer_UID").value }, onChange: (watcher) => { base.Database.get(base.Database.ONCE, `users/${watcher.newValue}`, (res) => { new DOM("#Dialogs_Profile_InfoViewer_Content_Photo").dataset.uid = watcher.newValue, new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Name").textContent = res.userName, new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Detail").textContent = res.detail; while (new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").childNodes.length > 0) new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").childNodes[0].remove(); if (res.links) { for (let i = 0; i < res.links.length; i++) { let link = new Component.Dialogs.Profile.InfoViewer.Links.Link(res.links[i].name, res.links[i].url); new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").appendChild(link); } } }); } }); new DOM("#Dialogs_Thread_DeleteConfirmer_Btns_Yes").addEventListener("click", () => { base.Database.delete(`threads/${new DOM("#Dialogs_Thread_DeleteConfirmer_TID").value}/`); parent.document.querySelector("IFrame.mdl-layout__content").contentWindow.postMessage({ code: "Code-Refresh" }, "*"); new DOM("#Dialogs_Thread_EditNotify").showModal(); }); new DOM("@#Dialogs_Thread_InfoInputter *[Required]").forEach((input) => { input.addEventListener("input", () => { let result = true; let list = [ new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input") ]; if (new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked) list.push(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input")); list.forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); if (result) { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.remove("mdl-button--disabled"); }); } else { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.add("mdl-button--disabled"); }); } }); }); new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").addEventListener("change", (event) => { let result = true; switch (event.target.checked) { case true: new DOM("#Dialogs_Thread_InfoInputter_Content_Password").classList.remove("mdl-switch__child-hide"); [new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input")].forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); break; case false: new DOM("#Dialogs_Thread_InfoInputter_Content_Password").classList.add("mdl-switch__child-hide"); [new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input")].forEach(requiredField => { if (requiredField.value.replace(/\s/g, "").length == 0) { result = false; return; } }); break; } if (result) { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.remove("mdl-button--disabled"); }); } else { new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => { btn.classList.add("mdl-button--disabled"); }); } }); new DOM("#Dialogs_Thread_InfoInputter_Btns_Create").addEventListener("click", (event) => { base.Database.transaction("threads", (res) => { let now = new Date().getTime(); base.Database.set("threads/" + res.length, { title: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value, overview: new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input").value, detail: new DOM("#Dialogs_Thread_InfoInputter_Content_Detail-Input").value, jobs: { Owner: (() => { let owner = {}; owner[base.user.uid] = ""; return owner; })(), Admin: { } }, createdAt: now, data: [ { uid: "!SYSTEM_INFO", content: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value, createdAt: now } ], password: new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked ? Encrypter.encrypt(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input").value) : "" }); new DOM("#Dialogs_Thread_InfoInputter").close(); parent.document.querySelector("IFrame.mdl-layout__content").src = "Thread/Viewer/?tid=" + res.length; }); }); new DOM("#Dialogs_Thread_InfoInputter_Btns_Edit").addEventListener("click", (event) => { base.Database.update(`threads/${new DOM("#Dialogs_Thread_InfoInputter_TID").value}/`, { title: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value, overview: new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input").value, detail: new DOM("#Dialogs_Thread_InfoInputter_Content_Detail-Input").value, password: new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked ? Encrypter.encrypt(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input").value) : "" }); new DOM("#Dialogs_Thread_InfoInputter").close(); new DOM("#Dialogs_Thread_EditNotify").showModal(); }); new DOM("#Dialogs_Thread_PasswordConfirmer_Btns_OK").addEventListener("click", (event) => { if (Encrypter.encrypt(new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password-Input").value) == new DOM("#Dialogs_Thread_PasswordConfirmer_Password").value) { sessionStorage.setItem("com.GenbuProject.SimpleThread.currentPassword", new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password-Input").value); new DOM("$IFrame.mdl-layout__content").src = new DOM("#Dialogs_Thread_PasswordConfirmer_Link").value; new DOM("#Dialogs_Thread_PasswordConfirmer_Link").value = "", new DOM("#Dialogs_Thread_PasswordConfirmer_Password").value = ""; } else { new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password").classList.add("is-invalid"); } }); new DOM("#Dialogs_Thread_PasswordConfirmer_Btns_Cancel").addEventListener("click", (event) => { new DOM("$IFrame.mdl-layout__content").src = "/SimpleThread/Thread/"; }); watchers["Dialogs_Thread_InfoViewer_TID"] = { valueObj: { value: "0" }, watcher: null }; watchers["Dialogs_Thread_InfoViewer_TID"].watcher = new DOM.Watcher({ target: watchers["Dialogs_Thread_InfoViewer_TID"].valueObj, onGet: () => { watchers["Dialogs_Thread_InfoViewer_TID"].valueObj.value = new DOM("#Dialogs_Thread_InfoViewer_TID").value }, onChange: (watcher) => { base.Database.get(base.Database.ONCE, `threads/${watcher.newValue}`, (res) => { new DOM("#Dialogs_Thread_InfoViewer_Content_Name").textContent = res.title, new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").textContent = res.overview, new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").textContent = res.detail; URL.filter(new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").textContent).forEach((urlString) => { new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").innerHTML = new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").innerHTML.replace(urlString, `<A Href = "${urlString}" Target = "_blank">${urlString}</A>`); }); URL.filter(new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").textContent).forEach((urlString) => { new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").innerHTML = new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").innerHTML.replace(urlString, `<A Href = "${urlString}" Target = "_blank">${urlString}</A>`); }); }); } }); new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedLink").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster_LinkEmbedder").showModal(); }); new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedImage").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster").close(); let picker = new Picker.PhotoPicker(data => { console.log(data); switch (data[google.picker.Response.ACTION]) { case google.picker.Action.CANCEL: case google.picker.Action.PICKED: new DOM("#Dialogs_Thread_Poster").showModal(); break; } }); picker.show(); }); new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedFile").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster").close(); let picker = new Picker.FilePicker(data => { console.log(data); switch (data[google.picker.Response.ACTION]) { case google.picker.Action.CANCEL: case google.picker.Action.PICKED: new DOM("#Dialogs_Thread_Poster").showModal(); break; } }); picker.show(); }); new DOM("#Dialogs_Thread_Poster_Content_Text-Input").addEventListener("keydown", (event) => { let inputter = event.target; let selectionStart = inputter.selectionStart, selectionEnd = inputter.selectionEnd; switch (event.keyCode) { case 9: event.preventDefault(); inputter.value = `${inputter.value.slice(0, selectionStart)}\t${inputter.value.slice(selectionEnd)}`; inputter.setSelectionRange(selectionStart + 1, selectionStart + 1); new DOM("#Dialogs_Thread_Poster_Content_Text").classList.add("is-dirty"); break; } }); new DOM("#Dialogs_Thread_Poster_Btns_OK").addEventListener("click", (event) => { base.Database.transaction("threads/" + new DOM("#Dialogs_Thread_Poster_TID").value + "/data", (res) => { base.Database.set("threads/" + new DOM("#Dialogs_Thread_Poster_TID").value + "/data/" + res.length, { uid: base.user.uid, content: new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value, createdAt: new Date().getTime() }); new DOM("#Dialogs_Thread_Poster_Btns_OK").classList.add("mdl-button--disabled"), new DOM("#Dialogs_Thread_Poster_Content_Text").classList.remove("is-dirty"), new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value = ""; new DOM("#Page").contentDocument.querySelector("#FlowPanel_Btns_CreatePost").removeAttribute("Disabled"); new DOM("#Dialogs_Thread_Poster").close(); }); }); new DOM("#Dialogs_Thread_Poster_Btns_Cancel").addEventListener("click", () => { new DOM("#Dialogs_Thread_Poster_Btns_OK").classList.add("mdl-button--disabled"), new DOM("#Dialogs_Thread_Poster_Content_Text").classList.remove("is-dirty"), new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value = ""; new DOM("#Page").contentDocument.querySelector("#FlowPanel_Btns_CreatePost").removeAttribute("Disabled"); }); for (let watcherName in watchers) DOM.Watcher.addWatcher(watchers[watcherName].watcher); });
GenbuProject/SimpleThread
Dialog.js
JavaScript
agpl-3.0
13,060
# -*- encoding: utf-8 -*- from . import res_partner_bank from . import account_bank_statement_import
StefanRijnhart/bank-statement-import
account_bank_statement_import/__init__.py
Python
agpl-3.0
102
import {login, signup} from '../../src/app/actions/authActions'; import ActionsConstants from '../../src/common/constants/actionsConstants'; describe('auth actions', () => { describe('if we create a login action', () => { let userId = 'TestUser'; it('should generate action with payload', () => { expect(login(userId)).toEqual({ type: ActionsConstants.Login, payload: userId }); }); }); describe('if we create a login action without a userId', () => { const error = new TypeError('not a string'); it('should fail', () => { expect(login(error)).toEqual({ type: ActionsConstants.Login, payload: error, error: true }); }); }); describe('if we create a signup action', () => { it('should generate action with payload', () => { expect(signup()).toEqual({ type: ActionsConstants.SignUp }); }); }); });
bernatmv/thegame
client/__tests__/actions/authActions.spec.ts
TypeScript
agpl-3.0
1,057
""" Tests course_creators.admin.py. """ from django.test import TestCase from django.contrib.auth.models import User from django.contrib.admin.sites import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator from django.core import mail from student.roles import CourseCreatorRole from student import auth def mock_render_to_string(template_name, context): """Return a string that encodes template_name and context""" return str((template_name, context)) class CourseCreatorAdminTest(TestCase): """ Tests for course creator admin. """ def setUp(self): """ Test case setup """ super(CourseCreatorAdminTest, self).setUp() self.user = User.objects.create_user('test_user', 'test_user+courses@edx.org', 'foo') self.table_entry = CourseCreator(user=self.user) self.table_entry.save() self.admin = User.objects.create_user('Mark', 'admin+courses@edx.org', 'foo') self.admin.is_staff = True self.request = HttpRequest() self.request.user = self.admin self.creator_admin = CourseCreatorAdmin(self.table_entry, AdminSite()) self.studio_request_email = 'mark@marky.mark' self.enable_creator_group_patch = { "ENABLE_CREATOR_GROUP": True, "STUDIO_REQUEST_EMAIL": self.studio_request_email } @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) @mock.patch('django.contrib.auth.models.User.email_user') def test_change_status(self, email_user): """ Tests that updates to state impact the creator group maintained in authz.py and that e-mails are sent. """ def change_state_and_verify_email(state, is_creator): """ Changes user state, verifies creator status, and verifies e-mail is sent based on transition """ self._change_state(state) self.assertEqual(is_creator, auth.user_has_role(self.user, CourseCreatorRole())) context = {'studio_request_email': self.studio_request_email} if state == CourseCreator.GRANTED: template = 'emails/course_creator_granted.txt' elif state == CourseCreator.DENIED: template = 'emails/course_creator_denied.txt' else: template = 'emails/course_creator_revoked.txt' email_user.assert_called_with( mock_render_to_string('emails/course_creator_subject.txt', context), mock_render_to_string(template, context), self.studio_request_email ) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # User is initially unrequested. self.assertFalse(auth.user_has_role(self.user, CourseCreatorRole())) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.DENIED, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.PENDING, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.UNREQUESTED, False) change_state_and_verify_email(CourseCreator.DENIED, False) @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) def test_mail_admin_on_pending(self): """ Tests that the admin account is notified when a user is in the 'pending' state. """ def check_admin_message_state(state, expect_sent_to_admin, expect_sent_to_user): """ Changes user state and verifies e-mail sent to admin address only when pending. """ mail.outbox = [] self._change_state(state) # If a message is sent to the user about course creator status change, it will be the first # message sent. Admin message will follow. base_num_emails = 1 if expect_sent_to_user else 0 if expect_sent_to_admin: context = {'user_name': "test_user", 'user_email': u'test_user+courses@edx.org'} self.assertEquals(base_num_emails + 1, len(mail.outbox), 'Expected admin message to be sent') sent_mail = mail.outbox[base_num_emails] self.assertEquals( mock_render_to_string('emails/course_creator_admin_subject.txt', context), sent_mail.subject ) self.assertEquals( mock_render_to_string('emails/course_creator_admin_user_pending.txt', context), sent_mail.body ) self.assertEquals(self.studio_request_email, sent_mail.from_email) self.assertEqual([self.studio_request_email], sent_mail.to) else: self.assertEquals(base_num_emails, len(mail.outbox)) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # E-mail message should be sent to admin only when new state is PENDING, regardless of what # previous state was (unless previous state was already PENDING). # E-mail message sent to user only on transition into and out of GRANTED state. check_admin_message_state(CourseCreator.UNREQUESTED, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=False) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) def _change_state(self, state): """ Helper method for changing state """ self.table_entry.state = state self.creator_admin.save_model(self.request, self.table_entry, None, True) def test_add_permission(self): """ Tests that staff cannot add entries """ self.assertFalse(self.creator_admin.has_add_permission(self.request)) def test_delete_permission(self): """ Tests that staff cannot delete entries """ self.assertFalse(self.creator_admin.has_delete_permission(self.request)) def test_change_permission(self): """ Tests that only staff can change entries """ self.assertTrue(self.creator_admin.has_change_permission(self.request)) self.request.user = self.user self.assertFalse(self.creator_admin.has_change_permission(self.request))
nttks/edx-platform
cms/djangoapps/course_creators/tests/test_admin.py
Python
agpl-3.0
7,332
<?php $mod_strings = array_merge($mod_strings, array( 'LBL_LIST_NONINHERITABLE' => "Não Herdável", ) ); ?>
yonkon/nedvig
custom/Extension/modules/Users/Ext/Language/pt_br.SecurityGroups.php
PHP
agpl-3.0
115
<?php /** * Validation. * * @author Fabio Alessandro Locati <fabiolocati@gmail.com> * @author Wenzel Pünter <wenzel@phelix.me> * @author Daniel Mejta <daniel@mejta.net> * * @version 2.0.0 */ namespace Isbn; /** * Validation. */ class Validation { /** * Check Instance. * * @var Check */ private $check; /** * Hyphens Instance. * * @var Hyphens */ private $hyphens; /** * Constructor. * * @param Check $check * @param Hyphens $hyphens */ public function __construct(Check $check, Hyphens $hyphens) { $this->check = $check; $this->hyphens = $hyphens; } /** * Validate the ISBN $isbn. * * @param string $isbn * * @return bool */ public function isbn($isbn) { if ($this->check->is13($isbn)) { return $this->isbn13($isbn); } if ($this->check->is10($isbn)) { return $this->isbn10($isbn); } return false; } /** * Validate the ISBN-10 $isbn. * * @param string $isbn * * @throws Exception * * @return bool */ public function isbn10($isbn) { if (\is_string($isbn) === false) { throw new Exception('Invalid parameter type.'); } //Verify ISBN-10 scheme $isbn = $this->hyphens->removeHyphens($isbn); if (\strlen($isbn) != 10) { return false; } if (\preg_match('/\d{9}[0-9xX]/i', $isbn) == false) { return false; } //Verify checksum $check = 0; for ($i = 0; $i < 10; $i++) { if (\strtoupper($isbn[$i]) === 'X') { $check += 10 * \intval(10 - $i); } else { $check += \intval($isbn[$i]) * \intval(10 - $i); } } return $check % 11 === 0; } /** * Validate the ISBN-13 $isbn. * * @param string $isbn * * @throws Exception * * @return bool */ public function isbn13($isbn) { if (\is_string($isbn) === false) { throw new Exception('Invalid parameter type.'); } //Verify ISBN-13 scheme $isbn = $this->hyphens->removeHyphens($isbn); if (\strlen($isbn) != 13) { return false; } if (\preg_match('/\d{13}/i', $isbn) == false) { return false; } //Verify checksum $check = 0; for ($i = 0; $i < 13; $i += 2) { $check += \substr($isbn, $i, 1); } for ($i = 1; $i < 12; $i += 2) { $check += 3 * \substr($isbn, $i, 1); } return $check % 10 === 0; } }
Fale/isbn
src/Isbn/Validation.php
PHP
agpl-3.0
2,769
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.beans.admin; import java.util.ArrayList; import java.util.List; import com.silverpeas.scheduler.Scheduler; import com.silverpeas.scheduler.SchedulerEvent; import com.silverpeas.scheduler.SchedulerEventListener; import com.silverpeas.scheduler.SchedulerFactory; import com.silverpeas.scheduler.trigger.JobTrigger; import com.stratelia.silverpeas.silvertrace.SilverTrace; public class SynchroDomainScheduler implements SchedulerEventListener { public static final String ADMINSYNCHRODOMAIN_JOB_NAME = "AdminSynchroDomainJob"; private List<String> domainIds = null; public void initialize(String cron, List<String> domainIds) { try { this.domainIds = domainIds; SchedulerFactory schedulerFactory = SchedulerFactory.getFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.unscheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME); JobTrigger trigger = JobTrigger.triggerAt(cron); scheduler.scheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME, trigger, this); } catch (Exception e) { SilverTrace.error("admin", "SynchroDomainScheduler.initialize()", "admin.CANT_INIT_DOMAINS_SYNCHRO", e); } } public void addDomain(String id) { if (domainIds == null) { domainIds = new ArrayList<String>(); } domainIds.add(id); } public void removeDomain(String id) { if (domainIds != null) { domainIds.remove(id); } } public void doSynchro() { SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_ENTER_METHOD"); if (domainIds != null) { for (String domainId : domainIds) { try { AdminReference.getAdminService().synchronizeSilverpeasWithDomain(domainId, true); } catch (Exception e) { SilverTrace.error("admin", "SynchroDomainScheduler.doSynchro()", "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e); } } } SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void triggerFired(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.debug("admin", "SynchroDomainScheduler.triggerFired()", "The job '" + jobName + "' is executed"); doSynchro(); } @Override public void jobSucceeded(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.debug("admin", "SynchroDomainScheduler.jobSucceeded()", "The job '" + jobName + "' was successfull"); } @Override public void jobFailed(SchedulerEvent anEvent) { String jobName = anEvent.getJobExecutionContext().getJobName(); SilverTrace.error("admin", "SynchroDomainScheduler.jobFailed", "The job '" + jobName + "' was not successfull"); } }
stephaneperry/Silverpeas-Core
lib-core/src/main/java/com/stratelia/webactiv/beans/admin/SynchroDomainScheduler.java
Java
agpl-3.0
3,969
# frozen_string_literal: true require 'ffaker' FactoryBot.define do sequence(:random_string) { FFaker::Lorem.sentence } sequence(:random_description) { FFaker::Lorem.paragraphs(Kernel.rand(1..5)).join("\n") } sequence(:random_email) { FFaker::Internet.email } factory :classification, class: Spree::Classification do end factory :exchange, class: Exchange do incoming { false } order_cycle { OrderCycle.first || FactoryBot.create(:simple_order_cycle) } sender { incoming ? FactoryBot.create(:enterprise) : order_cycle.coordinator } receiver { incoming ? order_cycle.coordinator : FactoryBot.create(:enterprise) } end factory :schedule, class: Schedule do sequence(:name) { |n| "Schedule #{n}" } transient do order_cycles { [OrderCycle.first || create(:simple_order_cycle)] } end before(:create) do |schedule, evaluator| evaluator.order_cycles.each do |order_cycle| order_cycle.schedules << schedule end end end factory :proxy_order, class: ProxyOrder do subscription order_cycle { subscription.order_cycles.first } before(:create) do |proxy_order, _proxy| proxy_order.order&.update_attribute(:order_cycle_id, proxy_order.order_cycle_id) end end factory :variant_override, class: VariantOverride do price { 77.77 } on_demand { false } count_on_hand { 11_111 } default_stock { 2000 } resettable { false } trait :on_demand do on_demand { true } count_on_hand { nil } end trait :use_producer_stock_settings do on_demand { nil } count_on_hand { nil } end end factory :inventory_item, class: InventoryItem do enterprise variant visible { true } end factory :enterprise_relationship do end factory :enterprise_role do end factory :enterprise_group, class: EnterpriseGroup do name { 'Enterprise group' } sequence(:permalink) { |n| "group#{n}" } description { 'this is a group' } on_front_page { false } address { FactoryBot.build(:address) } end factory :enterprise_fee, class: EnterpriseFee do transient { amount { nil } } sequence(:name) { |n| "Enterprise fee #{n}" } sequence(:fee_type) { |n| EnterpriseFee::FEE_TYPES[n % EnterpriseFee::FEE_TYPES.count] } enterprise { Enterprise.first || FactoryBot.create(:supplier_enterprise) } calculator { build(:calculator_per_item, preferred_amount: amount) } after(:create) { |ef| ef.calculator.save! } trait :flat_rate do transient { amount { 1 } } calculator { build(:calculator_flat_rate, preferred_amount: amount) } end trait :per_item do transient { amount { 1 } } calculator { build(:calculator_per_item, preferred_amount: amount) } end end factory :adjustment_metadata, class: AdjustmentMetadata do adjustment { FactoryBot.create(:adjustment) } enterprise { FactoryBot.create(:distributor_enterprise) } fee_name { 'fee' } fee_type { 'packing' } enterprise_role { 'distributor' } end factory :producer_property, class: ProducerProperty do value { 'abc123' } producer { create(:supplier_enterprise) } property end factory :stripe_account do enterprise { FactoryBot.create(:distributor_enterprise) } stripe_user_id { "abc123" } stripe_publishable_key { "xyz456" } end end
openfoodfoundation/openfoodnetwork
spec/factories.rb
Ruby
agpl-3.0
3,400
module CC::Exporter::Epub module Exportable def content_cartridge self.attachment end def convert_to_epub(opts={}) exporter = CC::Exporter::Epub::Exporter.new(content_cartridge.open, opts[:sort_by_content]) epub = CC::Exporter::Epub::Book.new(exporter.templates) epub.create end end end
AndranikMarkosyan/lms
lib/cc/exporter/epub/exportable.rb
Ruby
agpl-3.0
332
from django.conf.urls.defaults import * import frontend.views as frontend_views import codewiki.views import codewiki.viewsuml from django.contrib.syndication.views import feed as feed_view from django.views.generic import date_based, list_detail from django.views.generic.simple import direct_to_template from django.contrib import admin import django.contrib.auth.views as auth_views from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.contrib import admin admin.autodiscover() # Need to move this somewhere more useful and try to make it less hacky but # seems to be the easiest way unfortunately. from django.contrib.auth.models import User User._meta.ordering = ['username'] from frontend.feeds import LatestCodeObjects, LatestCodeObjectsBySearchTerm, LatestCodeObjectsByTag, LatestViewObjects, LatestScraperObjects feeds = { 'all_code_objects': LatestCodeObjects, 'all_scrapers': LatestScraperObjects, 'all_views': LatestViewObjects, 'latest_code_objects_by_search_term': LatestCodeObjectsBySearchTerm, 'latest_code_objects_by_tag': LatestCodeObjectsByTag, } urlpatterns = patterns('', url(r'^$', frontend_views.frontpage, name="frontpage"), # redirects from old version (would clashes if you happen to have a scraper whose name is list!) (r'^scrapers/list/$', lambda request: HttpResponseRedirect(reverse('scraper_list_wiki_type', args=['scraper']))), url(r'^', include('codewiki.urls')), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name="logout"), url(r'^accounts/', include('registration.urls')), url(r'^accounts/resend_activation_email/', frontend_views.resend_activation_email, name="resend_activation_email"), url(r'^captcha/', include('captcha.urls')), url(r'^attachauth', codewiki.views.attachauth), # allows direct viewing of the django tables url(r'^admin/', include(admin.site.urls)), # favicon (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/media/images/favicon.ico'}), # RSS feeds url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds'), # API (r'^api/', include('api.urls', namespace='foo', app_name='api')), # Status url(r'^status/$', codewiki.viewsuml.status, name='status'), # Documentation (r'^docs/', include('documentation.urls')), # Robots.txt (r'^robots.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}), # pdf cropper technology (r'^cropper/', include('cropper.urls')), # froth (r'^froth/', include('froth.urls')), # static media server for the dev sites / local dev url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_DIR, 'show_indexes':True}), url(r'^media-admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ADMIN_DIR, 'show_indexes':True}), #Rest of the site url(r'^', include('frontend.urls')), # redirects from old version (r'^editor/$', lambda request: HttpResponseRedirect('/scrapers/new/python?template=tutorial_python_trivial')), (r'^scrapers/show/(?P<short_name>[\w_\-]+)/(?:data/|map-only/)?$', lambda request, short_name: HttpResponseRedirect(reverse('code_overview', args=['scraper', short_name]))), )
rossjones/ScraperWikiX
web/urls.py
Python
agpl-3.0
3,556
function timenow(){ var timenow1 = Date.getHours(); return timenow1; }
trynothingy/JQSchProj
assets/js/func.js
JavaScript
agpl-3.0
78
<!-- | FUNCTION show page to edit account --> <?php function $$$showEditAccount () { global $TSunic; // activate template $data = array('User' => $TSunic->Usr); $TSunic->Tmpl->activate('$$$showEditAccount', '$system$content', $data); $TSunic->Tmpl->activate('$system$html', false, array('title' => '{SHOWEDITACCOUNT__TITLE}')); return true; } ?>
nfrickler/tsunic
data/source/modules/usersystem/functions/showEditAccount.func.php
PHP
agpl-3.0
372
<?php //Harvie's PHP HTTP-Auth script (2oo7-2o1o) //CopyLefted4U ;) ///SETTINGS////////////////////////////////////////////////////////////////////////////////////////////////////// //Login /*$realm = 'music'; //This is used by browser to identify protected area and saving passwords (one_site+one_realm==one_user+one_password) $users = array( //You can specify multiple users in this array 'music' => 'passw' );*/ //Misc $require_login = true; //Require login? (if false, no login needed) - WARNING!!! $location = '401'; //Location after logout - 401 = default logout page (can be overridden by ?logout=[LOCATION]) //CopyLeft $ver = '2o1o-3.9'; $link = '<a href="https://blog.harvie.cz/">blog.harvie.cz</a>'; $banner = "Harvie's PHP HTTP-Auth script (v$ver)"; $hbanner = "<hr /><i>$banner\n-\n$link</i>\n"; $cbanner = "<!-- $banner -->\n"; //Config file @include('./_config.php'); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //MANUAL///////////////////////////////////////////////////////////////////////////////////////////////////////// /* HOWTO * To each file, you want to lock add this line (at begin of first line - Header-safe): * <?php require_once('http_auth.php'); ?> //Password Protection 8') * Protected file have to be php script (if it's html, simply rename it to .php) * Server needs to have PHP as module (not CGI). * You need HTTP Basic auth enabled on server and php. */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////CODE///////////////////////////////////////////////////////////////////////////////////////////////////////// function send_auth_headers($realm='') { Header('WWW-Authenticate: Basic realm="'.$realm.'"'); Header('HTTP/1.0 401 Unauthorized'); } function check_auth($PHP_AUTH_USER, $PHP_AUTH_PW) { //Check if login is succesfull (U can modify this to use DB, or anything else) return (isset($GLOBALS['users'][$PHP_AUTH_USER]) && ($GLOBALS['users'][$PHP_AUTH_USER] == $PHP_AUTH_PW)); } function unauth() { //Do this when login fails $cbanner = $GLOBALS['cbanner']; $hbanner = $GLOBALS['hbanner']; die("$cbanner<title>401 - Forbidden</title>\n<h1>401 - Forbidden</h1>\n<a href=\"?\">Login...</a>\n$hbanner"); //Show warning and die die(); //Don't forget!!! } //Backward compatibility if(isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_PW'] != '') $PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER']; if(isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] != '') $PHP_AUTH_PW = $_SERVER['PHP_AUTH_PW']; //Logout if(isset($_GET['logout'])) { //script.php?logout if(isset($PHP_AUTH_USER) || isset($PHP_AUTH_PW)) { Header('WWW-Authenticate: Basic realm="'.$realm.'"'); Header('HTTP/1.0 401 Unauthorized'); } else { if($_GET['logout'] != '') $location = $_GET['logout']; if(trim($location) != '401') Header('Location: '.$location); die("$cbanner<title>401 - Log out successfull</title>\n<h1>401 - Log out successfull</h1>\n<a href=\"?\">Continue...</a>\n$hbanner"); } } if($require_login) { if(!isset($PHP_AUTH_USER)) { //Storno or first visit of page send_auth_headers($realm); unauth(); } else { //Login sent if (check_auth($PHP_AUTH_USER, $PHP_AUTH_PW)) { //Login succesfull - probably do nothing } else { //Bad login send_auth_headers($realm); unauth(); } } } //Rest of file will be displayed only if login is correct
Kyberia/Kyberia-bloodline
wwwroot/inc/http_auth.php
PHP
agpl-3.0
3,525
#ifndef HIGHSCORE_HPP #define HIGHSCORE_HPP #include <cassert> #include <sstream> #include "framework.hpp" #include "./config.hpp" #include "./media.hpp" class Highscore { public: Highscore(); ~Highscore(); /* Load/Save */ void load(); void save(); /* Access particular difficulties */ util::Highscore &getHighscore(LEVEL_DIFFICULTY difficulty); /* Draw */ void draw(); private: /* Data */ util::Timer timer; util::Highscore highscore[LEVEL_DIFFICULTY_END]; double offset; int haltstart; int difficulty; bool shifting; struct { font::TtfLabel difficulty[LEVEL_DIFFICULTY_END]; font::TtfLabel place[3/*HIGHSCORE_PLACECOUNT*/]; font::TtfLabel score[LEVEL_DIFFICULTY_END][3/*HIGHSCORE_PLACECOUNT*/]; font::TtfLabel prescore[LEVEL_DIFFICULTY_END][3/*HIGHSCORE_PLACECOUNT*/]; }label; }; #endif // HIGHSCORE_HPP
mrzzzrm/shootet
src/Highscore.hpp
C++
lgpl-2.1
1,080
// CC0 Public Domain: http://creativecommons.org/publicdomain/zero/1.0/ #include "bsefilter.hh" #include <sfi/sfi.hh> using namespace Bse; const gchar* bse_iir_filter_kind_string (BseIIRFilterKind fkind) { switch (fkind) { case BSE_IIR_FILTER_BUTTERWORTH: return "Butterworth"; case BSE_IIR_FILTER_BESSEL: return "Bessel"; case BSE_IIR_FILTER_CHEBYSHEV1: return "Chebyshev1"; case BSE_IIR_FILTER_CHEBYSHEV2: return "Chebyshev2"; case BSE_IIR_FILTER_ELLIPTIC: return "Elliptic"; default: return "?unknown?"; } } const gchar* bse_iir_filter_type_string (BseIIRFilterType ftype) { switch (ftype) { case BSE_IIR_FILTER_LOW_PASS: return "Low-pass"; case BSE_IIR_FILTER_BAND_PASS: return "Band-pass"; case BSE_IIR_FILTER_HIGH_PASS: return "High-pass"; case BSE_IIR_FILTER_BAND_STOP: return "Band-stop"; default: return "?unknown?"; } } gchar* bse_iir_filter_request_string (const BseIIRFilterRequest *ifr) { String s; s += bse_iir_filter_kind_string (ifr->kind); s += " "; s += bse_iir_filter_type_string (ifr->type); s += " order=" + string_from_int (ifr->order); s += " sample-rate=" + string_from_float (ifr->sampling_frequency); if (ifr->kind == BSE_IIR_FILTER_CHEBYSHEV1 || ifr->kind == BSE_IIR_FILTER_ELLIPTIC) s += " passband-ripple-db=" + string_from_float (ifr->passband_ripple_db); s += " passband-edge=" + string_from_float (ifr->passband_edge); if (ifr->type == BSE_IIR_FILTER_BAND_PASS || ifr->type == BSE_IIR_FILTER_BAND_STOP) s += " passband-edge2=" + string_from_float (ifr->passband_edge2); if (ifr->kind == BSE_IIR_FILTER_ELLIPTIC && ifr->stopband_db < 0) s += " stopband-db=" + string_from_float (ifr->stopband_db); if (ifr->kind == BSE_IIR_FILTER_ELLIPTIC && ifr->stopband_edge > 0) s += " stopband-edge=" + string_from_float (ifr->stopband_edge); return g_strdup (s.c_str()); } gchar* bse_iir_filter_design_string (const BseIIRFilterDesign *fid) { String s; s += "order=" + string_from_int (fid->order); s += " sampling-frequency=" + string_from_float (fid->sampling_frequency); s += " center-frequency=" + string_from_float (fid->center_frequency); s += " gain=" + string_from_double (fid->gain); s += " n_zeros=" + string_from_int (fid->n_zeros); s += " n_poles=" + string_from_int (fid->n_poles); for (uint i = 0; i < fid->n_zeros; i++) { String u ("Zero:"); u += " " + string_from_double (fid->zz[i].re); u += " + " + string_from_double (fid->zz[i].im) + "*i"; s += "\n" + u; } for (uint i = 0; i < fid->n_poles; i++) { String u ("Pole:"); u += " " + string_from_double (fid->zp[i].re); u += " + " + string_from_double (fid->zp[i].im) + "*i"; s += "\n" + u; } String u; #if 0 uint o = fid->order; u = string_from_double (fid->zn[o]); while (o--) u = "(" + u + ") * z + " + string_from_double (fid->zn[o]); s += "\nNominator: " + u; o = fid->order; u = string_from_double (fid->zd[o]); while (o--) u = "(" + u + ") * z + " + string_from_double (fid->zd[o]); s += "\nDenominator: " + u; #endif return g_strdup (s.c_str()); } bool bse_iir_filter_design (const BseIIRFilterRequest *filter_request, BseIIRFilterDesign *filter_design) { if (filter_request->kind == BSE_IIR_FILTER_BUTTERWORTH || filter_request->kind == BSE_IIR_FILTER_CHEBYSHEV1 || filter_request->kind == BSE_IIR_FILTER_ELLIPTIC) return _bse_filter_design_ellf (filter_request, filter_design); return false; }
GNOME/beast
bse/bsefilter.cc
C++
lgpl-2.1
3,662
#include <stdio.h> #include <QtDebug> #include "cguitreedomdocument.h" CGuiTreeDomDocument::CGuiTreeDomDocument() { QDomImplementation impl; impl.setInvalidDataPolicy(QDomImplementation::ReturnNullNode); } /** * Get first "guiObject" located in "guiRoot". * * @return Node element of first guiObject or an empty element node if there is none. **/ CGuiTreeDomElement CGuiTreeDomDocument::getFirstGuiObjectElement() { CGuiTreeDomElement domElmGuiTree; domElmGuiTree = this->firstChildElement("guiRoot"); if(domElmGuiTree.isNull()) return(domElmGuiTree); return(domElmGuiTree.firstChildElement("guiObject")); }
stevedorries/DFM2QT4UI
cguitreedomdocument.cpp
C++
lgpl-2.1
651
/* * Copyright 2005-2006 UniVis Explorer development team. * * This file is part of UniVis Explorer * (http://phobos22.inf.uni-konstanz.de/univis). * * UniVis Explorer is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * Please see COPYING for the complete licence. */ package unikn.dbis.univis.message; /** * TODO: document me!!! * <p/> * <code>Internationalizable+</code>. * <p/> * User: raedler, weiler * Date: 18.05.2006 * Time: 01:39:22 * * @author Roman R&auml;dle * @author Andreas Weiler * @version $Id: Internationalizable.java 338 2006-10-08 23:11:30Z raedler $ * @since UniVis Explorer 0.1 */ public interface Internationalizable { public void internationalize(); }
raedle/univis
src/java/unikn/dbis/univis/message/Internationalizable.java
Java
lgpl-2.1
899
package soot.jimple.toolkits.callgraph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import soot.AnySubType; import soot.ArrayType; import soot.FastHierarchy; import soot.G; import soot.NullType; import soot.PhaseOptions; import soot.RefType; import soot.Scene; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.jimple.SpecialInvokeExpr; import soot.options.CGOptions; import soot.toolkits.scalar.Pair; import soot.util.Chain; import soot.util.HashMultiMap; import soot.util.LargeNumberedMap; import soot.util.MultiMap; import soot.util.NumberedString; import soot.util.SmallNumberedMap; import soot.util.queue.ChunkedQueue; /** * Resolves virtual calls. * * @author Ondrej Lhotak */ public class VirtualCalls { private CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")); public VirtualCalls(Singletons.Global g) { } public static VirtualCalls v() { return G.v().soot_jimple_toolkits_callgraph_VirtualCalls(); } private final LargeNumberedMap<Type, SmallNumberedMap<SootMethod>> typeToVtbl = new LargeNumberedMap<Type, SmallNumberedMap<SootMethod>>(Scene.v().getTypeNumberer()); public SootMethod resolveSpecial(SpecialInvokeExpr iie, NumberedString subSig, SootMethod container) { return resolveSpecial(iie, subSig, container, false); } public SootMethod resolveSpecial(SpecialInvokeExpr iie, NumberedString subSig, SootMethod container, boolean appOnly) { SootMethod target = iie.getMethod(); /* cf. JVM spec, invokespecial instruction */ if (Scene.v().getOrMakeFastHierarchy().canStoreType(container.getDeclaringClass().getType(), target.getDeclaringClass().getType()) && container.getDeclaringClass().getType() != target.getDeclaringClass().getType() && !target.getName().equals("<init>") && subSig != sigClinit) { return resolveNonSpecial(container.getDeclaringClass().getSuperclass().getType(), subSig, appOnly); } else { return target; } } public SootMethod resolveNonSpecial(RefType t, NumberedString subSig) { return resolveNonSpecial(t, subSig, false); } public SootMethod resolveNonSpecial(RefType t, NumberedString subSig, boolean appOnly) { SmallNumberedMap<SootMethod> vtbl = typeToVtbl.get(t); if (vtbl == null) { typeToVtbl.put(t, vtbl = new SmallNumberedMap<SootMethod>()); } SootMethod ret = vtbl.get(subSig); if (ret != null) { return ret; } SootClass cls = t.getSootClass(); if (appOnly && cls.isLibraryClass()) { return null; } SootMethod m = cls.getMethodUnsafe(subSig); if (m != null) { if (!m.isAbstract()) { ret = m; } } else { SootClass c = cls.getSuperclassUnsafe(); if (c != null) { ret = resolveNonSpecial(c.getType(), subSig); } } vtbl.put(subSig, ret); return ret; } protected MultiMap<Type, Type> baseToSubTypes = new HashMultiMap<Type, Type>(); protected MultiMap<Pair<Type, NumberedString>, Pair<Type, NumberedString>> baseToPossibleSubTypes = new HashMultiMap<Pair<Type, NumberedString>, Pair<Type, NumberedString>>(); public void resolve(Type t, Type declaredType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets) { resolve(t, declaredType, null, subSig, container, targets); } public void resolve(Type t, Type declaredType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets, boolean appOnly) { resolve(t, declaredType, null, subSig, container, targets, appOnly); } public void resolve(Type t, Type declaredType, Type sigType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets) { resolve(t, declaredType, sigType, subSig, container, targets, false); } public void resolve(Type t, Type declaredType, Type sigType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets, boolean appOnly) { if (declaredType instanceof ArrayType) { declaredType = RefType.v("java.lang.Object"); } if (sigType instanceof ArrayType) { sigType = RefType.v("java.lang.Object"); } if (t instanceof ArrayType) { t = RefType.v("java.lang.Object"); } FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy(); if (declaredType != null && !fastHierachy.canStoreType(t, declaredType)) { return; } if (sigType != null && !fastHierachy.canStoreType(t, sigType)) { return; } if (t instanceof RefType) { SootMethod target = resolveNonSpecial((RefType) t, subSig, appOnly); if (target != null) { targets.add(target); } } else if (t instanceof AnySubType) { RefType base = ((AnySubType) t).getBase(); /* * Whenever any sub type of a specific type is considered as receiver for a method to call and the base type is an * interface, calls to existing methods with matching signature (possible implementation of method to call) are also * added. As Javas' subtyping allows contra-variance for return types and co-variance for parameters when overriding a * method, these cases are also considered here. * * Example: Classes A, B (B sub type of A), interface I with method public A foo(B b); and a class C with method public * B foo(A a) { ... }. The extended class hierarchy will contain C as possible implementation of I. * * Since Java has no multiple inheritance call by signature resolution is only activated if the base is an interface. */ if (options.library() == CGOptions.library_signature_resolution && base.getSootClass().isInterface()) { resolveLibrarySignature(declaredType, sigType, subSig, container, targets, appOnly, base); } else { resolveAnySubType(declaredType, sigType, subSig, container, targets, appOnly, base); } } else if (t instanceof NullType) { } else { throw new RuntimeException("oops " + t); } } public void resolveSuperType(Type t, Type declaredType, NumberedString subSig, ChunkedQueue<SootMethod> targets, boolean appOnly) { if (declaredType == null) { return; } if (t == null) { return; } if (declaredType instanceof ArrayType) { declaredType = RefType.v("java.lang.Object"); } if (t instanceof ArrayType) { t = RefType.v("java.lang.Object"); } if (declaredType instanceof RefType) { RefType parent = (RefType)declaredType; SootClass parentClass = parent.getSootClass(); RefType child; SootClass childClass; if (t instanceof AnySubType) { child = ((AnySubType) t).getBase(); } else if (t instanceof RefType) { child = (RefType)t; } else { return; } childClass = child.getSootClass(); FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy(); if (fastHierachy.canStoreClass(childClass,parentClass)) { SootMethod target = resolveNonSpecial(child, subSig, appOnly); if (target != null) { targets.add(target); } } } } protected void resolveAnySubType(Type declaredType, Type sigType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets, boolean appOnly, RefType base) { FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy(); { Set<Type> subTypes = baseToSubTypes.get(base); if (subTypes != null && !subTypes.isEmpty()) { for (final Type st : subTypes) { resolve(st, declaredType, sigType, subSig, container, targets, appOnly); } return; } } Set<Type> newSubTypes = new HashSet<>(); newSubTypes.add(base); LinkedList<SootClass> worklist = new LinkedList<SootClass>(); HashSet<SootClass> workset = new HashSet<SootClass>(); FastHierarchy fh = fastHierachy; SootClass cl = base.getSootClass(); if (workset.add(cl)) { worklist.add(cl); } while (!worklist.isEmpty()) { cl = worklist.removeFirst(); if (cl.isInterface()) { for (Iterator<SootClass> cIt = fh.getAllImplementersOfInterface(cl).iterator(); cIt.hasNext();) { final SootClass c = cIt.next(); if (workset.add(c)) { worklist.add(c); } } } else { if (cl.isConcrete()) { resolve(cl.getType(), declaredType, sigType, subSig, container, targets, appOnly); newSubTypes.add(cl.getType()); } for (Iterator<SootClass> cIt = fh.getSubclassesOf(cl).iterator(); cIt.hasNext();) { final SootClass c = cIt.next(); if (workset.add(c)) { worklist.add(c); } } } } baseToSubTypes.putAll(base, newSubTypes); } protected void resolveLibrarySignature(Type declaredType, Type sigType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets, boolean appOnly, RefType base) { FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy(); assert (declaredType instanceof RefType); Pair<Type, NumberedString> pair = new Pair<Type, NumberedString>(base, subSig); { Set<Pair<Type, NumberedString>> types = baseToPossibleSubTypes.get(pair); // if this type and method has been resolved earlier we can // just retrieve the previous result. if (types != null) { for (Pair<Type, NumberedString> tuple : types) { Type st = tuple.getO1(); if (!fastHierachy.canStoreType(st, declaredType)) { resolve(st, st, sigType, subSig, container, targets, appOnly); } else { resolve(st, declaredType, sigType, subSig, container, targets, appOnly); } } return; } } Set<Pair<Type, NumberedString>> types = new HashSet<Pair<Type, NumberedString>>(); // get return type; method name; parameter types String[] split = subSig.getString().replaceAll("(.*) (.*)\\((.*)\\)", "$1;$2;$3").split(";"); Type declaredReturnType = Scene.v().getType(split[0]); String declaredName = split[1]; List<Type> declaredParamTypes = new ArrayList<Type>(); // separate the parameter types if (split.length == 3) { for (String type : split[2].split(",")) { declaredParamTypes.add(Scene.v().getType(type)); } } Chain<SootClass> classes = Scene.v().getClasses(); for (SootClass sc : classes) { for (SootMethod sm : sc.getMethods()) { if (!sm.isAbstract()) { // method name has to match if (!sm.getName().equals(declaredName)) { continue; } // the return type has to be a the declared return // type or a sub type of it if (!fastHierachy.canStoreType(sm.getReturnType(), declaredReturnType)) { continue; } List<Type> paramTypes = sm.getParameterTypes(); // method parameters have to match to the declared // ones (same type or super type). if (declaredParamTypes.size() != paramTypes.size()) { continue; } boolean check = true; for (int i = 0; i < paramTypes.size(); i++) { if (!fastHierachy.canStoreType(declaredParamTypes.get(i), paramTypes.get(i))) { check = false; break; } } if (check) { Type st = sc.getType(); if (!fastHierachy.canStoreType(st, declaredType)) { // final classes can not be extended and // therefore not used in library client if (!sc.isFinal()) { NumberedString newSubSig = sm.getNumberedSubSignature(); resolve(st, st, sigType, newSubSig, container, targets, appOnly); types.add(new Pair<Type, NumberedString>(st, newSubSig)); } } else { resolve(st, declaredType, sigType, subSig, container, targets, appOnly); types.add(new Pair<Type, NumberedString>(st, subSig)); } } } } } baseToPossibleSubTypes.putAll(pair, types); } public final NumberedString sigClinit = Scene.v().getSubSigNumberer().findOrAdd("void <clinit>()"); public final NumberedString sigStart = Scene.v().getSubSigNumberer().findOrAdd("void start()"); public final NumberedString sigRun = Scene.v().getSubSigNumberer().findOrAdd("void run()"); }
plast-lab/soot
src/main/java/soot/jimple/toolkits/callgraph/VirtualCalls.java
Java
lgpl-2.1
13,477
/* Copyright (C) 2000-2001 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csqsqrt.h" #include "csgeom/box.h" #include "csgeom/math.h" #include "csgeom/math3d.h" #include "csgeom/math2d.h" #include "csgeom/transfrm.h" #include "csgfx/renderbuffer.h" #include "cstool/rbuflock.h" #include "cstool/rviewclipper.h" #include "csutil/scfarray.h" #include "ivaria/reporter.h" #include "iengine/movable.h" #include "iengine/rview.h" #include "ivideo/graph3d.h" #include "ivideo/graph2d.h" #include "ivideo/material.h" #include "ivideo/rendermesh.h" #include "iengine/material.h" #include "iengine/camera.h" #include "igeom/clip2d.h" #include "iengine/engine.h" #include "iengine/light.h" #include "iutil/objreg.h" #include "spr2d.h" CS_PLUGIN_NAMESPACE_BEGIN(Spr2D) { CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObject); CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObject::RenderBufferAccessor); CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObjectFactory); csSprite2DMeshObject::csSprite2DMeshObject (csSprite2DMeshObjectFactory* factory) : scfImplementationType (this), uvani (0), vertices_dirty (true), texels_dirty (true), colors_dirty (true), indicesSize ((size_t)-1), logparent (0), factory (factory), initialized (false), current_lod (1), current_features (0) { ifactory = scfQueryInterface<iMeshObjectFactory> (factory); material = factory->GetMaterialWrapper (); lighting = factory->HasLighting (); MixMode = factory->GetMixMode (); } csSprite2DMeshObject::~csSprite2DMeshObject () { delete uvani; } iColoredVertices* csSprite2DMeshObject::GetVertices () { if (!scfVertices.IsValid()) return factory->GetVertices (); return scfVertices; } csColoredVertices* csSprite2DMeshObject::GetCsVertices () { if (!scfVertices.IsValid()) return factory->GetCsVertices (); return &vertices; } void csSprite2DMeshObject::SetupObject () { if (!initialized) { initialized = true; float max_sq_dist = 0; size_t i; csColoredVertices* vertices = GetCsVertices (); bbox_2d.StartBoundingBox((*vertices)[0].pos); for (i = 0 ; i < vertices->GetSize () ; i++) { csSprite2DVertex& v = (*vertices)[i]; bbox_2d.AddBoundingVertexSmart(v.pos); if (!lighting) { // If there is no lighting then we need to copy the color_init // array to color. v.color = (*vertices)[i].color_init; v.color.Clamp (2, 2, 2); } float sqdist = v.pos.x*v.pos.x + v.pos.y*v.pos.y; if (sqdist > max_sq_dist) max_sq_dist = sqdist; } radius = csQsqrt (max_sq_dist); bufferHolder.AttachNew (new csRenderBufferHolder); csRef<iRenderBufferAccessor> newAccessor; newAccessor.AttachNew (new RenderBufferAccessor (this)); bufferHolder->SetAccessor (newAccessor, (uint32)CS_BUFFER_ALL_MASK); svcontext.AttachNew (new csShaderVariableContext); } } static csVector3 cam; void csSprite2DMeshObject::UpdateLighting ( const csSafeCopyArray<csLightInfluence>& lights, const csVector3& pos) { if (!lighting) return; csColor color (0, 0, 0); // @@@ GET AMBIENT //csSector* sect = movable.GetSector (0); //if (sect) //{ //int r, g, b; //sect->GetAmbientColor (r, g, b); //color.Set (r / 128.0, g / 128.0, b / 128.0); //} int i; int num_lights = (int)lights.GetSize (); for (i = 0; i < num_lights; i++) { iLight* li = lights[i].light; if (!li) continue; csColor light_color = li->GetColor () * (256. / CS_NORMAL_LIGHT_LEVEL); float sq_light_radius = csSquare (li->GetCutoffDistance ()); // Compute light position. csVector3 wor_light_pos = li->GetMovable ()->GetFullPosition (); float wor_sq_dist = csSquaredDist::PointPoint (wor_light_pos, pos); if (wor_sq_dist >= sq_light_radius) continue; float wor_dist = csQsqrt (wor_sq_dist); float cosinus = 1.0f; cosinus /= wor_dist; light_color *= cosinus * li->GetBrightnessAtDistance (wor_dist); color += light_color; } csColoredVertices* vertices = GetCsVertices (); for (size_t j = 0 ; j < vertices->GetSize () ; j++) { (*vertices)[j].color = (*vertices)[j].color_init + color; (*vertices)[j].color.Clamp (2, 2, 2); } colors_dirty = true; } void csSprite2DMeshObject::UpdateLighting ( const csSafeCopyArray<csLightInfluence>& lights, iMovable* movable, csVector3 offset) { if (!lighting) return; csVector3 pos = movable->GetFullPosition (); UpdateLighting (lights, pos + offset); } csRenderMesh** csSprite2DMeshObject::GetRenderMeshes (int &n, iRenderView* rview, iMovable* movable, uint32 frustum_mask, csVector3 offset) { SetupObject (); if (!material) { csReport (factory->object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.mesh.sprite2d", "Error! Trying to draw a sprite with no material!"); return 0; } iCamera* camera = rview->GetCamera (); // Camera transformation for the single 'position' vector. cam = rview->GetCamera ()->GetTransform ().Other2This ( movable->GetFullPosition () + offset); if (cam.z < SMALL_Z) { n = 0; return 0; } if (factory->light_mgr) { csSafeCopyArray<csLightInfluence> lightInfluences; scfArrayWrap<iLightInfluenceArray, csSafeCopyArray<csLightInfluence> > relevantLights (lightInfluences); //Yes, know, its on the stack... factory->light_mgr->GetRelevantLights (logparent, &relevantLights, -1); UpdateLighting (lightInfluences, movable, offset); } csReversibleTransform temp = camera->GetTransform (); if (!movable->IsFullTransformIdentity ()) temp /= movable->GetFullTransform (); int clip_portal, clip_plane, clip_z_plane; CS::RenderViewClipper::CalculateClipSettings (rview->GetRenderContext (), frustum_mask, clip_portal, clip_plane, clip_z_plane); csReversibleTransform tr_o2c; tr_o2c.SetO2TTranslation (-temp.Other2This (offset)); bool meshCreated; csRenderMesh*& rm = rmHolder.GetUnusedMesh (meshCreated, rview->GetCurrentFrameNumber ()); if (meshCreated) { rm->meshtype = CS_MESHTYPE_TRIANGLEFAN; rm->buffers = bufferHolder; rm->variablecontext = svcontext; rm->geometryInstance = this; } rm->material = material;//Moved this statement out of the above 'if' //to make the change of the material possible at any time //(thru a call to either iSprite2DState::SetMaterialWrapper () or //csSprite2DMeshObject::SetMaterialWrapper (). Luca rm->mixmode = MixMode; rm->clip_portal = clip_portal; rm->clip_plane = clip_plane; rm->clip_z_plane = clip_z_plane; rm->do_mirror = false/* camera->IsMirrored () */; /* Force to false as the front-face culling will let the sprite disappear. */ rm->indexstart = 0; rm->worldspace_origin = movable->GetFullPosition (); rm->object2world = tr_o2c.GetInverse () * camera->GetTransform (); rm->bbox = GetObjectBoundingBox(); rm->indexend = (uint)GetCsVertices ()->GetSize (); n = 1; return &rm; } void csSprite2DMeshObject::PreGetBuffer (csRenderBufferHolder* holder, csRenderBufferName buffer) { if (!holder) return; csColoredVertices* vertices = GetCsVertices (); if (buffer == CS_BUFFER_INDEX) { size_t indexSize = vertices->GetSize (); if (!index_buffer.IsValid() || (indicesSize != indexSize)) { index_buffer = csRenderBuffer::CreateIndexRenderBuffer ( indexSize, CS_BUF_DYNAMIC, CS_BUFCOMP_UNSIGNED_INT, 0, vertices->GetSize () - 1); holder->SetRenderBuffer (CS_BUFFER_INDEX, index_buffer); csRenderBufferLock<uint> indexLock (index_buffer); uint* ptr = indexLock; for (size_t i = 0; i < vertices->GetSize (); i++) { *ptr++ = (uint)i; } indicesSize = indexSize; } } else if (buffer == CS_BUFFER_TEXCOORD0) { if (texels_dirty) { int texels_count; const csVector2 *uvani_uv = 0; if (!uvani) texels_count = (int)vertices->GetSize (); else uvani_uv = uvani->GetVertices (texels_count); size_t texelSize = texels_count; if (!texel_buffer.IsValid() || (texel_buffer->GetSize() != texelSize * sizeof(float) * 2)) { texel_buffer = csRenderBuffer::CreateRenderBuffer ( texelSize, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 2); holder->SetRenderBuffer (CS_BUFFER_TEXCOORD0, texel_buffer); } csRenderBufferLock<csVector2> texelLock (texel_buffer); for (size_t i = 0; i < (size_t)texels_count; i++) { csVector2& v = texelLock[i]; if (!uvani) { v.x = (*vertices)[i].u; v.y = (*vertices)[i].v; } else { v.x = uvani_uv[i].x; v.y = uvani_uv[i].y; } } texels_dirty = false; } } else if (buffer == CS_BUFFER_COLOR) { if (colors_dirty) { size_t color_size = vertices->GetSize (); if (!color_buffer.IsValid() || (color_buffer->GetSize() != color_size * sizeof(float) * 2)) { color_buffer = csRenderBuffer::CreateRenderBuffer ( color_size, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 3); holder->SetRenderBuffer (CS_BUFFER_COLOR, color_buffer); } csRenderBufferLock<csColor> colorLock (color_buffer); for (size_t i = 0; i < vertices->GetSize (); i++) { colorLock[i] = (*vertices)[i].color; } colors_dirty = false; } } else if (buffer == CS_BUFFER_POSITION) { if (vertices_dirty) { size_t vertices_size = vertices->GetSize (); if (!vertex_buffer.IsValid() || (vertex_buffer->GetSize() != vertices_size * sizeof(float) * 3)) { vertex_buffer = csRenderBuffer::CreateRenderBuffer ( vertices_size, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 3); holder->SetRenderBuffer (CS_BUFFER_POSITION, vertex_buffer); } csRenderBufferLock<csVector3> vertexLock (vertex_buffer); for (size_t i = 0; i < vertices->GetSize (); i++) { vertexLock[i].Set ((*vertices)[i].pos.x, (*vertices)[i].pos.y, 0.0f); } vertices_dirty = false; } } } const csBox3& csSprite2DMeshObject::GetObjectBoundingBox () { SetupObject (); obj_bbox.Set (-radius, radius); return obj_bbox; } void csSprite2DMeshObject::SetObjectBoundingBox (const csBox3&) { // @@@ TODO } void csSprite2DMeshObject::HardTransform (const csReversibleTransform& t) { (void)t; //@@@ TODO } void csSprite2DMeshObject::CreateRegularVertices (int n, bool setuv) { double angle_inc = TWO_PI / n; double angle = 0.0; csColoredVertices* vertices = GetCsVertices (); vertices->SetSize (n); size_t i; for (i = 0; i < vertices->GetSize (); i++, angle += angle_inc) { (*vertices) [i].pos.y = cos (angle); (*vertices) [i].pos.x = sin (angle); if (setuv) { // reuse sin/cos values and scale to [0..1] (*vertices) [i].u = (*vertices) [i].pos.x / 2.0f + 0.5f; (*vertices) [i].v = (*vertices) [i].pos.y / 2.0f + 0.5f; } (*vertices) [i].color.Set (1, 1, 1); (*vertices) [i].color_init.Set (1, 1, 1); } vertices_dirty = true; texels_dirty = true; colors_dirty = true; ShapeChanged (); } void csSprite2DMeshObject::NextFrame (csTicks current_time, const csVector3& /*pos*/, uint /*currentFrame*/) { if (uvani && !uvani->halted) { int old_frame_index = uvani->frameindex; uvani->Advance (current_time); texels_dirty |= (old_frame_index != uvani->frameindex); } } void csSprite2DMeshObject::UpdateLighting ( const csSafeCopyArray<csLightInfluence>& lights, const csReversibleTransform& transform) { csVector3 new_pos = transform.This2Other (part_pos); UpdateLighting (lights, new_pos); } void csSprite2DMeshObject::AddColor (const csColor& col) { iColoredVertices* vertices = GetVertices (); size_t i; for (i = 0 ; i < vertices->GetSize(); i++) vertices->Get (i).color_init += col; if (!lighting) for (i = 0 ; i < vertices->GetSize(); i++) vertices->Get (i).color = vertices->Get (i).color_init; colors_dirty = true; } bool csSprite2DMeshObject::SetColor (const csColor& col) { iColoredVertices* vertices = GetVertices (); size_t i; for (i = 0 ; i < vertices->GetSize(); i++) vertices->Get (i).color_init = col; if (!lighting) for (i = 0 ; i < vertices->GetSize(); i++) vertices->Get (i).color = col; colors_dirty = true; return true; } void csSprite2DMeshObject::ScaleBy (float factor) { iColoredVertices* vertices = GetVertices (); size_t i; for (i = 0 ; i < vertices->GetSize(); i++) vertices->Get (i).pos *= factor; vertices_dirty = true; ShapeChanged (); } void csSprite2DMeshObject::Rotate (float angle) { iColoredVertices* vertices = GetVertices (); size_t i; for (i = 0 ; i < vertices->GetSize(); i++) vertices->Get (i).pos.Rotate (angle); vertices_dirty = true; ShapeChanged (); } void csSprite2DMeshObject::SetUVAnimation (const char *name, int style, bool loop) { if (name) { iSprite2DUVAnimation *ani = factory->GetUVAnimation (name); if (ani && ani->GetFrameCount ()) { uvani = new uvAnimationControl (); uvani->ani = ani; uvani->last_time = 0; uvani->frameindex = 0; uvani->framecount = ani->GetFrameCount (); uvani->frame = ani->GetFrame (0); uvani->style = style; uvani->counter = 0; uvani->loop = loop; uvani->halted = false; } } else { // stop animation and show the normal texture delete uvani; uvani = 0; } } void csSprite2DMeshObject::StopUVAnimation (int idx) { if (uvani) { if (idx != -1) { uvani->frameindex = csMin (csMax (idx, 0), uvani->framecount-1); uvani->frame = uvani->ani->GetFrame (uvani->frameindex); } uvani->halted = true; } } void csSprite2DMeshObject::PlayUVAnimation (int idx, int style, bool loop) { if (uvani) { if (idx != -1) { uvani->frameindex = csMin (csMax (idx, 0), uvani->framecount-1); uvani->frame = uvani->ani->GetFrame (uvani->frameindex); } uvani->halted = false; uvani->counter = 0; uvani->last_time = 0; uvani->loop = loop; uvani->style = style; } } int csSprite2DMeshObject::GetUVAnimationCount () const { return factory->GetUVAnimationCount (); } iSprite2DUVAnimation *csSprite2DMeshObject::CreateUVAnimation () { return factory->CreateUVAnimation (); } void csSprite2DMeshObject::RemoveUVAnimation ( iSprite2DUVAnimation *anim) { factory->RemoveUVAnimation (anim); } iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation ( const char *name) const { return factory->GetUVAnimation (name); } iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation ( int idx) const { return factory->GetUVAnimation (idx); } iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation ( int idx, int &style, bool &loop) const { style = uvani->style; loop = uvani->loop; return factory->GetUVAnimation (idx); } void csSprite2DMeshObject::EnsureVertexCopy () { if (!scfVertices.IsValid()) { scfVertices.AttachNew (new scfArrayWrap<iColoredVertices, csColoredVertices> (vertices)); vertices = *(factory->GetCsVertices()); } } void csSprite2DMeshObject::uvAnimationControl::Advance (csTicks current_time) { int oldframeindex = frameindex; // the goal is to find the next frame to show if (style < 0) { // every (-1*style)-th frame show a new pic counter--; if (counter < style) { counter = 0; frameindex++; if (frameindex == framecount) { if (loop) frameindex = 0; else { frameindex = framecount-1; halted = true; } } } } else if (style > 0) { // skip to next frame every <style> millisecond if (last_time == 0) last_time = current_time; counter += (current_time - last_time); last_time = current_time; while (counter > style) { counter -= style; frameindex++; if (frameindex == framecount) { if (loop) frameindex = 0; else { frameindex = framecount-1; halted = true; } } } } else { // style == 0 -> use time indices attached to the frames if (last_time == 0) last_time = current_time; while (frame->GetDuration () + last_time < current_time) { frameindex++; if (frameindex == framecount) { if (loop) { frameindex = 0; } else { frameindex = framecount-1; halted = true; break; } } } last_time += frame->GetDuration (); frame = ani->GetFrame (frameindex); } if (oldframeindex != frameindex) frame = ani->GetFrame (frameindex); } const csVector2 *csSprite2DMeshObject::uvAnimationControl::GetVertices ( int &num) { num = frame->GetUVCount (); return frame->GetUVCoo (); } // The hit beam methods in sprite2d make a couple of small presumptions. // 1) The sprite is always facing the start of the beam. // 2) Since it is always facing the beam, only one side // of its bounding box can be hit (if at all). void csSprite2DMeshObject::CheckBeam (const csVector3& /*start*/, const csVector3& pl, float sqr, csMatrix3& o2t) { // This method is an optimized version of LookAt() based on // the presumption that the up vector is always (0,1,0). // This is used to create a transform to move the intersection // to the sprites vector space, then it is tested against the 2d // coords, which are conveniently located at z=0. // The transformation matrix is stored and used again if the // start vector for the beam is in the same position. MHV. csVector3 pl2 = pl * csQisqrt (sqr); csVector3 v1( pl2.z, 0, -pl2.x); sqr = v1*v1; v1 *= csQisqrt(sqr); csVector3 v2(pl2.y * v1.z, pl2.z * v1.x - pl2.x * v1.z, -pl2.y * v1.x); o2t.Set (v1.x, v2.x, pl2.x, v1.y, v2.y, pl2.y, v1.z, v2.z, pl2.z); } bool csSprite2DMeshObject::HitBeamOutline(const csVector3& start, const csVector3& end, csVector3& isect, float* pr) { csVector2 cen = bbox_2d.GetCenter(); csVector3 pl = start - csVector3(cen.x, cen.y, 0); float sqr = pl * pl; if (sqr < SMALL_EPSILON) return false; // Too close, Cannot intersect float dist; csIntersect3::SegmentPlane(start, end, pl, 0, isect, dist); if (pr) { *pr = dist; } csMatrix3 o2t; CheckBeam (start, pl, sqr, o2t); csVector3 r = o2t * isect; csColoredVertices* vertices = GetCsVertices (); int trail, len = (int)vertices->GetSize (); trail = len - 1; csVector2 isec(r.x, r.y); int i; for (i = 0; i < len; trail = i++) { if (csMath2::WhichSide2D(isec, (*vertices)[trail].pos, (*vertices)[i].pos) > 0) return false; } return true; } bool csSprite2DMeshObject::HitBeamObject (const csVector3& start, const csVector3& end, csVector3& isect, float* pr, int* polygon_idx, iMaterialWrapper** material, bool bf) { if (material) *material = csSprite2DMeshObject::material; if (polygon_idx) *polygon_idx = -1; return HitBeamOutline (start, end, isect, pr); } //---------------------------------------------------------------------- csSprite2DMeshObjectFactory::csSprite2DMeshObjectFactory (iMeshObjectType* pParent, iObjectRegistry* object_reg) : scfImplementationType (this, pParent), material (0), logparent (0), spr2d_type (pParent), MixMode (0), lighting (true), object_reg (object_reg) { light_mgr = csQueryRegistry<iLightManager> (object_reg); g3d = csQueryRegistry<iGraphics3D> (object_reg); scfVertices.AttachNew (new scfArrayWrap<iColoredVertices, csColoredVertices> (vertices)); ax = -10; } csSprite2DMeshObjectFactory::~csSprite2DMeshObjectFactory () { } csPtr<iMeshObject> csSprite2DMeshObjectFactory::NewInstance () { csRef<csSprite2DMeshObject> cm; cm.AttachNew (new csSprite2DMeshObject (this)); csRef<iMeshObject> im (scfQueryInterface<iMeshObject> (cm)); return csPtr<iMeshObject> (im); } //---------------------------------------------------------------------- SCF_IMPLEMENT_FACTORY (csSprite2DMeshObjectType) csSprite2DMeshObjectType::csSprite2DMeshObjectType (iBase* pParent) : scfImplementationType (this, pParent) { } csSprite2DMeshObjectType::~csSprite2DMeshObjectType () { } csPtr<iMeshObjectFactory> csSprite2DMeshObjectType::NewFactory () { csRef<csSprite2DMeshObjectFactory> cm; cm.AttachNew (new csSprite2DMeshObjectFactory (this, object_reg)); csRef<iMeshObjectFactory> ifact = scfQueryInterface<iMeshObjectFactory> (cm); return csPtr<iMeshObjectFactory> (ifact); } bool csSprite2DMeshObjectType::Initialize (iObjectRegistry* object_reg) { csSprite2DMeshObjectType::object_reg = object_reg; return true; } } CS_PLUGIN_NAMESPACE_END(Spr2D)
baoboa/Crystal-Space
plugins/mesh/spr2d/object/spr2d.cpp
C++
lgpl-2.1
21,393
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "./"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _addClass = __webpack_require__(25); var _addClass2 = _interopRequireDefault(_addClass); var _removeClass = __webpack_require__(26); var _removeClass2 = _interopRequireDefault(_removeClass); var _after = __webpack_require__(96); var _after2 = _interopRequireDefault(_after); var _browser = __webpack_require__(97); var _browser2 = _interopRequireDefault(_browser); var _fix = __webpack_require__(98); var _fix2 = _interopRequireDefault(_fix); var _util = __webpack_require__(27); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // fix hexo 不支持的配置 function isPathMatch(path, href) { var reg = /\/|index.html/g; return path.replace(reg, '') === href.replace(reg, ''); } // 浏览器判断 function tabActive() { var $tabs = document.querySelectorAll('.js-header-menu li a'); var path = window.location.pathname; for (var i = 0, len = $tabs.length; i < len; i++) { var $tab = $tabs[i]; if (isPathMatch(path, $tab.getAttribute('href'))) { (0, _addClass2.default)($tab, 'active'); } } } function getElementLeft(element) { var actualLeft = element.offsetLeft; var current = element.offsetParent; while (current !== null) { actualLeft += current.offsetLeft; current = current.offsetParent; } return actualLeft; } function getElementTop(element) { var actualTop = element.offsetTop; var current = element.offsetParent; while (current !== null) { actualTop += current.offsetTop; current = current.offsetParent; } return actualTop; } function scrollStop($dom, top, limit, zIndex, diff) { var nowLeft = getElementLeft($dom); var nowTop = getElementTop($dom) - top; if (nowTop - limit <= diff) { var $newDom = $dom.$newDom; if (!$newDom) { $newDom = $dom.cloneNode(true); (0, _after2.default)($dom, $newDom); $dom.$newDom = $newDom; $newDom.style.position = 'fixed'; $newDom.style.top = (limit || nowTop) + 'px'; $newDom.style.left = nowLeft + 'px'; $newDom.style.zIndex = zIndex || 2; $newDom.style.width = '100%'; $newDom.style.color = '#fff'; } $newDom.style.visibility = 'visible'; $dom.style.visibility = 'hidden'; } else { $dom.style.visibility = 'visible'; var _$newDom = $dom.$newDom; if (_$newDom) { _$newDom.style.visibility = 'hidden'; } } } function handleScroll() { var $overlay = document.querySelector('.js-overlay'); var $menu = document.querySelector('.js-header-menu'); scrollStop($overlay, document.body.scrollTop, -63, 2, 0); scrollStop($menu, document.body.scrollTop, 1, 3, 0); } function bindScroll() { document.querySelector('#container').addEventListener('scroll', function (e) { handleScroll(); }); window.addEventListener('scroll', function (e) { handleScroll(); }); handleScroll(); } function init() { if (_browser2.default.versions.mobile && window.screen.width < 800) { tabActive(); bindScroll(); } } init(); (0, _util.addLoadEvent)(function () { _fix2.default.init(); }); module.exports = {}; /***/ }, /* 1 */, /* 2 */, /* 3 */, /* 4 */, /* 5 */, /* 6 */, /* 7 */, /* 8 */, /* 9 */, /* 10 */, /* 11 */, /* 12 */, /* 13 */, /* 14 */, /* 15 */, /* 16 */, /* 17 */, /* 18 */, /* 19 */, /* 20 */, /* 21 */, /* 22 */, /* 23 */, /* 24 */, /* 25 */ /***/ function(module, exports) { /** * addClass : addClass(el, className) * Adds a class name to an element. Compare with `$.fn.addClass`. * * var addClass = require('dom101/add-class'); * * addClass(el, 'active'); */ function addClass (el, className) { if (el.classList) { el.classList.add(className); } else { el.className += ' ' + className; } } module.exports = addClass; /***/ }, /* 26 */ /***/ function(module, exports) { /** * removeClass : removeClass(el, className) * Removes a classname. * * var removeClass = require('dom101/remove-class'); * * el.className = 'selected active'; * removeClass(el, 'active'); * * el.className * => "selected" */ function removeClass (el, className) { if (el.classList) { el.classList.remove(className); } else { var expr = new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'); el.className = el.className.replace(expr, ' '); } } module.exports = removeClass; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _typeof2 = __webpack_require__(28); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var e = function () { function r(e, r, n) { return r || n ? String.fromCharCode(r || n) : u[e] || e; } function n(e) { return p[e]; } var t = /&quot;|&lt;|&gt;|&amp;|&nbsp;|&apos;|&#(\d+);|&#(\d+)/g, o = /['<> "&]/g, u = { "&quot;": '"', "&lt;": "<", "&gt;": ">", "&amp;": "&", "&nbsp;": " " }, c = /\u00a0/g, a = /<br\s*\/?>/gi, i = /\r?\n/g, f = /\s/g, p = {}; for (var s in u) { p[u[s]] = s; }return u["&apos;"] = "'", p["'"] = "&#39;", { encode: function encode(e) { return e ? ("" + e).replace(o, n).replace(i, "<br/>").replace(f, "&nbsp;") : ""; }, decode: function decode(e) { return e ? ("" + e).replace(a, "\n").replace(t, r).replace(c, " ") : ""; }, encodeBase16: function encodeBase16(e) { if (!e) return e; e += ""; for (var r = [], n = 0, t = e.length; t > n; n++) { r.push(e.charCodeAt(n).toString(16).toUpperCase()); }return r.join(""); }, encodeBase16forJSON: function encodeBase16forJSON(e) { if (!e) return e; e = e.replace(/[\u4E00-\u9FBF]/gi, function (e) { return escape(e).replace("%u", "\\u"); }); for (var r = [], n = 0, t = e.length; t > n; n++) { r.push(e.charCodeAt(n).toString(16).toUpperCase()); }return r.join(""); }, decodeBase16: function decodeBase16(e) { if (!e) return e; e += ""; for (var r = [], n = 0, t = e.length; t > n; n += 2) { r.push(String.fromCharCode("0x" + e.slice(n, n + 2))); }return r.join(""); }, encodeObject: function encodeObject(r) { if (r instanceof Array) for (var n = 0, t = r.length; t > n; n++) { r[n] = e.encodeObject(r[n]); } else if ("object" == (typeof r === "undefined" ? "undefined" : (0, _typeof3.default)(r))) for (var o in r) { r[o] = e.encodeObject(r[o]); } else if ("string" == typeof r) return e.encode(r); return r; }, loadScript: function loadScript(path) { var $script = document.createElement('script'); document.getElementsByTagName('body')[0].appendChild($script); $script.setAttribute('src', path); }, addLoadEvent: function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != "function") { window.onload = func; } else { window.onload = function () { oldonload(); func(); }; } } }; }(); module.exports = e; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(29); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(80); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(30), __esModule: true }; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(31); __webpack_require__(75); module.exports = __webpack_require__(79).f('iterator'); /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(32)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(35)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(33) , defined = __webpack_require__(34); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 33 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 34 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(36) , $export = __webpack_require__(37) , redefine = __webpack_require__(52) , hide = __webpack_require__(42) , has = __webpack_require__(53) , Iterators = __webpack_require__(54) , $iterCreate = __webpack_require__(55) , setToStringTag = __webpack_require__(71) , getPrototypeOf = __webpack_require__(73) , ITERATOR = __webpack_require__(72)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 36 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(38) , core = __webpack_require__(39) , ctx = __webpack_require__(40) , hide = __webpack_require__(42) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }, /* 38 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 39 */ /***/ function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(41); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 41 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(43) , createDesc = __webpack_require__(51); module.exports = __webpack_require__(47) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(44) , IE8_DOM_DEFINE = __webpack_require__(46) , toPrimitive = __webpack_require__(50) , dP = Object.defineProperty; exports.f = __webpack_require__(47) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(45); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 45 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(47) && !__webpack_require__(48)(function(){ return Object.defineProperty(__webpack_require__(49)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(48)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 48 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(45) , document = __webpack_require__(38).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(45); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }, /* 51 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(42); /***/ }, /* 53 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 54 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var create = __webpack_require__(56) , descriptor = __webpack_require__(51) , setToStringTag = __webpack_require__(71) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(42)(IteratorPrototype, __webpack_require__(72)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(44) , dPs = __webpack_require__(57) , enumBugKeys = __webpack_require__(69) , IE_PROTO = __webpack_require__(66)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(49)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; __webpack_require__(70).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(43) , anObject = __webpack_require__(44) , getKeys = __webpack_require__(58); module.exports = __webpack_require__(47) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(59) , enumBugKeys = __webpack_require__(69); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var has = __webpack_require__(53) , toIObject = __webpack_require__(60) , arrayIndexOf = __webpack_require__(63)(false) , IE_PROTO = __webpack_require__(66)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(61) , defined = __webpack_require__(34); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(62); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 62 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(60) , toLength = __webpack_require__(64) , toIndex = __webpack_require__(65); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(33) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(33) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var shared = __webpack_require__(67)('keys') , uid = __webpack_require__(68); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(38) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 68 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 69 */ /***/ function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(38).document && document.documentElement; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(43).f , has = __webpack_require__(53) , TAG = __webpack_require__(72)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(67)('wks') , uid = __webpack_require__(68) , Symbol = __webpack_require__(38).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(53) , toObject = __webpack_require__(74) , IE_PROTO = __webpack_require__(66)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(34); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(76); var global = __webpack_require__(38) , hide = __webpack_require__(42) , Iterators = __webpack_require__(54) , TO_STRING_TAG = __webpack_require__(72)('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(77) , step = __webpack_require__(78) , Iterators = __webpack_require__(54) , toIObject = __webpack_require__(60); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(35)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 77 */ /***/ function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }, /* 78 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { exports.f = __webpack_require__(72); /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(81), __esModule: true }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(82); __webpack_require__(93); __webpack_require__(94); __webpack_require__(95); module.exports = __webpack_require__(39).Symbol; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var global = __webpack_require__(38) , has = __webpack_require__(53) , DESCRIPTORS = __webpack_require__(47) , $export = __webpack_require__(37) , redefine = __webpack_require__(52) , META = __webpack_require__(83).KEY , $fails = __webpack_require__(48) , shared = __webpack_require__(67) , setToStringTag = __webpack_require__(71) , uid = __webpack_require__(68) , wks = __webpack_require__(72) , wksExt = __webpack_require__(79) , wksDefine = __webpack_require__(84) , keyOf = __webpack_require__(85) , enumKeys = __webpack_require__(86) , isArray = __webpack_require__(89) , anObject = __webpack_require__(44) , toIObject = __webpack_require__(60) , toPrimitive = __webpack_require__(50) , createDesc = __webpack_require__(51) , _create = __webpack_require__(56) , gOPNExt = __webpack_require__(90) , $GOPD = __webpack_require__(92) , $DP = __webpack_require__(43) , $keys = __webpack_require__(58) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(91).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(88).f = $propertyIsEnumerable; __webpack_require__(87).f = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(36)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(42)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { var META = __webpack_require__(68)('meta') , isObject = __webpack_require__(45) , has = __webpack_require__(53) , setDesc = __webpack_require__(43).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !__webpack_require__(48)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(38) , core = __webpack_require__(39) , LIBRARY = __webpack_require__(36) , wksExt = __webpack_require__(79) , defineProperty = __webpack_require__(43).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(58) , toIObject = __webpack_require__(60); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(58) , gOPS = __webpack_require__(87) , pIE = __webpack_require__(88); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; /***/ }, /* 87 */ /***/ function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }, /* 88 */ /***/ function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(62); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(60) , gOPN = __webpack_require__(91).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(59) , hiddenKeys = __webpack_require__(69).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var pIE = __webpack_require__(88) , createDesc = __webpack_require__(51) , toIObject = __webpack_require__(60) , toPrimitive = __webpack_require__(50) , has = __webpack_require__(53) , IE8_DOM_DEFINE = __webpack_require__(46) , gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(47) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }, /* 93 */ /***/ function(module, exports) { /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(84)('asyncIterator'); /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(84)('observable'); /***/ }, /* 96 */ /***/ function(module, exports) { /** * after : after(el, newEl) * Inserts a new element `newEl` just after `el`. * * var after = require('dom101/after'); * var newNode = document.createElement('div'); * var button = document.querySelector('#submit'); * * after(button, newNode); */ function after (el, newEl) { if (typeof newEl === 'string') { return el.insertAdjacentHTML('afterend', newEl); } else { var next = el.nextSibling; if (next) { return el.parentNode.insertBefore(newEl, next); } else { return el.parentNode.appendChild(newEl); } } } module.exports = after; /***/ }, /* 97 */ /***/ function(module, exports) { 'use strict'; var browser = { versions: function () { var u = window.navigator.userAgent; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器 iPad: u.indexOf('iPad') > -1, //是否为iPad webApp: u.indexOf('Safari') == -1, //是否为web应用程序,没有头部与底部 weixin: u.indexOf('MicroMessenger') == -1 //是否为微信浏览器 }; }() }; module.exports = browser; /***/ }, /* 98 */ /***/ function(module, exports) { 'use strict'; function init() { // 由于hexo分页不支持,手工美化 var $nav = document.querySelector('#page-nav'); if ($nav && !document.querySelector('#page-nav .extend.prev')) { $nav.innerHTML = '<a class="extend prev disabled" rel="prev">&laquo; Prev</a>' + $nav.innerHTML; } if ($nav && !document.querySelector('#page-nav .extend.next')) { $nav.innerHTML = $nav.innerHTML + '<a class="extend next disabled" rel="next">Next &raquo;</a>'; } // 新窗口打开 if (yiliaConfig && yiliaConfig.open_in_new) { var $a = document.querySelectorAll('.article-entry a:not(.article-more-a)'); $a.forEach(function ($em) { $em.setAttribute('target', '_blank'); }); } // about me 转义 var $aboutme = document.querySelector('#js-aboutme'); if ($aboutme && $aboutme.length !== 0) { $aboutme.innerHTML = $aboutme.innerText; } } module.exports = { init: init }; /***/ } /******/ ]);
halochen90/Hexo-Theme-Luna
source/mobile.09c351.js
JavaScript
lgpl-2.1
51,975
///////////////////////////////////////////////////////////////////////////// // Name: help.cpp // Purpose: wxHtml sample: help test // Author: ? // Modified by: // Created: ? // RCS-ID: $Id$ // Copyright: (c) wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/image.h" #include "wx/html/helpfrm.h" #include "wx/html/helpctrl.h" #include "wx/filesys.h" #include "wx/fs_zip.h" #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../../sample.xpm" #endif // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // Define a new application type, each program should derive a class from wxApp class MyApp : public wxApp { public: // override base class virtuals // ---------------------------- // this one is called on application startup and is a good place for the app // initialization (doing it here and not in the ctor allows to have an error // return: if OnInit() returns false, the application terminates) virtual bool OnInit(); }; // Define a new frame type: this is going to be our main frame class MyFrame : public wxFrame { public: // ctor(s) MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); // event handlers (these functions should _not_ be virtual) void OnQuit(wxCommandEvent& event); void OnHelp(wxCommandEvent& event); void OnClose(wxCloseEvent& event); private: wxHtmlHelpController help; // any class wishing to process wxWidgets events must use this macro DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum { // menu items Minimal_Quit = 1, Minimal_Help }; // ---------------------------------------------------------------------------- // event tables and other macros for wxWidgets // ---------------------------------------------------------------------------- // the event tables connect the wxWidgets events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(Minimal_Quit, MyFrame::OnQuit) EVT_MENU(Minimal_Help, MyFrame::OnHelp) EVT_CLOSE(MyFrame::OnClose) END_EVENT_TABLE() // Create a new application object: this macro will allow wxWidgets to create // the application object during program execution (it's better than using a // static object for many reasons) and also declares the accessor function // wxGetApp() which will return the reference of the right type (i.e. MyApp and // not wxApp) IMPLEMENT_APP(MyApp) // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // the application class // ---------------------------------------------------------------------------- // `Main program' equivalent: the program execution "starts" here bool MyApp::OnInit() { if ( !wxApp::OnInit() ) return false; wxInitAllImageHandlers(); #if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB wxFileSystem::AddHandler(new wxZipFSHandler); #endif SetVendorName(wxT("wxWidgets")); SetAppName(wxT("wxHTMLHelp")); // Create the main application window MyFrame *frame = new MyFrame(_("HTML Help Sample"), wxDefaultPosition, wxDefaultSize); // Show it frame->Show(true); // success: wxApp::OnRun() will be called which will enter the main message // loop and the application will run. If we returned false here, the // application would exit immediately. return true; } // ---------------------------------------------------------------------------- // main frame // ---------------------------------------------------------------------------- // frame constructor MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size), help(wxHF_DEFAULT_STYLE | wxHF_OPEN_FILES) { SetIcon(wxICON(sample)); // create a menu bar wxMenu *menuFile = new wxMenu; menuFile->Append(Minimal_Help, _("&Help")); menuFile->Append(Minimal_Quit, _("E&xit")); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar; menuBar->Append(menuFile, _("&File")); // ... and attach this menu bar to the frame SetMenuBar(menuBar); help.UseConfig(wxConfig::Get()); bool ret; help.SetTempDir(wxT(".")); ret = help.AddBook(wxFileName(wxT("helpfiles/testing.hhp"), wxPATH_UNIX)); if (! ret) wxMessageBox(wxT("Failed adding book helpfiles/testing.hhp")); ret = help.AddBook(wxFileName(wxT("helpfiles/another.hhp"), wxPATH_UNIX)); if (! ret) wxMessageBox(_("Failed adding book helpfiles/another.hhp")); } // event handlers void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { // true is to force the frame to close Close(true); } void MyFrame::OnHelp(wxCommandEvent& WXUNUSED(event)) { help.Display(wxT("Test HELPFILE")); } void MyFrame::OnClose(wxCloseEvent& event) { // Close the help frame; this will cause the config data to // get written. if ( help.GetFrame() ) // returns NULL if no help frame active help.GetFrame()->Close(true); // now we can safely delete the config pointer event.Skip(); delete wxConfig::Set(NULL); }
enachb/freetel-code
src/wxWidgets-2.9.4/samples/html/help/help.cpp
C++
lgpl-2.1
6,219
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.controller.interfaces; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.jboss.as.controller.logging.ControllerLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * Overall interface criteria. Encapsulates a set of individual criteria and selects interfaces and addresses * that meet them all. */ public final class OverallInterfaceCriteria implements InterfaceCriteria { // java.net properties static final String PREFER_IPV4_STACK = "java.net.preferIPv4Stack"; static final String PREFER_IPV6_ADDRESSES = "java.net.preferIPv6Addresses"; private static final long serialVersionUID = -5417786897309925997L; private final String interfaceName; private final Set<InterfaceCriteria> interfaceCriteria; public OverallInterfaceCriteria(final String interfaceName, Set<InterfaceCriteria> criteria) { this.interfaceName = interfaceName; this.interfaceCriteria = criteria; } @Override public Map<NetworkInterface, Set<InetAddress>> getAcceptableAddresses(Map<NetworkInterface, Set<InetAddress>> candidates) throws SocketException { Map<NetworkInterface, Set<InetAddress>> result = AbstractInterfaceCriteria.cloneCandidates(candidates); Set<InterfaceCriteria> sorted = new TreeSet<>(interfaceCriteria); for (InterfaceCriteria criteria : sorted) { result = criteria.getAcceptableAddresses(result); if (result.size() == 0) { break; } } if (result.size() > 0) { if (hasMultipleMatches(result)) { // Multiple options matched the criteria. Eliminate the same address showing up in both // a subinterface (an alias) and in the parent result = pruneAliasDuplicates(result); } if (hasMultipleMatches(result)) { // Multiple options matched the criteria. Try and narrow the selection based on // preferences indirectly expressed via -Djava.net.preferIPv4Stack and -Djava.net.preferIPv6Addresses result = pruneIPTypes(result); } if (hasMultipleMatches(result)) { // Multiple options matched the criteria; Pick one Map<NetworkInterface, Set<InetAddress>> selected = selectInterfaceAndAddress(result); // Warn user their criteria was insufficiently exact if (interfaceName != null) { // will be null if the resolution is being performed for the "resolved-address" // user query operation in which case we don't want to log a WARN Map.Entry<NetworkInterface, Set<InetAddress>> entry = selected.entrySet().iterator().next(); warnMultipleValidInterfaces(interfaceName, result, entry.getKey(), entry.getValue().iterator().next()); } result = selected; } } return result; } public String toString() { StringBuilder sb = new StringBuilder("OverallInterfaceCriteria("); for (InterfaceCriteria criteria : interfaceCriteria) { sb.append(criteria.toString()); sb.append(","); } sb.setLength(sb.length() - 1); sb.append(")"); return sb.toString(); } @Override public int compareTo(InterfaceCriteria o) { if (this.equals(o)) { return 0; } return 1; } private Map<NetworkInterface, Set<InetAddress>> pruneIPTypes(Map<NetworkInterface, Set<InetAddress>> candidates) { Boolean preferIPv4Stack = getBoolean(PREFER_IPV4_STACK); Boolean preferIPv6Stack = (preferIPv4Stack != null && !preferIPv4Stack) ? Boolean.TRUE : getBoolean(PREFER_IPV6_ADDRESSES); if (preferIPv4Stack == null && preferIPv6Stack == null) { // No meaningful user input return candidates; } final Map<NetworkInterface, Set<InetAddress>> result = new HashMap<NetworkInterface, Set<InetAddress>>(); for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : candidates.entrySet()) { Set<InetAddress> good = null; for (InetAddress address : entry.getValue()) { if ((preferIPv4Stack != null && preferIPv4Stack && address instanceof Inet4Address) || (preferIPv6Stack != null && preferIPv6Stack && address instanceof Inet6Address)) { if (good == null) { good = new HashSet<InetAddress>(); result.put(entry.getKey(), good); } good.add(address); } } } return result.size() == 0 ? candidates : result; } static Map<NetworkInterface, Set<InetAddress>> pruneAliasDuplicates(Map<NetworkInterface, Set<InetAddress>> result) { final Map<NetworkInterface, Set<InetAddress>> pruned = new HashMap<NetworkInterface, Set<InetAddress>>(); for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : result.entrySet()) { NetworkInterface ni = entry.getKey(); if (ni.getParent() != null) { pruned.put(ni, entry.getValue()); } else { Set<InetAddress> retained = new HashSet<InetAddress>(entry.getValue()); Enumeration<NetworkInterface> subInterfaces = ni.getSubInterfaces(); while (subInterfaces.hasMoreElements()) { NetworkInterface sub = subInterfaces.nextElement(); Set<InetAddress> subAddresses = result.get(sub); if (subAddresses != null) { retained.removeAll(subAddresses); } } if (retained.size() > 0) { pruned.put(ni, retained); } } } return pruned; } private static Boolean getBoolean(final String property) { final String value = WildFlySecurityManager.getPropertyPrivileged(property, null); return value == null ? null : value.equalsIgnoreCase("true"); } private static Map<NetworkInterface, Set<InetAddress>> selectInterfaceAndAddress(Map<NetworkInterface, Set<InetAddress>> acceptable) throws SocketException { // Give preference to NetworkInterfaces that are 1) up, 2) not loopback 3) not point-to-point. // If any of these criteria eliminate all interfaces, discard it. if (acceptable.size() > 1) { Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (NetworkInterface ni : acceptable.keySet()) { if (ni.isUp()) { preferred.put(ni, acceptable.get(ni)); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } if (acceptable.size() > 1) { Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (NetworkInterface ni : acceptable.keySet()) { if (!ni.isLoopback()) { preferred.put(ni, acceptable.get(ni)); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } if (acceptable.size() > 1) { Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (NetworkInterface ni : acceptable.keySet()) { if (!ni.isPointToPoint()) { preferred.put(ni, acceptable.get(ni)); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } if (hasMultipleMatches(acceptable)) { // Give preference to non-link-local addresses Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : acceptable.entrySet()) { Set<InetAddress> acceptableAddresses = entry.getValue(); if (acceptableAddresses.size() > 1) { Set<InetAddress> preferredAddresses = null; for (InetAddress addr : acceptableAddresses) { if (!addr.isLinkLocalAddress()) { if (preferredAddresses == null) { preferredAddresses = new HashSet<InetAddress>(); preferred.put(entry.getKey(), preferredAddresses); } preferredAddresses.add(addr); } } } else { acceptable.put(entry.getKey(), acceptableAddresses); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } Map.Entry<NetworkInterface, Set<InetAddress>> entry = acceptable.entrySet().iterator().next(); return Collections.singletonMap(entry.getKey(), Collections.singleton(entry.getValue().iterator().next())); } private static boolean hasMultipleMatches(Map<NetworkInterface, Set<InetAddress>> map) { return map.size() > 1 || (map.size() == 1 && map.values().iterator().next().size() > 1); } private static void warnMultipleValidInterfaces(String interfaceName, Map<NetworkInterface, Set<InetAddress>> acceptable, NetworkInterface selectedInterface, InetAddress selectedAddress) { Set<String> nis = new HashSet<String>(); Set<InetAddress> addresses = new HashSet<InetAddress>(); for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : acceptable.entrySet()) { nis.add(entry.getKey().getName()); addresses.addAll(entry.getValue()); } ControllerLogger.ROOT_LOGGER.multipleMatchingAddresses(interfaceName, addresses, nis, selectedAddress, selectedInterface.getName()); } }
JiriOndrusek/wildfly-core
controller/src/main/java/org/jboss/as/controller/interfaces/OverallInterfaceCriteria.java
Java
lgpl-2.1
11,851
/* * CLiC, Framework for Command Line Interpretation in Eclipse * * Copyright (C) 2013 Worldline or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package com.worldline.clic.internal.assist; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; /** * This class allows to deal with autocompletion for all commands. * * @author mvanbesien * @since 1.0 * @version 1.0 */ public class ContentAssistProvider { private final StyledText text; private final IProcessor[] processors; private final Map<String, Object> properties = new HashMap<String, Object>(); private IStructuredContentProvider assistContentProvider; private Listener textKeyListener; private Listener assistTablePopulationListener; private Listener onSelectionListener; private Listener onEscapeListener; private IDoubleClickListener tableDoubleClickListener; private Listener focusOutListener; private Listener vanishListener; private Table table; private TableViewer viewer; private Shell popupShell; public ContentAssistProvider(final StyledText text, final IProcessor... processors) { this.text = text; this.processors = processors; build(); } public void setProperty(final String key, final Object value) { properties.put(key, value); } private void build() { // Creation of graphical elements final Display display = text.getDisplay(); popupShell = new Shell(display, SWT.ON_TOP); popupShell.setLayout(new FillLayout()); table = new Table(popupShell, SWT.SINGLE); viewer = new TableViewer(table); assistContentProvider = newAssistContentProvider(); textKeyListener = newTextKeyListener(); assistTablePopulationListener = newAssistTablePopulationListener(); onSelectionListener = newOnSelectionListener(); onEscapeListener = newOnEscapeListener(); tableDoubleClickListener = newDoubleClickListener(); focusOutListener = newFocusOutListener(); vanishListener = newVanishListener(); viewer.setContentProvider(assistContentProvider); text.addListener(SWT.KeyDown, textKeyListener); text.addListener(SWT.Modify, assistTablePopulationListener); table.addListener(SWT.DefaultSelection, onSelectionListener); table.addListener(SWT.KeyDown, onEscapeListener); viewer.addDoubleClickListener(tableDoubleClickListener); table.addListener(SWT.FocusOut, focusOutListener); text.addListener(SWT.FocusOut, focusOutListener); text.getShell().addListener(SWT.Move, vanishListener); text.addDisposeListener(newDisposeListener()); } private DisposeListener newDisposeListener() { return new DisposeListener() { @Override public void widgetDisposed(final DisposeEvent e) { text.removeListener(SWT.KeyDown, textKeyListener); text.removeListener(SWT.Modify, assistTablePopulationListener); table.removeListener(SWT.DefaultSelection, onSelectionListener); table.removeListener(SWT.KeyDown, onEscapeListener); viewer.removeDoubleClickListener(tableDoubleClickListener); table.removeListener(SWT.FocusOut, focusOutListener); text.removeListener(SWT.FocusOut, focusOutListener); text.getShell().removeListener(SWT.Move, vanishListener); table.dispose(); popupShell.dispose(); } }; } private IStructuredContentProvider newAssistContentProvider() { return new IStructuredContentProvider() { @Override public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { } @Override public void dispose() { } @Override public Object[] getElements(final Object inputElement) { final Collection<String> results = new ArrayList<String>(); if (inputElement instanceof String) { final String input = (String) inputElement; final ProcessorContext pc = new ProcessorContext(input, text.getCaretOffset(), properties); for (final IProcessor processor : processors) results.addAll(processor.getProposals(pc)); } return results.toArray(); } }; } private Listener newAssistTablePopulationListener() { return new Listener() { @Override public void handleEvent(final Event event) { if (event.widget instanceof Text) { final Text text = (Text) event.widget; final String string = text.getText(); if (string.length() == 0) // if (popupShell.isVisible()) popupShell.setVisible(false); else { viewer.setInput(string); final Rectangle textBounds = text.getDisplay().map( text.getParent(), null, text.getBounds()); popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height, textBounds.width, 80); // if (!popupShell.isVisible()) popupShell.setVisible(true); } } } }; } private Listener newVanishListener() { return new Listener() { @Override public void handleEvent(final Event event) { popupShell.setVisible(false); } }; } private Listener newTextKeyListener() { return new Listener() { @Override public void handleEvent(final Event event) { switch (event.keyCode) { case SWT.ARROW_DOWN: int index = (table.getSelectionIndex() + 1) % table.getItemCount(); table.setSelection(index); event.doit = false; break; case SWT.ARROW_UP: index = table.getSelectionIndex() - 1; if (index < 0) index = table.getItemCount() - 1; table.setSelection(index); event.doit = false; break; case SWT.ARROW_RIGHT: if (popupShell.isVisible() && table.getSelectionIndex() != -1) { text.setText(table.getSelection()[0].getText()); text.setSelection(text.getText().length()); popupShell.setVisible(false); } break; case SWT.ESC: popupShell.setVisible(false); break; } } }; } private IDoubleClickListener newDoubleClickListener() { return new IDoubleClickListener() { @Override public void doubleClick(final DoubleClickEvent event) { if (popupShell.isVisible() && table.getSelectionIndex() != -1) { text.setText(table.getSelection()[0].getText()); text.setSelection(text.getText().length()); popupShell.setVisible(false); } } }; } private Listener newOnSelectionListener() { return new Listener() { @Override public void handleEvent(final Event event) { if (event.widget instanceof Text) { final Text text = (Text) event.widget; final ISelection selection = viewer.getSelection(); if (selection instanceof IStructuredSelection) { text.setText(((IStructuredSelection) selection) .getFirstElement().toString()); text.setSelection(text.getText().length() - 1); } popupShell.setVisible(false); } } }; } private Listener newOnEscapeListener() { return new Listener() { @Override public void handleEvent(final Event event) { if (event.keyCode == SWT.ESC) popupShell.setVisible(false); } }; } private Listener newFocusOutListener() { return new Listener() { @Override public void handleEvent(final Event event) { popupShell.setVisible(false); } }; } }
awltech/clic
com.worldline.clic/src/main/java/com/worldline/clic/internal/assist/ContentAssistProvider.java
Java
lgpl-2.1
8,789
// LICENSE: (Please see the file COPYING for details) // // NUS - Nemesis Utilities System: A C++ application development framework // Copyright (C) 2006, 2007 Otavio Rodolfo Piske // // This file is part of NUS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation version 2.1 // of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #include "nthread.h" void *nthread_start_routine(void *data) { NThread *thread = static_cast<NThread *>(data); thread->threadStart(); return NULL; } NThread::NThread(void) : NObject() { } void NThread::threadCreate() { int ret = 0; pthread_t a_thread; ret = pthread_create(&a_thread, NULL, nthread_start_routine, (void *) this); }
orpiske/nus
src/base/osal/unix/nthread.cpp
C++
lgpl-2.1
1,277
package com.stek101.projectzulu.common.core; /** * For usage see: {@link Pair} */ public class PairDirectoryFile<K, V> { private final K directory; private final V file; public static <K, V> PairDirectoryFile<K, V> createPair(K directory, V file) { return new PairDirectoryFile<K, V>(directory, file); } public PairDirectoryFile(K directory, V file) { this.file = file; this.directory = directory; } public K getDirectory() { return directory; } public V getFile() { return file; } @Override public boolean equals(Object object){ if (! (object instanceof PairDirectoryFile)) { return false; } PairDirectoryFile pair = (PairDirectoryFile)object; return directory.equals(pair.directory) && file.equals(pair.file); } @Override public int hashCode(){ return 7 * directory.hashCode() + 13 * file.hashCode(); } }
soultek101/projectzulu1.7.10
src/main/java/com/stek101/projectzulu/common/core/PairDirectoryFile.java
Java
lgpl-2.1
1,073
using System; namespace InSimDotNet.Packets { /// <summary> /// Message to connection packet. /// </summary> /// <remarks> /// Used to send a message to a specific connection or player (can only be used on hosts). /// </remarks> public class IS_MTC : IPacket, ISendable { /// <summary> /// Gets the size of the packet. /// </summary> public int Size { get; private set; } /// <summary> /// Gets the type of the packet. /// </summary> public PacketType Type { get; private set; } /// <summary> /// Gets or sets the request ID. /// </summary> public byte ReqI { get; set; } /// <summary> /// Gets or sets the sound effect. /// </summary> public MessageSound Sound { get; set; } /// <summary> /// Gets or sets the unique ID of the connection to send the message to (0 = host / 255 = all). /// </summary> public byte UCID { get; set; } /// <summary> /// Gets or sets the unique ID of the player to send the message to (if 0 use UCID). /// </summary> public byte PLID { get; set; } /// <summary> /// Gets or sets the message to send. /// </summary> public string Msg { get; set; } /// <summary> /// Creates a new message to connection packet. /// </summary> public IS_MTC() { Size = 8; Type = PacketType.ISP_MTC; Msg = String.Empty; } /// <summary> /// Returns the packet data. /// </summary> /// <returns>The packet data.</returns> public byte[] GetBuffer() { // Encode string first so we can figure out the packet size. byte[] buffer = new byte[128]; int length = LfsEncoding.Current.GetBytes(Msg, buffer, 0, 128); // Get the packet size (MTC needs trailing zero). Size = (byte)(8 + Math.Min(length + (4 - (length % 4)), 128)); PacketWriter writer = new PacketWriter(Size); writer.WriteSize(Size); writer.Write((byte)Type); writer.Write(ReqI); writer.Write((byte)Sound); writer.Write(UCID); writer.Write(PLID); writer.Skip(2); writer.Write(buffer, length); return writer.GetBuffer(); } } }
alexmcbride/insimdotnet
InSimDotNet/Packets/IS_MTC.cs
C#
lgpl-2.1
2,537
package fastSim.data; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; //import fanweizhu.fastSim.util.Config; //import fanweizhu.fastSim.util.IndexManager; //import fanweizhu.fastSim.util.KeyValuePair; //import fanweizhu.fastSim.util.MapCapacity; import fastSim.util.*; import fastSim.util.io.DataReader; import fastSim.util.io.DataWriter; public class PrimeSim implements Serializable{ /** * */ private static final long serialVersionUID = -7028575305146090045L; private List<Integer> hubs; protected Map<Integer, Map<Integer,Double>> map; protected boolean outG; protected List<Integer> meetingNodes; /*public PrimeSim(int capacity) { super(capacity); hubs = new ArrayList<Integer>(); }*/ public PrimeSim() { map = new HashMap<Integer, Map<Integer,Double>>(); hubs = new ArrayList<Integer>(); meetingNodes = new ArrayList<Integer>(); } public PrimeSim(int numNodes) { //need to change MapCapacity when double->Map? map = new HashMap<Integer, Map<Integer,Double>>(MapCapacity.compute(numNodes)); hubs = new ArrayList<Integer>(); } public Set<Integer> getLengths(){ return map.keySet(); } public int numHubs() { return hubs.size(); } public int numLength(){ return map.size(); } public Map<Integer,Map<Integer,Double>> getMap(){ return map; } public int getHubId(int index) { return hubs.get(index); } public List<Integer> getMeetingNodes(){ return meetingNodes; } public void addNewNode(Node h, String simType){ h.isVisited = true; if(h.isHub) hubs.add(h.id); if(simType=="in" && h.out.size()>1) //store meeting nodes for ingraphs //meetingnodes refer to >1 nodes (descendants) meetingNodes.add(h.id); } public void set(int l, Node n, double value) { // if (n.isVisited == false){ // if (n.isHub) // hubs.add(n.id); // if (graphType=="in" && n.in.size()>1) // meetingNodes.add(n.id); // } // Map<Integer, Double> nodesVal; if (map.get(l)!= null) { nodesVal = map.get(l); nodesVal.put(n.id, value); map.put(l, nodesVal); } else { nodesVal = new HashMap<Integer,Double>(); nodesVal.put(n.id, value); map.put(l, nodesVal); } } public void set(int l, Map<Integer,Double> nodeValuePairs){ //System.out.println(l); Map<Integer, Double> nodesVal = map.get(l); // for(Integer i:nodeValuePairs.keySet()) { // System.out.println("PS node: "+ i + " rea: " +nodeValuePairs.get(i)); // } if(nodesVal == null) { map.put(l, nodeValuePairs); } else{ System.out.println("####PrimeSim line108: should not go to here."); nodesVal.putAll(nodeValuePairs); map.put(l, nodesVal); } //System.out.println("length_Test:" + l + " Map_Size:" + map.get(l).size()); // for(Integer i: map.get(l).keySet()) // System.out.println(map.get(l).get(i)); } public long computeStorageInBytes() { long nodeIdSize = (1 + hubs.size()) * 4; long mapSize = (1 + map.size()) * 4 + map.size() * 8; return nodeIdSize + mapSize; } public String getCountInfo() { //int graphSize = map.size(); int hubSize = hubs.size(); int meetingNodesSize = meetingNodes.size(); return "hub size: " + hubSize + " meetingNodesSize: " + meetingNodesSize ; } public void trim(double clip) { Map<Integer, Map<Integer,Double>> newMap = new HashMap<Integer, Map<Integer,Double>>(); List<Integer> newHublist = new ArrayList<Integer>(); List<Integer> newXlist = new ArrayList<Integer>(); for (int l: map.keySet()){ Map<Integer, Double> pairMap =map.get(l); Map<Integer, Double> newPairs = new HashMap<Integer, Double>(); for (int nid: pairMap.keySet()){ double score = pairMap.get(nid); if (score > clip){ newPairs.put(nid, score); if(hubs.contains(nid) && !newHublist.contains(nid)) newHublist.add(nid); if(meetingNodes.contains(nid) && !newXlist.contains(nid)) newXlist.add(nid); } } newMap.put(l, newPairs); } this.map = newMap; this.hubs = newHublist; this.meetingNodes = newXlist; } public void saveToDisk(int id,String type,boolean doTrim) throws Exception { String path = ""; if(type == "out") //path = "./outSim/" + Integer.toString(id); path = IndexManager.getIndexDeepDir() + "out/" +Integer.toString(id); else if(type == "in") //path = "./inSim/" + Integer.toString(id); path = IndexManager.getIndexDeepDir() + "in/" +Integer.toString(id); else{ System.out.println("Type of prime graph should be either out or in."); System.exit(0); } // System.out.println(path+"/"+id); DataWriter out = new DataWriter(path); if (doTrim) trim(Config.clip); out.writeInteger(hubs.size()); for (int i : hubs) { out.writeInteger(i); } out.writeInteger(meetingNodes.size()); for(int i: meetingNodes){ out.writeInteger(i); } out.writeInteger(map.size()); for(int i=0; i<map.size();i++){ int pairNum = map.get(i).size(); Map<Integer,Double> pairMap = map.get(i); out.writeInteger(pairNum); for(int j: pairMap.keySet()){ out.writeInteger(j); out.writeDouble(pairMap.get(j)); } } out.close(); /*//test: read all the content DataReader in = new DataReader(path); while(true){ double oneNum =in.readDouble(); if (oneNum == -1.11) break; System.out.print(oneNum+"\t"); } System.out.println(); in.close();*/ } public void loadFromDisk(int id,String type) throws Exception { String path = ""; if(type == "out") path = IndexManager.getIndexDeepDir() + "out/" + Integer.toString(id); else if(type == "in") path = IndexManager.getIndexDeepDir() + "in/" + Integer.toString(id); else { System.out.println("Type of prime graph should be either out or in."); System.exit(0); } //============== DataReader in = new DataReader(path); int n = in.readInteger(); this.hubs = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) this.hubs.add(in.readInteger()); int numM = in.readInteger(); this.meetingNodes=new ArrayList<Integer>(numM); for(int i =0; i<numM; i++) this.meetingNodes.add(in.readInteger()); int numL = in.readInteger(); for(int i=0; i<numL; i++){ int numPair = in.readInteger(); Map<Integer,Double> pairMap = new HashMap<Integer, Double>(); for(int j=0; j<numPair; j++){ int nodeId = in.readInteger(); double nodeScore = in.readDouble(); pairMap.put(nodeId, nodeScore); } this.map.put(i, pairMap); } in.close(); } public PrimeSim duplicate() { // TODO Auto-generated method stub PrimeSim sim = new PrimeSim(); sim.map.putAll(this.map); return sim; } public void addFrom(PrimeSim nextOut, Map<Integer, Double> oneHubValue) { // TODO Auto-generated method stub for (int lenToHub : oneHubValue.keySet()){ double hubScoreoflen = oneHubValue.get(lenToHub); for (int lenFromHub : nextOut.getMap().keySet()){ if(lenFromHub == 0){ // the new score of hub (over length==0) is just the score on prime graph continue; } int newLen = lenToHub + lenFromHub; if (!this.getMap().containsKey(newLen)) this.getMap().put(newLen, new HashMap<Integer,Double>()); for(int toNode: nextOut.getMap().get(lenFromHub).keySet()){ double oldValue = this.getMap().get(newLen).keySet() .contains(toNode) ? this.getMap().get(newLen).get(toNode): 0.0; //System.out.println(oldValue); double newValue = hubScoreoflen *nextOut.getMap().get(lenFromHub).get(toNode); // //added aug-29 // if (newValue<Config.epsilon) // continue; this.getMap().get(newLen).put(toNode, oldValue + newValue) ; // PrintInfor.printDoubleMap(this.getMap(), "assemble simout of the hub at length: " + lenFromHub +" node: "+ toNode ); // System.out.println(this.getMap()); } } } } public void addMeetingNodes(List<Integer> nodes){ for (int nid: nodes){ if (!this.meetingNodes.contains(nid)) this.meetingNodes.add(nid); } //System.out.println("====PrimeSim: line 195: meetingnodes Size " + this.meetingNodes.size()); } }
fastsim2016/FastSim
fastSim_SS_pre/src/fastSim/data/PrimeSim.java
Java
lgpl-2.1
8,347
/* Copyright (c) 2013-2014 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Gabriel Roldan (Boundless) - initial implementation */ package org.locationtech.geogig.geotools.data; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import org.eclipse.jdt.annotation.Nullable; import org.geotools.data.DataStore; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.store.ContentDataStore; import org.geotools.data.store.ContentEntry; import org.geotools.data.store.ContentState; import org.geotools.feature.NameImpl; import org.locationtech.geogig.data.FindFeatureTypeTrees; import org.locationtech.geogig.model.ObjectId; import org.locationtech.geogig.model.Ref; import org.locationtech.geogig.model.RevObject.TYPE; import org.locationtech.geogig.model.RevTree; import org.locationtech.geogig.model.SymRef; import org.locationtech.geogig.plumbing.ForEachRef; import org.locationtech.geogig.plumbing.RefParse; import org.locationtech.geogig.plumbing.RevParse; import org.locationtech.geogig.plumbing.TransactionBegin; import org.locationtech.geogig.porcelain.AddOp; import org.locationtech.geogig.porcelain.CheckoutOp; import org.locationtech.geogig.porcelain.CommitOp; import org.locationtech.geogig.repository.Context; import org.locationtech.geogig.repository.GeogigTransaction; import org.locationtech.geogig.repository.NodeRef; import org.locationtech.geogig.repository.Repository; import org.locationtech.geogig.repository.WorkingTree; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.Name; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; /** * A GeoTools {@link DataStore} that serves and edits {@link SimpleFeature}s in a geogig repository. * <p> * Multiple instances of this kind of data store may be created against the same repository, * possibly working against different {@link #setHead(String) heads}. * <p> * A head is any commit in GeoGig. If a head has a branch pointing at it then the store allows * transactions, otherwise no data modifications may be made. * * A branch in Geogig is a separate line of history that may or may not share a common ancestor with * another branch. In the later case the branch is called "orphan" and by convention the default * branch is called "master", which is created when the geogig repo is first initialized, but does * not necessarily exist. * <p> * Every read operation (like in {@link #getFeatureSource(Name)}) reads committed features out of * the configured "head" branch. Write operations are only supported if a {@link Transaction} is * set, in which case a {@link GeogigTransaction} is tied to the geotools transaction by means of a * {@link GeogigTransactionState}. During the transaction, read operations will read from the * transaction's {@link WorkingTree} in order to "see" features that haven't been committed yet. * <p> * When the transaction is committed, the changes made inside that transaction are merged onto the * actual repository. If any other change was made to the repository meanwhile, a rebase will be * attempted, and the transaction commit will fail if the rebase operation finds any conflict. This * provides for optimistic locking and reduces thread contention. * */ public class GeoGigDataStore extends ContentDataStore implements DataStore { private final Repository geogig; /** @see #setHead(String) */ private String refspec; /** When the configured head is not a branch, we disallow transactions */ private boolean allowTransactions = true; public GeoGigDataStore(Repository geogig) { super(); Preconditions.checkNotNull(geogig); this.geogig = geogig; } @Override public void dispose() { super.dispose(); geogig.close(); } /** * Instructs the datastore to operate against the specified refspec, or against the checked out * branch, whatever it is, if the argument is {@code null}. * * Editing capabilities are disabled if the refspec is not a local branch. * * @param refspec the name of the branch to work against, or {@code null} to default to the * currently checked out branch * @see #getConfiguredBranch() * @see #getOrFigureOutHead() * @throws IllegalArgumentException if {@code refspec} is not null and no such commit exists in * the repository */ public void setHead(@Nullable final String refspec) throws IllegalArgumentException { if (refspec == null) { allowTransactions = true; // when no branch name is set we assume we should make // transactions against the current HEAD } else { final Context context = getCommandLocator(null); Optional<ObjectId> rev = context.command(RevParse.class).setRefSpec(refspec).call(); if (!rev.isPresent()) { throw new IllegalArgumentException("Bad ref spec: " + refspec); } Optional<Ref> branchRef = context.command(RefParse.class).setName(refspec).call(); if (branchRef.isPresent()) { Ref ref = branchRef.get(); if (ref instanceof SymRef) { ref = context.command(RefParse.class).setName(((SymRef) ref).getTarget()).call() .orNull(); } Preconditions.checkArgument(ref != null, "refSpec is a dead symref: " + refspec); if (ref.getName().startsWith(Ref.HEADS_PREFIX)) { allowTransactions = true; } else { allowTransactions = false; } } else { allowTransactions = false; } } this.refspec = refspec; } public String getOrFigureOutHead() { String branch = getConfiguredHead(); if (branch != null) { return branch; } return getCheckedOutBranch(); } public Repository getGeogig() { return geogig; } /** * @return the configured refspec of the commit this datastore works against, or {@code null} if * no head in particular has been set, meaning the data store works against whatever the * currently checked out branch is. */ @Nullable public String getConfiguredHead() { return this.refspec; } /** * @return whether or not we can support transactions against the configured head */ public boolean isAllowTransactions() { return this.allowTransactions; } /** * @return the name of the currently checked out branch in the repository, not necessarily equal * to {@link #getConfiguredBranch()}, or {@code null} in the (improbable) case HEAD is * on a dettached state (i.e. no local branch is currently checked out) */ @Nullable public String getCheckedOutBranch() { Optional<Ref> head = getCommandLocator(null).command(RefParse.class).setName(Ref.HEAD) .call(); if (!head.isPresent()) { return null; } Ref headRef = head.get(); if (!(headRef instanceof SymRef)) { return null; } String refName = ((SymRef) headRef).getTarget(); Preconditions.checkState(refName.startsWith(Ref.HEADS_PREFIX)); String branchName = refName.substring(Ref.HEADS_PREFIX.length()); return branchName; } public ImmutableList<String> getAvailableBranches() { ImmutableSet<Ref> heads = getCommandLocator(null).command(ForEachRef.class) .setPrefixFilter(Ref.HEADS_PREFIX).call(); List<String> list = Lists.newArrayList(Collections2.transform(heads, (ref) -> { String branchName = ref.getName().substring(Ref.HEADS_PREFIX.length()); return branchName; })); Collections.sort(list); return ImmutableList.copyOf(list); } public Context getCommandLocator(@Nullable Transaction transaction) { Context commandLocator = null; if (transaction != null && !Transaction.AUTO_COMMIT.equals(transaction)) { GeogigTransactionState state; state = (GeogigTransactionState) transaction.getState(GeogigTransactionState.class); Optional<GeogigTransaction> geogigTransaction = state.getGeogigTransaction(); if (geogigTransaction.isPresent()) { commandLocator = geogigTransaction.get(); } } if (commandLocator == null) { commandLocator = geogig.context(); } return commandLocator; } public Name getDescriptorName(NodeRef treeRef) { Preconditions.checkNotNull(treeRef); Preconditions.checkArgument(TYPE.TREE.equals(treeRef.getType())); Preconditions.checkArgument(!treeRef.getMetadataId().isNull(), "NodeRef '%s' is not a feature type reference", treeRef.path()); return new NameImpl(getNamespaceURI(), NodeRef.nodeFromPath(treeRef.path())); } public NodeRef findTypeRef(Name typeName, @Nullable Transaction tx) { Preconditions.checkNotNull(typeName); final String localName = typeName.getLocalPart(); final List<NodeRef> typeRefs = findTypeRefs(tx); Collection<NodeRef> matches = Collections2.filter(typeRefs, new Predicate<NodeRef>() { @Override public boolean apply(NodeRef input) { return NodeRef.nodeFromPath(input.path()).equals(localName); } }); switch (matches.size()) { case 0: throw new NoSuchElementException( String.format("No tree ref matched the name: %s", localName)); case 1: return matches.iterator().next(); default: throw new IllegalArgumentException(String .format("More than one tree ref matches the name %s: %s", localName, matches)); } } @Override protected ContentState createContentState(ContentEntry entry) { return new ContentState(entry); } @Override protected ImmutableList<Name> createTypeNames() throws IOException { List<NodeRef> typeTrees = findTypeRefs(Transaction.AUTO_COMMIT); return ImmutableList .copyOf(Collections2.transform(typeTrees, (ref) -> getDescriptorName(ref))); } private List<NodeRef> findTypeRefs(@Nullable Transaction tx) { final String rootRef = getRootRef(tx); Context commandLocator = getCommandLocator(tx); List<NodeRef> typeTrees = commandLocator.command(FindFeatureTypeTrees.class) .setRootTreeRef(rootRef).call(); return typeTrees; } String getRootRef(@Nullable Transaction tx) { final String rootRef; if (null == tx || Transaction.AUTO_COMMIT.equals(tx)) { rootRef = getOrFigureOutHead(); } else { rootRef = Ref.WORK_HEAD; } return rootRef; } @Override protected GeogigFeatureStore createFeatureSource(ContentEntry entry) throws IOException { return new GeogigFeatureStore(entry); } /** * Creates a new feature type tree on the {@link #getOrFigureOutHead() current branch}. * <p> * Implementation detail: the operation is the homologous to starting a transaction, checking * out the current/configured branch, creating the type tree inside the transaction, issueing a * geogig commit, and committing the transaction for the created tree to be merged onto the * configured branch. */ @Override public void createSchema(SimpleFeatureType featureType) throws IOException { if (!allowTransactions) { throw new IllegalStateException("Configured head " + refspec + " is not a branch; transactions are not supported."); } GeogigTransaction tx = getCommandLocator(null).command(TransactionBegin.class).call(); boolean abort = false; try { String treePath = featureType.getName().getLocalPart(); // check out the datastore branch on the transaction space final String branch = getOrFigureOutHead(); tx.command(CheckoutOp.class).setForce(true).setSource(branch).call(); // now we can use the transaction working tree with the correct branch checked out WorkingTree workingTree = tx.workingTree(); workingTree.createTypeTree(treePath, featureType); tx.command(AddOp.class).addPattern(treePath).call(); tx.command(CommitOp.class).setMessage("Created feature type tree " + treePath).call(); tx.commit(); } catch (IllegalArgumentException alreadyExists) { abort = true; throw new IOException(alreadyExists.getMessage(), alreadyExists); } catch (Exception e) { abort = true; throw Throwables.propagate(e); } finally { if (abort) { tx.abort(); } } } // Deliberately leaving the @Override annotation commented out so that the class builds // both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x) // @Override public void removeSchema(Name name) throws IOException { throw new UnsupportedOperationException( "removeSchema not yet supported by geogig DataStore"); } // Deliberately leaving the @Override annotation commented out so that the class builds // both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x) // @Override public void removeSchema(String name) throws IOException { throw new UnsupportedOperationException( "removeSchema not yet supported by geogig DataStore"); } public static enum ChangeType { ADDED, REMOVED, CHANGED_NEW, CHANGED_OLD; } /** * Builds a FeatureSource (read-only) that fetches features out of the differences between two * root trees: a provided tree-ish as the left side of the comparison, and the datastore's * configured HEAD as the right side of the comparison. * <p> * E.g., to get all features of a given feature type that were removed between a given commit * and its parent: * * <pre> * <code> * String commitId = ... * GeoGigDataStore store = new GeoGigDataStore(geogig); * store.setHead(commitId); * FeatureSource removed = store.getDiffFeatureSource("roads", commitId + "~1", ChangeType.REMOVED); * </code> * </pre> * * @param typeName the feature type name to look up a type tree for in the datastore's current * {@link #getOrFigureOutHead() HEAD} * @param oldRoot a tree-ish string that resolves to the ROOT tree to be used as the left side * of the diff * @param changeType the type of change between {@code oldRoot} and {@link #getOrFigureOutHead() * head} to pick as the features to return. * @return a feature source whose features are computed out of the diff between the feature type * diffs between the given {@code oldRoot} and the datastore's * {@link #getOrFigureOutHead() HEAD}. */ public SimpleFeatureSource getDiffFeatureSource(final String typeName, final String oldRoot, final ChangeType changeType) throws IOException { Preconditions.checkNotNull(typeName, "typeName"); Preconditions.checkNotNull(oldRoot, "oldRoot"); Preconditions.checkNotNull(changeType, "changeType"); final Name name = name(typeName); final ContentEntry entry = ensureEntry(name); GeogigFeatureSource featureSource = new GeogigFeatureSource(entry); featureSource.setTransaction(Transaction.AUTO_COMMIT); featureSource.setChangeType(changeType); if (ObjectId.NULL.toString().equals(oldRoot) || RevTree.EMPTY_TREE_ID.toString().equals(oldRoot)) { featureSource.setOldRoot(null); } else { featureSource.setOldRoot(oldRoot); } return featureSource; } }
jodygarnett/GeoGig
src/datastore/src/main/java/org/locationtech/geogig/geotools/data/GeoGigDataStore.java
Java
lgpl-2.1
17,024
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2003-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * 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. */ package org.geotools.data.vpf.exc; /** * Class VPFHeaderFormatException.java is responsible for * * <p>Created: Tue Jan 21 15:12:10 2003 * * @author <a href="mailto:kobit@users.sourceforge.net">Artur Hefczyc</a> * @source $URL$ * @version 1.0.0 */ public class VPFHeaderFormatException extends VPFDataException { /** serialVersionUID */ private static final long serialVersionUID = 4680952037855445222L; /** Creates a new VPFHeaderFormatException object. */ public VPFHeaderFormatException() { super(); } /** * Creates a new VPFHeaderFormatException object. * * @param message DOCUMENT ME! */ public VPFHeaderFormatException(String message) { super(message); } } // VPFHeaderFormatException
geotools/geotools
modules/unsupported/vpf/src/main/java/org/geotools/data/vpf/exc/VPFHeaderFormatException.java
Java
lgpl-2.1
1,418
#!/usr/bin/env python import sys import gobject import dbus.mainloop.glib dbus.mainloop.glib.DBusGMainLoop(set_as_default = True) import telepathy DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties' def get_registry(): reg = telepathy.client.ManagerRegistry() reg.LoadManagers() return reg def get_connection_manager(reg): cm = reg.GetManager('bluewire') return cm class Action(object): def __init__(self): self._action = None def queue_action(self): pass def append_action(self, action): assert self._action is None self._action = action def get_next_action(self): assert self._action is not None return self._action def _on_done(self): if self._action is None: return self._action.queue_action() def _on_error(self, error): print error def _on_generic_message(self, *args): pass class DummyAction(Action): def queue_action(self): gobject.idle_add(self._on_done) class QuitLoop(Action): def __init__(self, loop): super(QuitLoop, self).__init__() self._loop = loop def queue_action(self): self._loop.quit() class DisplayParams(Action): def __init__(self, cm): super(DisplayParams, self).__init__() self._cm = cm def queue_action(self): self._cm[telepathy.interfaces.CONN_MGR_INTERFACE].GetParameters( 'bluetooth, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, params): print "Connection Parameters:" for name, flags, signature, default in params: print "\t%s (%s)" % (name, signature), if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_REQUIRED: print "required", if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_REGISTER: print "register", if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_SECRET: print "secret", if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_DBUS_PROPERTY: print "dbus-property", if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_HAS_DEFAULT: print "has-default(%s)" % default, print "" super(DisplayParams, self)._on_done() class RequestConnection(Action): def __init__(self, cm, username, password, forward): super(RequestConnection, self).__init__() self._cm = cm self._conn = None self._serviceName = None self._username = username self._password = password self._forward = forward @property def conn(self): return self._conn @property def serviceName(self): return self._serviceName def queue_action(self): self._cm[telepathy.server.CONNECTION_MANAGER].RequestConnection( 'bluetooth", { 'account': self._username, 'password': self._password, 'forward': self._forward, }, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, busName, objectPath): self._serviceName = busName self._conn = telepathy.client.Connection(busName, objectPath) super(RequestConnection, self)._on_done() class Connect(Action): def __init__(self, connAction): super(Connect, self).__init__() self._connAction = connAction def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION].connect_to_signal( 'StatusChanged', self._on_change, ) self._connAction.conn[telepathy.server.CONNECTION].Connect( reply_handler = self._on_generic_message, error_handler = self._on_error, ) def _on_done(self): super(Connect, self)._on_done() def _on_change(self, status, reason): if status == telepathy.constants.CONNECTION_STATUS_DISCONNECTED: print "Disconnected!" self._conn = None elif status == telepathy.constants.CONNECTION_STATUS_CONNECTED: print "Connected" self._on_done() elif status == telepathy.constants.CONNECTION_STATUS_CONNECTING: print "Connecting" else: print "Status: %r" % status class SimplePresenceOptions(Action): def __init__(self, connAction): super(SimplePresenceOptions, self).__init__() self._connAction = connAction def queue_action(self): self._connAction.conn[DBUS_PROPERTIES].Get( telepathy.server.CONNECTION_INTERFACE_SIMPLE_PRESENCE, 'Statuses', reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, statuses): print "\tAvailable Statuses" for (key, value) in statuses.iteritems(): print "\t\t - %s" % key super(SimplePresenceOptions, self)._on_done() class NullHandle(object): @property def handle(self): return 0 @property def handles(self): return [] class UserHandle(Action): def __init__(self, connAction): super(UserHandle, self).__init__() self._connAction = connAction self._handle = None @property def handle(self): return self._handle @property def handles(self): return [self._handle] def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION].GetSelfHandle( reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, handle): self._handle = handle super(UserHandle, self)._on_done() class RequestHandle(Action): def __init__(self, connAction, handleType, handleNames): super(RequestHandle, self).__init__() self._connAction = connAction self._handle = None self._handleType = handleType self._handleNames = handleNames @property def handle(self): return self._handle @property def handles(self): return [self._handle] def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION].RequestHandles( self._handleType, self._handleNames, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, handles): self._handle = handles[0] super(RequestHandle, self)._on_done() class RequestChannel(Action): def __init__(self, connAction, handleAction, channelType, handleType): super(RequestChannel, self).__init__() self._connAction = connAction self._handleAction = handleAction self._channel = None self._channelType = channelType self._handleType = handleType @property def channel(self): return self._channel def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION].RequestChannel( self._channelType, self._handleType, self._handleAction.handle, True, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, channelObjectPath): self._channel = telepathy.client.Channel(self._connAction.serviceName, channelObjectPath) super(RequestChannel, self)._on_done() class EnsureChannel(Action): def __init__(self, connAction, channelType, handleType, handleId): super(EnsureChannel, self).__init__() self._connAction = connAction self._channel = None self._channelType = channelType self._handleType = handleType self._handleId = handleId self._handle = None @property def channel(self): return self._channel @property def handle(self): return self._handle @property def handles(self): return [self._handle] def queue_action(self): properties = { telepathy.server.CHANNEL_INTERFACE+".ChannelType": self._channelType, telepathy.server.CHANNEL_INTERFACE+".TargetHandleType": self._handleType, telepathy.server.CHANNEL_INTERFACE+".TargetID": self._handleId, } self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_REQUESTS].EnsureChannel( properties, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, yours, channelObjectPath, properties): print "Create?", not not yours print "Path:", channelObjectPath print "Properties:", properties self._channel = telepathy.client.Channel(self._connAction.serviceName, channelObjectPath) self._handle = properties[telepathy.server.CHANNEL_INTERFACE+".TargetHandle"] super(EnsureChannel, self)._on_done() class CloseChannel(Action): def __init__(self, connAction, chanAction): super(CloseChannel, self).__init__() self._connAction = connAction self._chanAction = chanAction self._handles = [] def queue_action(self): self._chanAction.channel[telepathy.server.CHANNEL].Close( reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self): super(CloseChannel, self)._on_done() class ContactHandles(Action): def __init__(self, connAction, chanAction): super(ContactHandles, self).__init__() self._connAction = connAction self._chanAction = chanAction self._handles = [] @property def handles(self): return self._handles def queue_action(self): self._chanAction.channel[DBUS_PROPERTIES].Get( telepathy.server.CHANNEL_INTERFACE_GROUP, 'Members', reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, handles): self._handles = list(handles) super(ContactHandles, self)._on_done() class SimplePresenceStatus(Action): def __init__(self, connAction, handleAction): super(SimplePresenceStatus, self).__init__() self._connAction = connAction self._handleAction = handleAction def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_SIMPLE_PRESENCE].GetPresences( self._handleAction.handles, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, aliases): print "\tPresences:" for hid, (presenceType, presence, presenceMessage) in aliases.iteritems(): print "\t\t%s:" % hid, presenceType, presence, presenceMessage super(SimplePresenceStatus, self)._on_done() class SetSimplePresence(Action): def __init__(self, connAction, status, message): super(SetSimplePresence, self).__init__() self._connAction = connAction self._status = status self._message = message def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_SIMPLE_PRESENCE].SetPresence( self._status, self._message, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self): super(SetSimplePresence, self)._on_done() class Aliases(Action): def __init__(self, connAction, handleAction): super(Aliases, self).__init__() self._connAction = connAction self._handleAction = handleAction def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_ALIASING].RequestAliases( self._handleAction.handles, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, aliases): print "\tAliases:" for h, alias in zip(self._handleAction.handles, aliases): print "\t\t", h, alias super(Aliases, self)._on_done() class Call(Action): def __init__(self, connAction, chanAction, handleAction): super(Call, self).__init__() self._connAction = connAction self._chanAction = chanAction self._handleAction = handleAction def queue_action(self): self._chanAction.channel[telepathy.server.CHANNEL_TYPE_STREAMED_MEDIA].RequestStreams( self._handleAction.handle, [telepathy.constants.MEDIA_STREAM_TYPE_AUDIO], reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self, handle): print "Call started" super(Call, self)._on_done() class SendText(Action): def __init__(self, connAction, chanAction, handleAction, messageType, message): super(SendText, self).__init__() self._connAction = connAction self._chanAction = chanAction self._handleAction = handleAction self._messageType = messageType self._message = message def queue_action(self): self._chanAction.channel[telepathy.server.CHANNEL_TYPE_TEXT].Send( self._messageType, self._message, reply_handler = self._on_done, error_handler = self._on_error, ) def _on_done(self,): print "Message sent" super(SendText, self)._on_done() class Sleep(Action): def __init__(self, length): super(Sleep, self).__init__() self._length = length def queue_action(self): gobject.timeout_add(self._length, self._on_done) class Block(Action): def __init__(self): super(Block, self).__init__() def queue_action(self): print "Blocking" def _on_done(self): #super(SendText, self)._on_done() pass class Disconnect(Action): def __init__(self, connAction): super(Disconnect, self).__init__() self._connAction = connAction def queue_action(self): self._connAction.conn[telepathy.server.CONNECTION].Disconnect( reply_handler = self._on_done, error_handler = self._on_error, ) if __name__ == '__main__': loop = gobject.MainLoop() reg = get_registry() cm = get_connection_manager(reg) nullHandle = NullHandle() dummy = DummyAction() firstAction = dummy lastAction = dummy if True: dp = DisplayParams(cm) lastAction.append_action(dp) lastAction = lastAction.get_next_action() if True: username = sys.argv[1] password = sys.argv[2] forward = sys.argv[3] reqcon = RequestConnection(cm, username, password, forward) lastAction.append_action(reqcon) lastAction = lastAction.get_next_action() if False: reqcon = RequestConnection(cm, username, password, forward) lastAction.append_action(reqcon) lastAction = lastAction.get_next_action() con = Connect(reqcon) lastAction.append_action(con) lastAction = lastAction.get_next_action() if True: spo = SimplePresenceOptions(reqcon) lastAction.append_action(spo) lastAction = lastAction.get_next_action() if True: uh = UserHandle(reqcon) lastAction.append_action(uh) lastAction = lastAction.get_next_action() ua = Aliases(reqcon, uh) lastAction.append_action(ua) lastAction = lastAction.get_next_action() sps = SimplePresenceStatus(reqcon, uh) lastAction.append_action(sps) lastAction = lastAction.get_next_action() if False: setdnd = SetSimplePresence(reqcon, "dnd", "") lastAction.append_action(setdnd) lastAction = lastAction.get_next_action() sps = SimplePresenceStatus(reqcon, uh) lastAction.append_action(sps) lastAction = lastAction.get_next_action() setdnd = SetSimplePresence(reqcon, "available", "") lastAction.append_action(setdnd) lastAction = lastAction.get_next_action() sps = SimplePresenceStatus(reqcon, uh) lastAction.append_action(sps) lastAction = lastAction.get_next_action() if False: sl = Sleep(10 * 1000) lastAction.append_action(sl) lastAction = lastAction.get_next_action() if False: rclh = RequestHandle(reqcon, telepathy.HANDLE_TYPE_LIST, ["subscribe"]) lastAction.append_action(rclh) lastAction = lastAction.get_next_action() rclc = RequestChannel( reqcon, rclh, telepathy.CHANNEL_TYPE_CONTACT_LIST, telepathy.HANDLE_TYPE_LIST, ) lastAction.append_action(rclc) lastAction = lastAction.get_next_action() ch = ContactHandles(reqcon, rclc) lastAction.append_action(ch) lastAction = lastAction.get_next_action() ca = Aliases(reqcon, ch) lastAction.append_action(ca) lastAction = lastAction.get_next_action() if True: accountNumber = sys.argv[4] enChan = EnsureChannel(reqcon, telepathy.CHANNEL_TYPE_TEXT, telepathy.HANDLE_TYPE_CONTACT, accountNumber) lastAction.append_action(enChan) lastAction = lastAction.get_next_action() sendDebugtext = SendText(reqcon, enChan, enChan, telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, "Boo!") lastAction.append_action(sendDebugtext) lastAction = lastAction.get_next_action() if False: rch = RequestHandle(reqcon, telepathy.HANDLE_TYPE_CONTACT, ["18005558355"]) #(1-800-555-TELL) lastAction.append_action(rch) lastAction = lastAction.get_next_action() # making a phone call if True: smHandle = rch smHandleType = telepathy.HANDLE_TYPE_CONTACT else: smHandle = nullHandle smHandleType = telepathy.HANDLE_TYPE_NONE rsmc = RequestChannel( reqcon, smHandle, telepathy.CHANNEL_TYPE_STREAMED_MEDIA, smHandleType, ) lastAction.append_action(rsmc) lastAction = lastAction.get_next_action() if False: call = Call(reqcon, rsmc, rch) lastAction.append_action(call) lastAction = lastAction.get_next_action() # sending a text rtc = RequestChannel( reqcon, rch, telepathy.CHANNEL_TYPE_TEXT, smHandleType, ) lastAction.append_action(rtc) lastAction = lastAction.get_next_action() if True: closechan = CloseChannel(reqcon, rtc) lastAction.append_action(closechan) lastAction = lastAction.get_next_action() rtc = RequestChannel( reqcon, rch, telepathy.CHANNEL_TYPE_TEXT, smHandleType, ) lastAction.append_action(rtc) lastAction = lastAction.get_next_action() if False: sendtext = SendText(reqcon, rtc, rch, telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, "Boo!") lastAction.append_action(sendtext) lastAction = lastAction.get_next_action() if False: bl = Block() lastAction.append_action(bl) lastAction = lastAction.get_next_action() if False: sl = Sleep(30 * 1000) lastAction.append_action(sl) lastAction = lastAction.get_next_action() dis = Disconnect(reqcon) lastAction.append_action(dis) lastAction = lastAction.get_next_action() quitter = QuitLoop(loop) lastAction.append_action(quitter) lastAction = lastAction.get_next_action() firstAction.queue_action() loop.run()
epage/telepathy-bluewire
hand_tests/generic.py
Python
lgpl-2.1
17,072
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace Pango { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; #region Autogenerated code public partial class FontFace : GLib.Object { public FontFace (IntPtr raw) : base(raw) {} protected FontFace() : base(IntPtr.Zero) { CreateNativeObject (new string [0], new GLib.Value [0]); } [DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr pango_font_face_describe(IntPtr raw); public Pango.FontDescription Describe() { IntPtr raw_ret = pango_font_face_describe(Handle); Pango.FontDescription ret = raw_ret == IntPtr.Zero ? null : (Pango.FontDescription) GLib.Opaque.GetOpaque (raw_ret, typeof (Pango.FontDescription), true); return ret; } [DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr pango_font_face_get_face_name(IntPtr raw); public string FaceName { get { IntPtr raw_ret = pango_font_face_get_face_name(Handle); string ret = GLib.Marshaller.Utf8PtrToString (raw_ret); return ret; } } [DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr pango_font_face_get_type(); public static new GLib.GType GType { get { IntPtr raw_ret = pango_font_face_get_type(); GLib.GType ret = new GLib.GType(raw_ret); return ret; } } [DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern bool pango_font_face_is_synthesized(IntPtr raw); public bool IsSynthesized { get { bool raw_ret = pango_font_face_is_synthesized(Handle); bool ret = raw_ret; return ret; } } [DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void pango_font_face_list_sizes(IntPtr raw, out int sizes, out int n_sizes); public void ListSizes(out int sizes, out int n_sizes) { pango_font_face_list_sizes(Handle, out sizes, out n_sizes); } #endregion } }
akrisiun/gtk-sharp
pango/generated/Pango/FontFace.cs
C#
lgpl-2.1
2,141
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ia"> <context> <name>LxQtTaskButton</name> <message> <location filename="../lxqttaskbutton.cpp" line="367"/> <source>Application</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="400"/> <source>To &amp;Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="402"/> <source>&amp;All Desktops</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="410"/> <source>Desktop &amp;%1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="417"/> <source>&amp;To Current Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="426"/> <source>Ma&amp;ximize</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="433"/> <source>Maximize vertically</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="438"/> <source>Maximize horizontally</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="444"/> <source>&amp;Restore</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="448"/> <source>Mi&amp;nimize</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="454"/> <source>Roll down</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="460"/> <source>Roll up</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="468"/> <source>&amp;Layer</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="470"/> <source>Always on &amp;top</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="476"/> <source>&amp;Normal</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="482"/> <source>Always on &amp;bottom</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbutton.cpp" line="490"/> <source>&amp;Close</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LxQtTaskbarConfiguration</name> <message> <location filename="../lxqttaskbarconfiguration.ui" line="14"/> <source>Task Manager Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="20"/> <source>Taskbar Contents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="26"/> <source>Show windows from current desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="49"/> <source>Taskbar Appearance</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="65"/> <source>Minimum button width</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="88"/> <source>Auto&amp;rotate buttons when the panel is vertical</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="98"/> <source>Close on middle-click</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="36"/> <source>Show windows from all desktops</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.ui" line="55"/> <source>Button style</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.cpp" line="46"/> <source>Icon and text</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.cpp" line="47"/> <source>Only icon</source> <translation type="unfinished"></translation> </message> <message> <location filename="../lxqttaskbarconfiguration.cpp" line="48"/> <source>Only text</source> <translation type="unfinished"></translation> </message> </context> </TS>
npmiller/lxqt-panel
plugin-taskbar/translations/taskbar_ia.ts
TypeScript
lgpl-2.1
5,821
package compiler.ASTNodes.Operators; import compiler.ASTNodes.GeneralNodes.Node; import compiler.ASTNodes.GeneralNodes.UnaryNode; import compiler.ASTNodes.SyntaxNodes.ExprNode; import compiler.Visitors.AbstractVisitor; public class UnaryMinusNode extends ExprNode { public UnaryMinusNode(Node child) { super(child, null); } @Override public Object Accept(AbstractVisitor v) { return v.visit(this); } }
TobiasMorell/P4
Minecraft/src/main/java/compiler/ASTNodes/Operators/UnaryMinusNode.java
Java
lgpl-2.1
415
#include <QtGui> #include "btglobal.h" #include "btqlistdelegate.h" //#include <QMetaType> btQListDeletgate::btQListDeletgate(QObject *parent) : QItemDelegate(parent) { } QWidget *btQListDeletgate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { //qRegisterMetaType<btChildWeights>("btChildWeights"); //qRegisterMetaType<btParallelConditions>("btParallelConditions"); QComboBox *comboBox = new QComboBox(parent); comboBox->addItem("int", QVariant("int")); comboBox->addItem("QString", QVariant("QString")); comboBox->addItem("double", QVariant("double")); comboBox->addItem("QVariantList", QVariant("QVariantList")); //comboBox->addItem("btChildWeights", QVariant("btChildWeights")); comboBox->setCurrentIndex(comboBox->findData(index.data())); return comboBox; } void btQListDeletgate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString value = index.model()->data(index, Qt::EditRole).toString(); QComboBox *comboBox = static_cast<QComboBox*>(editor); comboBox->setCurrentIndex(comboBox->findText(value));//comboBox->findData(value)); } void btQListDeletgate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *comboBox = static_cast<QComboBox*>(editor); QString value = comboBox->currentText(); model->setData(index, value, Qt::EditRole); } void btQListDeletgate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); } #include "btqlistdelegate.moc"
pranavrc/gluon
smarts/editor/btqlistdelegate.cpp
C++
lgpl-2.1
1,655
/** * NativeFmod Project * * Want to use FMOD API (www.fmod.org) in the Java language ? NativeFmod is made for you. * Copyright © 2004-2007 Jérôme JOUVIE (Jouvieje) * * Created on 28 avr. 2004 * @version NativeFmod v3.4 (for FMOD v3.75) * @author Jérôme JOUVIE (Jouvieje) * * * WANT TO CONTACT ME ? * E-mail : * jerome.jouvie@gmail.com * My web sites : * http://jerome.jouvie.free.fr/ * * * INTRODUCTION * Fmod is an API (Application Programming Interface) that allow you to use music * and creating sound effects with a lot of sort of musics. * Fmod is at : * http://www.fmod.org/ * The reason of this project is that Fmod can't be used in Java direcly, so I've created * NativeFmod project. * * * GNU LESSER GENERAL PUBLIC LICENSE * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.jouvieje.Fmod.Structures; import org.jouvieje.Fmod.Misc.Pointer; /** * Structure defining the properties for a reverb source, related to a FSOUND channel. * For more indepth descriptions of the reverb properties under win32, please see the EAX3 * documentation at http://developer.creative.com/ under the 'downloads' section. * If they do not have the EAX3 documentation, then most information can be attained from * the EAX2 documentation, as EAX3 only adds some more parameters and functionality on top of * EAX2. * Note the default reverb properties are the same as the FSOUND_PRESET_GENERIC preset. * Note that integer values that typically range from -10,000 to 1000 are represented in * decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear. * PORTABILITY: Each member has the platform it supports in braces ie (win32/xbox). * Some reverb parameters are only supported in win32 and some only on xbox. If all parameters are set then * the reverb should product a similar effect on either platform. * Linux and FMODCE do not support the reverb api. * The numerical values listed below are the maximum, minimum and default values for each variable respectively. */ public class FSOUND_REVERB_CHANNELPROPERTIES extends Pointer { /** * Create a view of the <code>Pointer</code> object as a <code>FSOUND_REVERB_CHANNELPROPERTIES</code> object.<br> * This view is valid only if the memory holded by the <code>Pointer</code> holds a FSOUND_REVERB_CHANNELPROPERTIES object. */ public static FSOUND_REVERB_CHANNELPROPERTIES createView(Pointer pointer) { return new FSOUND_REVERB_CHANNELPROPERTIES(Pointer.getPointer(pointer)); } /** * Create a new <code>FSOUND_REVERB_CHANNELPROPERTIES</code>.<br> * The call <code>isNull()</code> on the object created will return false.<br> * <pre><code> FSOUND_REVERB_CHANNELPROPERTIES obj = FSOUND_REVERB_CHANNELPROPERTIES.create(); * (obj == null) <=> obj.isNull() <=> false * </code></pre> */ public static FSOUND_REVERB_CHANNELPROPERTIES create() { return new FSOUND_REVERB_CHANNELPROPERTIES(StructureJNI.new_FSOUND_REVERB_CHANNELPROPERTIES()); } protected FSOUND_REVERB_CHANNELPROPERTIES(long pointer) { super(pointer); } /** * Create an object that holds a null <code>FSOUND_REVERB_CHANNELPROPERTIES</code>.<br> * The call <code>isNull()</code> on the object created will returns true.<br> * <pre><code> FSOUND_REVERB_CHANNELPROPERTIES obj = new FSOUND_REVERB_CHANNELPROPERTIES(); * (obj == null) <=> false * obj.isNull() <=> true * </code></pre> * To creates a new <code>FSOUND_REVERB_CHANNELPROPERTIES</code>, use the static "constructor" : * <pre><code> FSOUND_REVERB_CHANNELPROPERTIES obj = FSOUND_REVERB_CHANNELPROPERTIES.create();</code></pre> * @see FSOUND_REVERB_CHANNELPROPERTIES#create() */ public FSOUND_REVERB_CHANNELPROPERTIES() { super(); } public void release() { if(pointer != 0) { StructureJNI.delete_FSOUND_REVERB_CHANNELPROPERTIES(pointer); } pointer = 0; } /** * -10000, 1000, 0, direct path level (at low and mid frequencies) (WIN32/XBOX) */ public void setDirect(int Direct) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Direct(pointer, Direct); } /** * @return value of Direct */ public int getDirect() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Direct(pointer); } /** * -10000, 0, 0, relative direct path level at high frequencies (WIN32/XBOX) */ public void setDirectHF(int DirectHF) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_DirectHF(pointer, DirectHF); } /** * @return value of DirectHF */ public int getDirectHF() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_DirectHF(pointer); } /** * -10000, 1000, 0, room effect level (at low and mid frequencies) (WIN32/XBOX/PS2) */ public void setRoom(int Room) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Room(pointer, Room); } /** * @return value of Room */ public int getRoom() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Room(pointer); } /** * -10000, 0, 0, relative room effect level at high frequencies (WIN32/XBOX) */ public void setRoomHF(int RoomHF) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_RoomHF(pointer, RoomHF); } /** * @return value of RoomHF */ public int getRoomHF() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_RoomHF(pointer); } /** * -10000, 0, 0, main obstruction control (attenuation at high frequencies) (WIN32/XBOX) */ public void setObstruction(int Obstruction) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Obstruction(pointer, Obstruction); } /** * @return value of Obstruction */ public int getObstruction() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Obstruction(pointer); } /** * 0.0, 1.0, 0.0, obstruction low-frequency level re. main control (WIN32/XBOX) */ public void setObstructionLFRatio(float ObstructionLFRatio) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_ObstructionLFRatio(pointer, ObstructionLFRatio); } /** * @return value of ObstructionLFRatio */ public float getObstructionLFRatio() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_ObstructionLFRatio(pointer); } /** * -10000, 0, 0, main occlusion control (attenuation at high frequencies) (WIN32/XBOX) */ public void setOcclusion(int Occlusion) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Occlusion(pointer, Occlusion); } /** * @return value of Occlusion */ public int getOcclusion() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Occlusion(pointer); } /** * 0.0, 1.0, 0.25, occlusion low-frequency level re. main control (WIN32/XBOX) */ public void setOcclusionLFRatio(float OcclusionLFRatio) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionLFRatio(pointer, OcclusionLFRatio); } /** * @return value of OcclusionLFRatio */ public float getOcclusionLFRatio() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionLFRatio(pointer); } /** * 0.0, 10.0, 1.5, relative occlusion control for room effect (WIN32) */ public void setOcclusionRoomRatio(float OcclusionRoomRatio) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionRoomRatio(pointer, OcclusionRoomRatio); } /** * @return value of OcclusionRoomRatio */ public float getOcclusionRoomRatio() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionRoomRatio(pointer); } /** * 0.0, 10.0, 1.0, relative occlusion control for direct path (WIN32) */ public void setOcclusionDirectRatio(float OcclusionDirectRatio) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionDirectRatio(pointer, OcclusionDirectRatio); } /** * @return value of OcclusionDirectRatio */ public float getOcclusionDirectRatio() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionDirectRatio(pointer); } /** * -10000, 0, 0, main exlusion control (attenuation at high frequencies) (WIN32) */ public void setExclusion(int Exclusion) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Exclusion(pointer, Exclusion); } /** * @return value of Exclusion */ public int getExclusion() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Exclusion(pointer); } /** * 0.0, 1.0, 1.0, exclusion low-frequency level re. main control (WIN32) */ public void setExclusionLFRatio(float ExclusionLFRatio) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_ExclusionLFRatio(pointer, ExclusionLFRatio); } /** * @return value of ExclusionLFRatio */ public float getExclusionLFRatio() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_ExclusionLFRatio(pointer); } /** * -10000, 0, 0, outside sound cone level at high frequencies (WIN32) */ public void setOutsideVolumeHF(int OutsideVolumeHF) { if(pointer == 0) throw new NullPointerException(); StructureJNI .set_FSOUND_REVERB_CHANNELPROPERTIES_OutsideVolumeHF(pointer, OutsideVolumeHF); } /** * @return value of OutsideVolumeHF */ public int getOutsideVolumeHF() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OutsideVolumeHF(pointer); } /** * 0.0, 10.0, 0.0, like DS3D flDopplerFactor but per source (WIN32) */ public void setDopplerFactor(float DopplerFactor) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_DopplerFactor(pointer, DopplerFactor); } /** * @return value of DopplerFactor */ public float getDopplerFactor() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_DopplerFactor(pointer); } /** * 0.0, 10.0, 0.0, like DS3D flRolloffFactor but per source (WIN32) */ public void setRolloffFactor(float RolloffFactor) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_RolloffFactor(pointer, RolloffFactor); } /** * @return value of RolloffFactor */ public float getRolloffFactor() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_RolloffFactor(pointer); } /** * 0.0, 10.0, 0.0, like DS3D flRolloffFactor but for room effect (WIN32/XBOX) */ public void setRoomRolloffFactor(float RoomRolloffFactor) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_RoomRolloffFactor(pointer, RoomRolloffFactor); } /** * @return value of RoomRolloverFactor */ public float getRoomRolloffFactor() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_RoomRolloffFactor(pointer); } /** * 0.0, 10.0, 1.0, multiplies AirAbsorptionHF member of FSOUND_REVERB_PROPERTIES (WIN32) * */ public void setAirAbsorptionFactor(float AirAbsorptionFactor) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_AirAbsorptionFactor(pointer, AirAbsorptionFactor); } /** * @return value of AirAbsorptionFactor */ public float getAirAbsorptionFactor() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_AirAbsorptionFactor(pointer); } /** * FSOUND_REVERB_CHANNELFLAGS - modifies the behavior of properties (WIN32) */ public void setFlags(int Flags) { if(pointer == 0) throw new NullPointerException(); StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Flags(pointer, Flags); } /** * @return value of EchoTime */ public int getFlags() { if(pointer == 0) throw new NullPointerException(); return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Flags(pointer); } }
jerome-jouvie/NativeFmod
src-java/org/jouvieje/Fmod/Structures/FSOUND_REVERB_CHANNELPROPERTIES.java
Java
lgpl-2.1
13,664
//Copyright (c) Microsoft Corporation. All rights reserved. // AddIn.cpp : Implementation of DLL Exports. #include "stdafx.h" #include "resource.h" #include "AddIn.h" CAddInModule _AtlModule; // DLL Entry Point extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { _AtlModule.SetResourceInstance(hInstance); return _AtlModule.DllMain(dwReason, lpReserved); } // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { return _AtlModule.DllCanUnloadNow(); } // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _AtlModule.DllGetClassObject(rclsid, riid, ppv); } void CreateRegistrationKey(const CString& version, const CString& modulePath, const CString& moduleShortName) { CString path = "Software\\Microsoft\\VisualStudio\\" + version; CRegKey devKey; if (devKey.Open(HKEY_LOCAL_MACHINE, path) == ERROR_SUCCESS) { // Auto create the addins key if it isn't already there. if (devKey.Create(HKEY_LOCAL_MACHINE, path + "\\AddIns") == ERROR_SUCCESS) { // Create the WorkspaceWhiz.DSAddin.1 key. if (devKey.Create(HKEY_LOCAL_MACHINE, path + "\\AddIns\\LuaPlusDebugger.Connect") == ERROR_SUCCESS) { // Remove all old entries. devKey.SetStringValue("SatelliteDLLPath", modulePath); devKey.SetStringValue("SatelliteDLLName", moduleShortName); devKey.SetDWORDValue("LoadBehavior", 3); devKey.SetStringValue("FriendlyName", "LuaPlus Debugger Window"); devKey.SetStringValue("Description", "The LuaPlus Debugger Window add-in provides support for viewing Lua tables while debugging."); devKey.SetDWORDValue("CommandPreload", 1); } } } if (devKey.Open(HKEY_CURRENT_USER, path + "\\PreloadAddinState") == ERROR_SUCCESS) { devKey.SetDWORDValue("LuaPlusDebugger.Connect", 1); } } void DestroyRegistrationKey(const CString& version) { CString path = "Software\\Microsoft\\VisualStudio\\" + version; CRegKey key; if (key.Open(HKEY_LOCAL_MACHINE, path + "\\AddIns") == ERROR_SUCCESS) { // Remove all old entries. key.RecurseDeleteKey("LuaPlusDebugger.Connect"); } } // DllRegisterServer - Adds entries to the system registry STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib HRESULT hr = _AtlModule.DllRegisterServer(); // Get the module name. TCHAR moduleName[_MAX_PATH]; moduleName[0] = 0; ::GetModuleFileName(_AtlModule.GetResourceInstance(), (TCHAR*)&moduleName, _MAX_PATH); // Get the module path. TCHAR modulePath[_MAX_PATH]; _tcscpy(modulePath, moduleName); TCHAR* ptr = _tcsrchr(modulePath, '\\'); ptr++; *ptr++ = 0; // Get the short module name. TCHAR moduleShortName[_MAX_PATH]; ptr = _tcsrchr(moduleName, '\\'); _tcscpy(moduleShortName, ptr + 1); // Register the add-in? CreateRegistrationKey("7.0", modulePath, moduleShortName); CreateRegistrationKey("7.1", modulePath, moduleShortName); return hr; } // DllUnregisterServer - Removes entries from the system registry STDAPI DllUnregisterServer(void) { HRESULT hr = _AtlModule.DllUnregisterServer(); // Remove entries. DestroyRegistrationKey("7.0"); DestroyRegistrationKey("7.1"); return hr; }
MikeMcShaffry/gamecode3
Dev/Source/3rdParty/LuaPlus/Tools/LuaPlusDebuggerAddin/LuaPlusDebuggerAddin/AddIn.cpp
C++
lgpl-2.1
3,265
import json import etcd from tendrl.gluster_bridge.atoms.volume.set import Set class SetVolumeOption(object): def __init__(self, api_job): super(SetVolumeOption, self).__init__() self.api_job = api_job self.atom = SetVolumeOption def start(self): attributes = json.loads(self.api_job['attributes'].decode('utf-8')) vol_name = attributes['volname'] option = attributes['option_name'] option_value = attributes['option_value'] self.atom().start(vol_name, option, option_value) self.api_job['status'] = "finished" etcd.Client().write(self.api_job['request_id'], json.dumps(self.api_job))
shtripat/gluster_bridge
tendrl/gluster_bridge/flows/set_volume_option.py
Python
lgpl-2.1
705
/** * @file common/js/xml_handler.js * @brief XE에서 ajax기능을 이용함에 있어 module, act를 잘 사용하기 위한 자바스크립트 **/ // xml handler을 이용하는 user function var show_waiting_message = true; /* This work is licensed under Creative Commons GNU LGPL License. License: http://creativecommons.org/licenses/LGPL/2.1/ Version: 0.9 Author: Stefan Goessner/2006 Web: http://goessner.net/ */ function xml2json(xml, tab, ignoreAttrib) { var X = { toObj: function(xml) { var o = {}; if (xml.nodeType==1) { // element node .. if (ignoreAttrib && xml.attributes.length) // element with attributes .. for (var i=0; i<xml.attributes.length; i++) o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString(); if (xml.firstChild) { // element has child nodes .. var textChild=0, cdataChild=0, hasElementChild=false; for (var n=xml.firstChild; n; n=n.nextSibling) { if (n.nodeType==1) hasElementChild = true; else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text else if (n.nodeType==4) cdataChild++; // cdata section node } if (hasElementChild) { if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node .. X.removeWhite(xml); for (var n=xml.firstChild; n; n=n.nextSibling) { if (n.nodeType == 3) // text node o = X.escape(n.nodeValue); else if (n.nodeType == 4) // cdata node // o["#cdata"] = X.escape(n.nodeValue); o = X.escape(n.nodeValue); else if (o[n.nodeName]) { // multiple occurence of element .. if (o[n.nodeName] instanceof Array) o[n.nodeName][o[n.nodeName].length] = X.toObj(n); else o[n.nodeName] = [o[n.nodeName], X.toObj(n)]; } else // first occurence of element.. o[n.nodeName] = X.toObj(n); } } else { // mixed content if (!xml.attributes.length) o = X.escape(X.innerXml(xml)); else o["#text"] = X.escape(X.innerXml(xml)); } } else if (textChild) { // pure text if (!xml.attributes.length) o = X.escape(X.innerXml(xml)); else o["#text"] = X.escape(X.innerXml(xml)); } else if (cdataChild) { // cdata if (cdataChild > 1) o = X.escape(X.innerXml(xml)); else for (var n=xml.firstChild; n; n=n.nextSibling){ //o["#cdata"] = X.escape(n.nodeValue); o = X.escape(n.nodeValue); } } } if (!xml.attributes.length && !xml.firstChild) o = null; } else if (xml.nodeType==9) { // document.node o = X.toObj(xml.documentElement); } else alert("unhandled node type: " + xml.nodeType); return o; }, toJson: function(o, name, ind) { var json = name ? ("\""+name+"\"") : ""; if (o instanceof Array) { for (var i=0,n=o.length; i<n; i++) o[i] = X.toJson(o[i], "", ind+"\t"); json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]"; } else if (o == null) json += (name&&":") + "null"; else if (typeof(o) == "object") { var arr = []; for (var m in o) arr[arr.length] = X.toJson(o[m], m, ind+"\t"); json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}"; } else if (typeof(o) == "string") json += (name&&":") + "\"" + o.toString() + "\""; else json += (name&&":") + o.toString(); return json; }, innerXml: function(node) { var s = "" if ("innerHTML" in node) s = node.innerHTML; else { var asXml = function(n) { var s = ""; if (n.nodeType == 1) { s += "<" + n.nodeName; for (var i=0; i<n.attributes.length;i++) s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\""; if (n.firstChild) { s += ">"; for (var c=n.firstChild; c; c=c.nextSibling) s += asXml(c); s += "</"+n.nodeName+">"; } else s += "/>"; } else if (n.nodeType == 3) s += n.nodeValue; else if (n.nodeType == 4) s += "<![CDATA[" + n.nodeValue + "]]>"; return s; }; for (var c=node.firstChild; c; c=c.nextSibling) s += asXml(c); } return s; }, escape: function(txt) { return txt.replace(/[\\]/g, "\\\\") .replace(/[\"]/g, '\\"') .replace(/[\n]/g, '\\n') .replace(/[\r]/g, '\\r'); }, removeWhite: function(e) { e.normalize(); for (var n = e.firstChild; n; ) { if (n.nodeType == 3) { // text node if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node var nxt = n.nextSibling; e.removeChild(n); n = nxt; } else n = n.nextSibling; } else if (n.nodeType == 1) { // element node X.removeWhite(n); n = n.nextSibling; } else // any other node n = n.nextSibling; } return e; } }; if (xml.nodeType == 9) // document node xml = xml.documentElement; var json_obj = X.toObj(X.removeWhite(xml)), json_str; if (typeof(JSON)=='object' && jQuery.isFunction(JSON.stringify) && false) { var obj = {}; obj[xml.nodeName] = json_obj; json_str = JSON.stringify(obj); return json_str; } else { json_str = X.toJson(json_obj, xml.nodeName, ""); return "{" + (tab ? json_str.replace(/\t/g, tab) : json_str.replace(/\t|\n/g, "")) + "}"; } } (function($){ /** * @brief exec_xml * @author NHN (developers@xpressengine.com) **/ $.exec_xml = window.exec_xml = function(module, act, params, callback_func, response_tags, callback_func_arg, fo_obj) { var xml_path = request_uri+"index.php" if(!params) params = {}; // {{{ set parameters if($.isArray(params)) params = arr2obj(params); params['module'] = module; params['act'] = act; if(typeof(xeVid)!='undefined') params['vid'] = xeVid; if(typeof(response_tags)=="undefined" || response_tags.length<1) response_tags = ['error','message']; else { response_tags.push('error', 'message'); } // }}} set parameters // use ssl? if ($.isArray(ssl_actions) && params['act'] && $.inArray(params['act'], ssl_actions) >= 0) { var url = default_url || request_uri; var port = window.https_port || 443; var _ul = $('<a>').attr('href', url)[0]; var target = 'https://' + _ul.hostname.replace(/:\d+$/, ''); if(port != 443) target += ':'+port; if(_ul.pathname[0] != '/') target += '/'; target += _ul.pathname; xml_path = target.replace(/\/$/, '')+'/index.php'; } var _u1 = $('<a>').attr('href', location.href)[0]; var _u2 = $('<a>').attr('href', xml_path)[0]; // 현 url과 ajax call 대상 url의 schema 또는 port가 다르면 직접 form 전송 if(_u1.protocol != _u2.protocol || _u1.port != _u2.port) return send_by_form(xml_path, params); var xml = [], i = 0; xml[i++] = '<?xml version="1.0" encoding="utf-8" ?>'; xml[i++] = '<methodCall>'; xml[i++] = '<params>'; $.each(params, function(key, val) { xml[i++] = '<'+key+'><![CDATA['+val+']]></'+key+'>'; }); xml[i++] = '</params>'; xml[i++] = '</methodCall>'; var _xhr = null; if (_xhr && _xhr.readyState != 0) _xhr.abort(); // 전송 성공시 function onsuccess(data, textStatus, xhr) { var resp_xml = $(data).find('response')[0], resp_obj, txt='', ret=[], tags={}, json_str=''; waiting_obj.css('visibility', 'hidden'); if(!resp_xml) { alert(_xhr.responseText); return null; } json_str = xml2json(resp_xml, false, false); resp_obj = (typeof(JSON)=='object' && $.isFunction(JSON.parse))?JSON.parse(json_str):eval('('+json_str+')'); resp_obj = resp_obj.response; if (typeof(resp_obj)=='undefined') { ret['error'] = -1; ret['message'] = 'Unexpected error occured.'; try { if(typeof(txt=resp_xml.childNodes[0].firstChild.data)!='undefined') ret['message'] += '\r\n'+txt; } catch(e){}; return ret; } $.each(response_tags, function(key, val){ tags[val] = true; }); tags["redirect_url"] = true; tags["act"] = true; $.each(resp_obj, function(key, val){ if(tags[key]) ret[key] = val; }); if(ret['error'] != 0) { if ($.isFunction($.exec_xml.onerror)) { return $.exec_xml.onerror(module, act, ret, callback_func, response_tags, callback_func_arg, fo_obj); } alert(ret['message'] || 'error!'); return null; } if(ret['redirect_url']) { location.href = ret['redirect_url'].replace(/&amp;/g, '&'); return null; } if($.isFunction(callback_func)) callback_func(ret, response_tags, callback_func_arg, fo_obj); } // 모든 xml데이터는 POST방식으로 전송. try-catch문으로 오류 발생시 대처 try { $.ajax({ url : xml_path, type : 'POST', dataType : 'xml', data : xml.join('\n'), contentType : 'text/plain', beforeSend : function(xhr){ _xhr = xhr; }, success : onsuccess, error : function(xhr, textStatus) { waiting_obj.css('visibility', 'hidden'); var msg = ''; if (textStatus == 'parsererror') { msg = 'The result is not valid XML :\n-------------------------------------\n'; if(xhr.responseText == "") return; msg += xhr.responseText.replace(/<[^>]+>/g, ''); } else { msg = textStatus; } alert(msg); } }); } catch(e) { alert(e); return; } // ajax 통신중 대기 메세지 출력 (show_waiting_message값을 false로 세팅시 보이지 않음) var waiting_obj = $('#waitingforserverresponse'); if(show_waiting_message && waiting_obj.length) { var d = $(document); waiting_obj.html(waiting_message).css({ 'top' : (d.scrollTop()+20)+'px', 'left' : (d.scrollLeft()+20)+'px', 'visibility' : 'visible' }); } } function send_by_form(url, params) { var frame_id = 'xeTmpIframe'; var form_id = 'xeVirtualForm'; if (!$('#'+frame_id).length) { $('<iframe name="%id%" id="%id%" style="position:absolute;left:-1px;top:1px;width:1px;height:1px"></iframe>'.replace(/%id%/g, frame_id)).appendTo(document.body); } $('#'+form_id).remove(); var form = $('<form id="%id%"></form>'.replace(/%id%/g, form_id)).attr({ 'id' : form_id, 'method' : 'post', 'action' : url, 'target' : frame_id }); params['xeVirtualRequestMethod'] = 'xml'; params['xeRequestURI'] = location.href.replace(/#(.*)$/i,''); params['xeVirtualRequestUrl'] = request_uri; $.each(params, function(key, value){ $('<input type="hidden">').attr('name', key).attr('value', value).appendTo(form); }); form.appendTo(document.body).submit(); } function arr2obj(arr) { var ret = {}; for(var key in arr) { if(arr.hasOwnProperty(key)) ret[key] = arr[key]; } return ret; } /** * @brief exec_json (exec_xml와 같은 용도) **/ $.exec_json = function(action,data,func){ if(typeof(data) == 'undefined') data = {}; action = action.split("."); if(action.length == 2){ if(show_waiting_message) { $("#waitingforserverresponse").html(waiting_message).css('top',$(document).scrollTop()+20).css('left',$(document).scrollLeft()+20).css('visibility','visible'); } $.extend(data,{module:action[0],act:action[1]}); if(typeof(xeVid)!='undefined') $.extend(data,{vid:xeVid}); $.ajax({ type:"POST" ,dataType:"json" ,url:request_uri ,contentType:"application/json" ,data:$.param(data) ,success : function(data){ $("#waitingforserverresponse").css('visibility','hidden'); if(data.error > 0) alert(data.message); if($.isFunction(func)) func(data); } }); } }; $.fn.exec_html = function(action,data,type,func,args){ if(typeof(data) == 'undefined') data = {}; if(!$.inArray(type, ['html','append','prepend'])) type = 'html'; var self = $(this); action = action.split("."); if(action.length == 2){ if(show_waiting_message) { $("#waitingforserverresponse").html(waiting_message).css('top',$(document).scrollTop()+20).css('left',$(document).scrollLeft()+20).css('visibility','visible'); } $.extend(data,{module:action[0],act:action[1]}); $.ajax({ type:"POST" ,dataType:"html" ,url:request_uri ,data:$.param(data) ,success : function(html){ $("#waitingforserverresponse").css('visibility','hidden'); self[type](html); if($.isFunction(func)) func(args); } }); } }; })(jQuery);
haegyung/xe-core
common/js/src/xml_handler.js
JavaScript
lgpl-2.1
14,624
/* * 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 org.kore.runtime.jsf.converter; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import org.kore.runtime.person.Titel; /** * * @author Konrad Renner */ @FacesConverter(value = "CurrencyConverter") public class TitelConverter implements Converter { @Override public Titel getAsObject(FacesContext fc, UIComponent uic, String string) { if (string == null || string.trim().length() == 0) { return null; } return new Titel(string.trim()); } @Override public String getAsString(FacesContext fc, UIComponent uic, Object o) { if (o == null) { return null; } if (o instanceof Titel) { return ((Titel) o).getValue(); } throw new IllegalArgumentException("Given object is not a org.kore.runtime.person.Titel"); } }
konradrenner/KoreRuntime-jsf
src/main/java/org/kore/runtime/jsf/converter/TitelConverter.java
Java
lgpl-2.1
1,145
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <qvariant.h> class tst_QGuiVariant : public QObject { Q_OBJECT public: tst_QGuiVariant(); private slots: void variantWithoutApplication(); }; tst_QGuiVariant::tst_QGuiVariant() {} void tst_QGuiVariant::variantWithoutApplication() { QVariant v = QString("red"); QVERIFY(qvariant_cast<QColor>(v) == QColor(Qt::red)); } QTEST_APPLESS_MAIN(tst_QGuiVariant) #include "tst_qguivariant.moc"
radekp/qt
tests/auto/qguivariant/tst_qguivariant.cpp
C++
lgpl-2.1
1,941
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2012, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * 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. */ package org.geotools.referencing.factory.gridshift; import java.net.URL; import org.geotools.metadata.iso.citation.Citations; import org.geotools.util.factory.AbstractFactory; import org.opengis.metadata.citation.Citation; /** * Default grid shift file locator, looks up grids in the classpath * * @author Andrea Aime - GeoSolutions */ public class ClasspathGridShiftLocator extends AbstractFactory implements GridShiftLocator { public ClasspathGridShiftLocator() { super(NORMAL_PRIORITY); } @Override public Citation getVendor() { return Citations.GEOTOOLS; } @Override public URL locateGrid(String grid) { return getClass().getResource(grid); } }
geotools/geotools
modules/library/referencing/src/main/java/org/geotools/referencing/factory/gridshift/ClasspathGridShiftLocator.java
Java
lgpl-2.1
1,361
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.dialect.identity; import java.sql.PreparedStatement; import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.identity.GetGeneratedKeysDelegate; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.id.PostInsertIdentityPersister; /** * @author Andrea Boriero */ public class Oracle12cGetGeneratedKeysDelegate extends GetGeneratedKeysDelegate { private String[] keyColumns; public Oracle12cGetGeneratedKeysDelegate(PostInsertIdentityPersister persister, Dialect dialect) { super( persister, dialect ); this.keyColumns = getPersister().getRootTableKeyColumnNames(); if ( keyColumns.length > 1 ) { throw new HibernateException( "Identity generator cannot be used with multi-column keys" ); } } @Override protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException { return session .getJdbcCoordinator() .getStatementPreparer() .prepareStatement( insertSQL, keyColumns ); } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/dialect/identity/Oracle12cGetGeneratedKeysDelegate.java
Java
lgpl-2.1
1,313
/******************************************************************************* * Copyright (c) 2012 Scott Ross. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Scott Ross - initial API and implementation ******************************************************************************/ package org.alms.messages; import org.alms.beans.*; import javax.ws.rs.core.HttpHeaders; public interface IMsg { public void setHeader(HttpHeaders msgHeaders); public void setIncomingMessage(String incomingMessage); public Boolean checkMessageVocubulary(); public RelatedParty getMsgDestination(); public RelatedParty getMsgSending(); public String getMsgId(); public String getUserName(); public String getPassword(); public String getXSDLocation(); public String getIncomingMessage(); public String receiverTransmissionType(); }
sross07/alms
src/main/java/org/alms/messages/IMsg.java
Java
lgpl-2.1
1,077
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: ks_prefreport.php 57954 2016-03-17 19:34:29Z jyhem $ // outputs the prefreport as a pipe delimited file // Usage: From the command line: // php doc/devtools/prefreport.php // resulting file can be found at dump/prefreport.txt // // also check out doc/devtools/securitycheck.php to see in which files are // used each pref (and permission name too) // $ourFileName = "dump/prefreport.txt"; require_once 'tiki-setup.php'; $prefslib = TikiLib::lib('prefs'); $defaultValues = get_default_prefs(); $fields = array( 'preference' => '', 'name' => '', 'description' => '', 'default' => '', 'help' => '', 'hard_to_search' => false, 'duplicate_name' => 0, 'duplicate_description' => 0, 'word_count' => 0, 'filter' => '', 'locations' => '', 'dependencies' => '', 'type' => '', 'options' => '', 'admin' => '', 'module' => '', 'view' => '', 'permission' => '', 'plugin' => '', 'extensions' => '', 'tags' => '', 'parameters' => '', 'detail' => '', 'warning' => '', 'hint' => '', 'shorthint' => '', 'perspective' => '', 'separator' => '', ); $stopWords = array('', 'in', 'and', 'a', 'to', 'be', 'of', 'on', 'the', 'for', 'as', 'it', 'or', 'with', 'by', 'is', 'an'); $data = array(); error_reporting(E_ALL);ini_set('display_errors', 'on'); $data = collect_raw_data($fields); remove_fake_descriptions($data); set_default_values($data, $defaultValues); collect_locations($data); $index = array( 'name' => index_data($data, 'name'), 'description' => index_data($data, 'description'), ); update_search_flag($data, $index, $stopWords); $ourFileHandle = fopen($ourFileName, 'w+') or die("can't open file"); // Output results fputcsv($ourFileHandle, array_keys($fields), '|'); foreach ($data as $values) { fputcsv($ourFileHandle, array_values($values), '|'); } fclose($ourFileHandle); /** * @param $fields * @return array */ function collect_raw_data($fields) { $data = array(); foreach (glob('lib/prefs/*.php') as $file) { $name = substr(basename($file), 0, -4); $function = "prefs_{$name}_list"; if ($name == 'index') { continue; } include $file; $list = $function(); foreach ($list as $name => $raw) { $entry = $fields; $entry['preference'] = $name; $entry['name'] = isset($raw['name']) ? $raw['name'] : ''; $entry['description'] = isset($raw['description']) ? $raw['description'] : ''; $entry['filter'] = isset($raw['filter']) ? $raw['filter'] : ''; $entry['help'] = isset($raw['help']) ? $raw['help'] : ''; $entry['dependencies'] = !empty($raw['dependencies']) ? implode(',', (array) $raw['dependencies']) : ''; $entry['type'] = isset($raw['type']) ? $raw['type'] : ''; $entry['options'] = isset($raw['options']) ? implode(',', $raw['options']) : ''; $entry['admin'] = isset($raw['admin']) ? $raw['admin'] : ''; $entry['module'] = isset($raw['module']) ? $raw['module'] : ''; $entry['view'] = isset($raw['view']) ? $raw['view'] : ''; $entry['permission'] = isset($raw['permission']) ? implode(',', $raw['permission']) : ''; $entry['plugin'] = isset($raw['plugin']) ? $raw['plugin'] : ''; $entry['extensions'] = isset($raw['extensions']) ? implode(',', $raw['extensions']) : ''; $entry['tags'] = isset($raw['tags']) ? implode(',', $raw['tags']) : ''; $entry['parameters'] = isset($raw['parameters']) ? implode(',', $raw['parameters']) : ''; $entry['detail'] = isset($raw['detail']) ? $raw['detail'] : ''; $entry['warning'] = isset($raw['warning']) ? $raw['warning'] : ''; $entry['hint'] = isset($raw['hint']) ? $raw['hint'] : ''; $entry['shorthint'] = isset($raw['shorthint']) ? $raw['shorthint'] : ''; $entry['perspective'] = isset($raw['perspective']) ? $raw['perspective'] ? 'true' : 'false' : ''; $entry['separator'] = isset($raw['separator']) ? $raw['separator'] : ''; $data[] = $entry; } } return $data; } /** * @param $data */ function remove_fake_descriptions(& $data) { foreach ($data as & $row) { if ($row['name'] == $row['description']) { $row['description'] = ''; } } } /** * @param $data * @param $prefs */ function set_default_values(& $data, $prefs) { foreach ($data as & $row) { $row['default'] = isset($prefs[$row['preference']]) ? $prefs[$row['preference']] : ''; if (is_array($row['default'])) { $row['default'] = implode($row['separator'], $row['default']); } } } /** * @param $data * @param $field * @return array */ function index_data($data, $field) { $index = array(); foreach ($data as $row) { $value = strtolower($row[$field]); if (! isset($index[$value])) { $index[$value] = 0; } $index[$value]++; } return $index; } /** * @param $data */ function collect_locations(& $data) { $prefslib = TikiLib::lib('prefs'); foreach ($data as & $row) { $pages = $prefslib->getPreferenceLocations($row['preference']); foreach ($pages as & $page) { $page = $page[0] . '/' . $page[1]; } $row['locations'] = implode(', ', $pages); } } /** * @param $data * @param $index * @param $stopWords */ function update_search_flag(& $data, $index, $stopWords) { foreach ($data as & $row) { $name = strtolower($row['name']); $description = strtolower($row['description']); $words = array_diff(explode(' ', $name . ' ' . $description), $stopWords); $row['duplicate_name'] = $index['name'][$name]; if (! empty($description)) { $row['duplicate_description'] = $index['description'][$description]; } $row['word_count'] = count($words); if (count($words) < 5) { $row['hard_to_search'] = 'X'; } elseif ($index['name'][$name] > 2) { $row['hard_to_search'] = 'X'; } elseif ($index['description'][$description] > 2) { $row['hard_to_search'] = 'X'; } } }
XavierSolerFR/diem25tiki
doc/devtools/ks_prefreport.php
PHP
lgpl-2.1
5,981
package jastadd.soot.JastAddJ; import java.util.HashSet;import java.util.LinkedHashSet;import java.io.File;import java.util.*;import jastadd.beaver.*;import java.util.ArrayList;import java.util.zip.*;import java.io.*;import java.io.FileNotFoundException;import java.util.Collection;import soot.*;import soot.util.*;import soot.jimple.*;import soot.coffi.ClassFile;import soot.coffi.method_info;import soot.coffi.CONSTANT_Utf8_info;import soot.tagkit.SourceFileTag;import soot.coffi.CoffiMethodSource; public class ParClassInstanceExpr extends ClassInstanceExpr implements Cloneable { public void flushCache() { super.flushCache(); } public void flushCollectionCache() { super.flushCollectionCache(); } @SuppressWarnings({"unchecked", "cast"}) public ParClassInstanceExpr clone() throws CloneNotSupportedException { ParClassInstanceExpr node = (ParClassInstanceExpr)super.clone(); node.in$Circle(false); node.is$Final(false); return node; } @SuppressWarnings({"unchecked", "cast"}) public ParClassInstanceExpr copy() { try { ParClassInstanceExpr node = clone(); if(children != null) node.children = children.clone(); return node; } catch (CloneNotSupportedException e) { } System.err.println("Error: Could not clone node of type " + getClass().getName() + "!"); return null; } @SuppressWarnings({"unchecked", "cast"}) public ParClassInstanceExpr fullCopy() { ParClassInstanceExpr res = copy(); for(int i = 0; i < getNumChildNoTransform(); i++) { ASTNode node = getChildNoTransform(i); if(node != null) node = node.fullCopy(); res.setChild(node, i); } return res; } // Declared in GenericMethods.jrag at line 160 public void toString(StringBuffer s) { s.append("<"); for(int i = 0; i < getNumTypeArgument(); i++) { if(i != 0) s.append(", "); getTypeArgument(i).toString(s); } s.append(">"); super.toString(s); } // Declared in GenericMethods.ast at line 3 // Declared in GenericMethods.ast line 15 public ParClassInstanceExpr() { super(); setChild(new List(), 1); setChild(new Opt(), 2); setChild(new List(), 3); } // Declared in GenericMethods.ast at line 13 // Declared in GenericMethods.ast line 15 public ParClassInstanceExpr(Access p0, List<Expr> p1, Opt<TypeDecl> p2, List<Access> p3) { setChild(p0, 0); setChild(p1, 1); setChild(p2, 2); setChild(p3, 3); } // Declared in GenericMethods.ast at line 20 protected int numChildren() { return 4; } // Declared in GenericMethods.ast at line 23 public boolean mayHaveRewrite() { return false; } // Declared in java.ast at line 2 // Declared in java.ast line 34 public void setAccess(Access node) { setChild(node, 0); } // Declared in java.ast at line 5 public Access getAccess() { return (Access)getChild(0); } // Declared in java.ast at line 9 public Access getAccessNoTransform() { return (Access)getChildNoTransform(0); } // Declared in java.ast at line 2 // Declared in java.ast line 34 public void setArgList(List<Expr> list) { setChild(list, 1); } // Declared in java.ast at line 6 public int getNumArg() { return getArgList().getNumChild(); } // Declared in java.ast at line 10 @SuppressWarnings({"unchecked", "cast"}) public Expr getArg(int i) { return getArgList().getChild(i); } // Declared in java.ast at line 14 public void addArg(Expr node) { List<Expr> list = (parent == null || state == null) ? getArgListNoTransform() : getArgList(); list.addChild(node); } // Declared in java.ast at line 19 public void addArgNoTransform(Expr node) { List<Expr> list = getArgListNoTransform(); list.addChild(node); } // Declared in java.ast at line 24 public void setArg(Expr node, int i) { List<Expr> list = getArgList(); list.setChild(node, i); } // Declared in java.ast at line 28 public List<Expr> getArgs() { return getArgList(); } // Declared in java.ast at line 31 public List<Expr> getArgsNoTransform() { return getArgListNoTransform(); } // Declared in java.ast at line 35 @SuppressWarnings({"unchecked", "cast"}) public List<Expr> getArgList() { List<Expr> list = (List<Expr>)getChild(1); list.getNumChild(); return list; } // Declared in java.ast at line 41 @SuppressWarnings({"unchecked", "cast"}) public List<Expr> getArgListNoTransform() { return (List<Expr>)getChildNoTransform(1); } // Declared in java.ast at line 2 // Declared in java.ast line 34 public void setTypeDeclOpt(Opt<TypeDecl> opt) { setChild(opt, 2); } // Declared in java.ast at line 6 public boolean hasTypeDecl() { return getTypeDeclOpt().getNumChild() != 0; } // Declared in java.ast at line 10 @SuppressWarnings({"unchecked", "cast"}) public TypeDecl getTypeDecl() { return getTypeDeclOpt().getChild(0); } // Declared in java.ast at line 14 public void setTypeDecl(TypeDecl node) { getTypeDeclOpt().setChild(node, 0); } // Declared in java.ast at line 17 @SuppressWarnings({"unchecked", "cast"}) public Opt<TypeDecl> getTypeDeclOpt() { return (Opt<TypeDecl>)getChild(2); } // Declared in java.ast at line 21 @SuppressWarnings({"unchecked", "cast"}) public Opt<TypeDecl> getTypeDeclOptNoTransform() { return (Opt<TypeDecl>)getChildNoTransform(2); } // Declared in GenericMethods.ast at line 2 // Declared in GenericMethods.ast line 15 public void setTypeArgumentList(List<Access> list) { setChild(list, 3); } // Declared in GenericMethods.ast at line 6 public int getNumTypeArgument() { return getTypeArgumentList().getNumChild(); } // Declared in GenericMethods.ast at line 10 @SuppressWarnings({"unchecked", "cast"}) public Access getTypeArgument(int i) { return getTypeArgumentList().getChild(i); } // Declared in GenericMethods.ast at line 14 public void addTypeArgument(Access node) { List<Access> list = (parent == null || state == null) ? getTypeArgumentListNoTransform() : getTypeArgumentList(); list.addChild(node); } // Declared in GenericMethods.ast at line 19 public void addTypeArgumentNoTransform(Access node) { List<Access> list = getTypeArgumentListNoTransform(); list.addChild(node); } // Declared in GenericMethods.ast at line 24 public void setTypeArgument(Access node, int i) { List<Access> list = getTypeArgumentList(); list.setChild(node, i); } // Declared in GenericMethods.ast at line 28 public List<Access> getTypeArguments() { return getTypeArgumentList(); } // Declared in GenericMethods.ast at line 31 public List<Access> getTypeArgumentsNoTransform() { return getTypeArgumentListNoTransform(); } // Declared in GenericMethods.ast at line 35 @SuppressWarnings({"unchecked", "cast"}) public List<Access> getTypeArgumentList() { List<Access> list = (List<Access>)getChild(3); list.getNumChild(); return list; } // Declared in GenericMethods.ast at line 41 @SuppressWarnings({"unchecked", "cast"}) public List<Access> getTypeArgumentListNoTransform() { return (List<Access>)getChildNoTransform(3); } // Declared in GenericMethods.jrag at line 126 public NameType Define_NameType_nameType(ASTNode caller, ASTNode child) { if(caller == getTypeArgumentListNoTransform()) { int childIndex = caller.getIndexOfChild(child); return NameType.TYPE_NAME; } return super.Define_NameType_nameType(caller, child); } // Declared in GenericMethods.jrag at line 127 public SimpleSet Define_SimpleSet_lookupType(ASTNode caller, ASTNode child, String name) { if(caller == getTypeArgumentListNoTransform()) { int childIndex = caller.getIndexOfChild(child); return unqualifiedScope().lookupType(name); } return super.Define_SimpleSet_lookupType(caller, child, name); } public ASTNode rewriteTo() { return super.rewriteTo(); } }
plast-lab/soot
src/jastadd/soot/JastAddJ/ParClassInstanceExpr.java
Java
lgpl-2.1
8,648
/* * filter_glsl_manager.cpp * Copyright (C) 2011-2012 Christophe Thommeret <hftom@free.fr> * Copyright (C) 2013 Dan Dennedy <dan@dennedy.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> #include <string> #include "filter_glsl_manager.h" #include <movit/init.h> #include <movit/util.h> #include <movit/effect_chain.h> #include <movit/resource_pool.h> #include "mlt_movit_input.h" #include "mlt_flip_effect.h" #include <mlt++/MltEvent.h> #include <mlt++/MltProducer.h> extern "C" { #include <framework/mlt_factory.h> } #if defined(__APPLE__) #include <OpenGL/OpenGL.h> #elif defined(_WIN32) #include <windows.h> #include <wingdi.h> #else #include <GL/glx.h> #endif using namespace movit; void dec_ref_and_delete(GlslManager *p) { if (p->dec_ref() == 0) { delete p; } } GlslManager::GlslManager() : Mlt::Filter( mlt_filter_new() ) , resource_pool(new ResourcePool()) , pbo(0) , initEvent(0) , closeEvent(0) , prev_sync(NULL) { mlt_filter filter = get_filter(); if ( filter ) { // Set the mlt_filter child in case we choose to override virtual functions. filter->child = this; add_ref(mlt_global_properties()); mlt_events_register( get_properties(), "init glsl", NULL ); mlt_events_register( get_properties(), "close glsl", NULL ); initEvent = listen("init glsl", this, (mlt_listener) GlslManager::onInit); closeEvent = listen("close glsl", this, (mlt_listener) GlslManager::onClose); } } GlslManager::~GlslManager() { mlt_log_debug(get_service(), "%s\n", __FUNCTION__); cleanupContext(); // XXX If there is still a frame holding a reference to a texture after this // destructor is called, then it will crash in release_texture(). // while (texture_list.peek_back()) // delete (glsl_texture) texture_list.pop_back(); delete initEvent; delete closeEvent; if (prev_sync != NULL) { glDeleteSync( prev_sync ); } while (syncs_to_delete.count() > 0) { GLsync sync = (GLsync) syncs_to_delete.pop_front(); glDeleteSync( sync ); } delete resource_pool; } void GlslManager::add_ref(mlt_properties properties) { inc_ref(); mlt_properties_set_data(properties, "glslManager", this, 0, (mlt_destructor) dec_ref_and_delete, NULL); } GlslManager* GlslManager::get_instance() { return (GlslManager*) mlt_properties_get_data(mlt_global_properties(), "glslManager", 0); } glsl_texture GlslManager::get_texture(int width, int height, GLint internal_format) { lock(); for (int i = 0; i < texture_list.count(); ++i) { glsl_texture tex = (glsl_texture) texture_list.peek(i); if (!tex->used && (tex->width == width) && (tex->height == height) && (tex->internal_format == internal_format)) { glBindTexture(GL_TEXTURE_2D, tex->texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture( GL_TEXTURE_2D, 0); tex->used = 1; unlock(); return tex; } } unlock(); GLuint tex = 0; glGenTextures(1, &tex); if (!tex) { return NULL; } glsl_texture gtex = new glsl_texture_s; if (!gtex) { glDeleteTextures(1, &tex); return NULL; } glBindTexture( GL_TEXTURE_2D, tex ); glTexImage2D( GL_TEXTURE_2D, 0, internal_format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glBindTexture( GL_TEXTURE_2D, 0 ); gtex->texture = tex; gtex->width = width; gtex->height = height; gtex->internal_format = internal_format; gtex->used = 1; lock(); texture_list.push_back(gtex); unlock(); return gtex; } void GlslManager::release_texture(glsl_texture texture) { texture->used = 0; } void GlslManager::delete_sync(GLsync sync) { // We do not know which thread we are called from, and we can only // delete this if we are in one with a valid OpenGL context. // Thus, store it for later deletion in render_frame_texture(). GlslManager* g = GlslManager::get_instance(); g->lock(); g->syncs_to_delete.push_back(sync); g->unlock(); } glsl_pbo GlslManager::get_pbo(int size) { lock(); if (!pbo) { GLuint pb = 0; glGenBuffers(1, &pb); if (!pb) { unlock(); return NULL; } pbo = new glsl_pbo_s; if (!pbo) { glDeleteBuffers(1, &pb); unlock(); return NULL; } pbo->pbo = pb; pbo->size = 0; } if (size > pbo->size) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo->pbo); glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, size, NULL, GL_STREAM_DRAW); glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0); pbo->size = size; } unlock(); return pbo; } void GlslManager::cleanupContext() { lock(); while (texture_list.peek_back()) { glsl_texture texture = (glsl_texture) texture_list.peek_back(); glDeleteTextures(1, &texture->texture); delete texture; texture_list.pop_back(); } if (pbo) { glDeleteBuffers(1, &pbo->pbo); delete pbo; pbo = 0; } unlock(); } void GlslManager::onInit( mlt_properties owner, GlslManager* filter ) { mlt_log_debug( filter->get_service(), "%s\n", __FUNCTION__ ); #ifdef _WIN32 std::string path = std::string(mlt_environment("MLT_APPDIR")).append("\\share\\movit"); #elif defined(__APPLE__) && defined(RELOCATABLE) std::string path = std::string(mlt_environment("MLT_APPDIR")).append("/share/movit"); #else std::string path = std::string(getenv("MLT_MOVIT_PATH") ? getenv("MLT_MOVIT_PATH") : SHADERDIR); #endif bool success = init_movit( path, mlt_log_get_level() == MLT_LOG_DEBUG? MOVIT_DEBUG_ON : MOVIT_DEBUG_OFF ); filter->set( "glsl_supported", success ); } void GlslManager::onClose( mlt_properties owner, GlslManager *filter ) { filter->cleanupContext(); } void GlslManager::onServiceChanged( mlt_properties owner, mlt_service aservice ) { Mlt::Service service( aservice ); service.lock(); service.set( "movit chain", NULL, 0 ); service.unlock(); } void GlslManager::onPropertyChanged( mlt_properties owner, mlt_service service, const char* property ) { if ( property && std::string( property ) == "disable" ) onServiceChanged( owner, service ); } extern "C" { mlt_filter filter_glsl_manager_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg ) { GlslManager* g = GlslManager::get_instance(); if (g) g->inc_ref(); else g = new GlslManager(); return g->get_filter(); } } // extern "C" static void deleteChain( GlslChain* chain ) { // The Input* is owned by the EffectChain, but the MltInput* is not. // Thus, we have to delete it here. for (std::map<mlt_producer, MltInput*>::iterator input_it = chain->inputs.begin(); input_it != chain->inputs.end(); ++input_it) { delete input_it->second; } delete chain->effect_chain; delete chain; } void* GlslManager::get_frame_specific_data( mlt_service service, mlt_frame frame, const char *key, int *length ) { const char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" ); char buf[256]; snprintf( buf, sizeof(buf), "%s_%s", key, unique_id ); return mlt_properties_get_data( MLT_FRAME_PROPERTIES(frame), buf, length ); } int GlslManager::set_frame_specific_data( mlt_service service, mlt_frame frame, const char *key, void *value, int length, mlt_destructor destroy, mlt_serialiser serialise ) { const char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" ); char buf[256]; snprintf( buf, sizeof(buf), "%s_%s", key, unique_id ); return mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), buf, value, length, destroy, serialise ); } void GlslManager::set_chain( mlt_service service, GlslChain* chain ) { mlt_properties_set_data( MLT_SERVICE_PROPERTIES(service), "_movit chain", chain, 0, (mlt_destructor) deleteChain, NULL ); } GlslChain* GlslManager::get_chain( mlt_service service ) { return (GlslChain*) mlt_properties_get_data( MLT_SERVICE_PROPERTIES(service), "_movit chain", NULL ); } Effect* GlslManager::get_effect( mlt_service service, mlt_frame frame ) { return (Effect*) get_frame_specific_data( service, frame, "_movit effect", NULL ); } Effect* GlslManager::set_effect( mlt_service service, mlt_frame frame, Effect* effect ) { set_frame_specific_data( service, frame, "_movit effect", effect, 0, NULL, NULL ); return effect; } MltInput* GlslManager::get_input( mlt_producer producer, mlt_frame frame ) { return (MltInput*) get_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input", NULL ); } MltInput* GlslManager::set_input( mlt_producer producer, mlt_frame frame, MltInput* input ) { set_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input", input, 0, NULL, NULL ); return input; } uint8_t* GlslManager::get_input_pixel_pointer( mlt_producer producer, mlt_frame frame ) { return (uint8_t*) get_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input pp", NULL ); } uint8_t* GlslManager::set_input_pixel_pointer( mlt_producer producer, mlt_frame frame, uint8_t* image ) { set_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input pp", image, 0, NULL, NULL ); return image; } mlt_service GlslManager::get_effect_input( mlt_service service, mlt_frame frame ) { return (mlt_service) get_frame_specific_data( service, frame, "_movit effect input", NULL ); } void GlslManager::set_effect_input( mlt_service service, mlt_frame frame, mlt_service input_service ) { set_frame_specific_data( service, frame, "_movit effect input", input_service, 0, NULL, NULL ); } void GlslManager::get_effect_secondary_input( mlt_service service, mlt_frame frame, mlt_service *input_service, mlt_frame *input_frame) { *input_service = (mlt_service) get_frame_specific_data( service, frame, "_movit effect secondary input", NULL ); *input_frame = (mlt_frame) get_frame_specific_data( service, frame, "_movit effect secondary input frame", NULL ); } void GlslManager::set_effect_secondary_input( mlt_service service, mlt_frame frame, mlt_service input_service, mlt_frame input_frame ) { set_frame_specific_data( service, frame, "_movit effect secondary input", input_service, 0, NULL, NULL ); set_frame_specific_data( service, frame, "_movit effect secondary input frame", input_frame, 0, NULL, NULL ); } void GlslManager::get_effect_third_input( mlt_service service, mlt_frame frame, mlt_service *input_service, mlt_frame *input_frame) { *input_service = (mlt_service) get_frame_specific_data( service, frame, "_movit effect third input", NULL ); *input_frame = (mlt_frame) get_frame_specific_data( service, frame, "_movit effect third input frame", NULL ); } void GlslManager::set_effect_third_input( mlt_service service, mlt_frame frame, mlt_service input_service, mlt_frame input_frame ) { set_frame_specific_data( service, frame, "_movit effect third input", input_service, 0, NULL, NULL ); set_frame_specific_data( service, frame, "_movit effect third input frame", input_frame, 0, NULL, NULL ); } int GlslManager::render_frame_texture(EffectChain *chain, mlt_frame frame, int width, int height, uint8_t **image) { glsl_texture texture = get_texture( width, height, GL_RGBA8 ); if (!texture) { return 1; } GLuint fbo; glGenFramebuffers( 1, &fbo ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, fbo ); check_error(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); lock(); while (syncs_to_delete.count() > 0) { GLsync sync = (GLsync) syncs_to_delete.pop_front(); glDeleteSync( sync ); } unlock(); // Make sure we never have more than one frame pending at any time. // This ensures we do not swamp the GPU with so much work // that we cannot actually display the frames we generate. if (prev_sync != NULL) { glFlush(); glClientWaitSync( prev_sync, 0, GL_TIMEOUT_IGNORED ); glDeleteSync( prev_sync ); } chain->render_to_fbo( fbo, width, height ); prev_sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 ); GLsync sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); glDeleteFramebuffers( 1, &fbo ); check_error(); *image = (uint8_t*) &texture->texture; mlt_frame_set_image( frame, *image, 0, NULL ); mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.texture", texture, 0, (mlt_destructor) GlslManager::release_texture, NULL ); mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.fence", sync, 0, (mlt_destructor) GlslManager::delete_sync, NULL ); return 0; } int GlslManager::render_frame_rgba(EffectChain *chain, mlt_frame frame, int width, int height, uint8_t **image) { glsl_texture texture = get_texture( width, height, GL_RGBA8 ); if (!texture) { return 1; } // Use a PBO to hold the data we read back with glReadPixels(). // (Intel/DRI goes into a slow path if we don't read to PBO.) int img_size = width * height * 4; glsl_pbo pbo = get_pbo( img_size ); if (!pbo) { release_texture(texture); return 1; } // Set the FBO GLuint fbo; glGenFramebuffers( 1, &fbo ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, fbo ); check_error(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); chain->render_to_fbo( fbo, width, height ); // Read FBO into PBO glBindFramebuffer( GL_FRAMEBUFFER, fbo ); check_error(); glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, pbo->pbo ); check_error(); glBufferData( GL_PIXEL_PACK_BUFFER_ARB, img_size, NULL, GL_STREAM_READ ); check_error(); glReadPixels( 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0) ); check_error(); // Copy from PBO uint8_t* buf = (uint8_t*) glMapBuffer( GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY ); check_error(); *image = (uint8_t*) mlt_pool_alloc( img_size ); mlt_frame_set_image( frame, *image, img_size, mlt_pool_release ); memcpy( *image, buf, img_size ); // Convert BGRA to RGBA register uint8_t *p = *image; register int n = width * height + 1; while ( --n ) { uint8_t b = p[0]; *p = p[2]; p += 2; *p = b; p += 2; } // Release PBO and FBO glUnmapBuffer( GL_PIXEL_PACK_BUFFER_ARB ); check_error(); glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, 0 ); check_error(); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); check_error(); glBindTexture( GL_TEXTURE_2D, 0 ); check_error(); mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.texture", texture, 0, (mlt_destructor) GlslManager::release_texture, NULL); glDeleteFramebuffers( 1, &fbo ); check_error(); return 0; } void GlslManager::lock_service( mlt_frame frame ) { Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) ); producer.lock(); } void GlslManager::unlock_service( mlt_frame frame ) { Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) ); producer.unlock(); }
xzhavilla/mlt
src/modules/opengl/filter_glsl_manager.cpp
C++
lgpl-2.1
15,812
package org.wingx; import java.awt.Color; import org.wings.*; import org.wings.style.CSSAttributeSet; import org.wings.style.CSSProperty; import org.wings.style.CSSStyle; import org.wings.style.CSSStyleSheet; import org.wings.style.Selector; import org.wings.style.Style; public class XDivision extends SContainer implements LowLevelEventListener { String title; SIcon icon; /** * Is the XDivision shaded? */ boolean shaded; /** * Is the title clickable? Default is false. */ protected boolean isTitleClickable = false; public static final Selector SELECTOR_TITLE = new Selector("xdiv.title"); /** * Creates a XDivision instance with the specified LayoutManager * @param l the LayoutManager */ public XDivision(SLayoutManager l) { super(l); } /** * Creates a XDivision instance */ public XDivision() { } public XDivision(String title) { this.title = title; } /** * Returns the title of the XDivision. * @return String the title */ public String getTitle() { return title; } /** * Sets the title of the XDivision. * @param title the title */ public void setTitle(String title) { String oldVal = this.title; reloadIfChange(this.title, title); this.title = title; propertyChangeSupport.firePropertyChange("title", oldVal, this.title); } /** * Sets the title-font of the XDivision. * @param titleFont the font for the title */ public void setTitleFont( org.wings.SFont titleFont) { SFont oldVal = this.getTitleFont(); CSSAttributeSet attributes = CSSStyleSheet.getAttributes(titleFont); Style style = getDynamicStyle(SELECTOR_TITLE); if (style == null) { addDynamicStyle(new CSSStyle(SELECTOR_TITLE, attributes)); } else { style.remove(CSSProperty.FONT); style.remove(CSSProperty.FONT_FAMILY); style.remove(CSSProperty.FONT_SIZE); style.remove(CSSProperty.FONT_STYLE); style.remove(CSSProperty.FONT_WEIGHT); style.putAll(attributes); } propertyChangeSupport.firePropertyChange("titleFont", oldVal, this.getTitleFont()); } /** * Returns the title-font of the XDivision. * @return SFont the font for the title */ public SFont getTitleFont() { return dynamicStyles == null || dynamicStyles.get(SELECTOR_TITLE) == null ? null : CSSStyleSheet.getFont((CSSAttributeSet) dynamicStyles.get(SELECTOR_TITLE)); } /** * Sets the title-color of the XDivision. * @param titleColor the color for the title */ public void setTitleColor( Color titleColor ) { Color oldVal = this.getTitleColor(); setAttribute( SELECTOR_TITLE, CSSProperty.COLOR, CSSStyleSheet.getAttribute( titleColor ) ); propertyChangeSupport.firePropertyChange("titleColor", oldVal, this.getTitleColor()); } /** * Returns the title-color of the XDivision. * @return titleColor the color for the title */ public Color getTitleColor() { return dynamicStyles == null || dynamicStyles.get(SELECTOR_TITLE) == null ? null : CSSStyleSheet.getForeground((CSSAttributeSet) dynamicStyles.get(SELECTOR_TITLE)); } /** * Determines whether or not the title is clickable. * @param clickable true if the title is clickable */ public void setTitleClickable( boolean clickable ) { boolean oldVal = this.isTitleClickable; this.isTitleClickable = clickable; propertyChangeSupport.firePropertyChange("titleClickable", oldVal, this.isTitleClickable); } /** * Returns true if the title is clickable. * @return boolean true if the title is clickable */ public boolean isTitleClickable() { return this.isTitleClickable; } public SIcon getIcon() { return icon; } public void setIcon(SIcon icon) { SIcon oldVal = this.icon; reloadIfChange(this.icon, icon); this.icon = icon; propertyChangeSupport.firePropertyChange("icon", oldVal, this.icon); } /** * Returns true if the XDivision is shaded. * @return boolean true if the XDivision is shaded */ public boolean isShaded() { return shaded; } /** * Determines whether or not the XDivision is shaded. * @param shaded true if the XDivision is shaded */ public void setShaded(boolean shaded) { if (this.shaded != shaded) { reload(); this.shaded = shaded; propertyChangeSupport.firePropertyChange("shaded", !this.shaded, this.shaded); setRecursivelyVisible(isRecursivelyVisible()); } } @Override public void processLowLevelEvent(String name, String... values) { if (values.length == 1 && "t".equals(values[0])) { setShaded(!shaded); } /* TODO: first focusable component if (!shaded && getComponentCount() > 0) getComponent(0).requestFocus(); else requestFocus(); */ } @Override public void fireIntermediateEvents() { } @Override public boolean isEpochCheckEnabled() { return false; } @Override protected boolean isShowingChildren() { return !shaded; } }
dheid/wings3
wingx/src/main/java/org/wingx/XDivision.java
Java
lgpl-2.1
5,529
/* * $Id: IpWatch.java 3905 2008-07-28 13:55:03Z uckelman $ * * Copyright (c) 2007-2008 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.chat.peer2peer; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.net.InetAddress; import java.net.UnknownHostException; public class IpWatch implements Runnable { private PropertyChangeSupport propSupport = new PropertyChangeSupport(this); private String currentIp; private long wait = 1000; public IpWatch(long waitInterval) { wait = waitInterval; currentIp = findIp(); } public IpWatch() { this(1000); } public void addPropertyChangeListener(PropertyChangeListener l) { propSupport.addPropertyChangeListener(l); } public void run() { while (true) { String newIp = findIp(); propSupport.firePropertyChange("address", currentIp, newIp); //$NON-NLS-1$ currentIp = newIp; try { Thread.sleep(wait); } catch (InterruptedException ex) { } } } public String getCurrentIp() { return currentIp; } private String findIp() { try { InetAddress a[] = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); final StringBuilder buff = new StringBuilder(); for (int i = 0; i < a.length; ++i) { buff.append(a[i].getHostAddress()); if (i < a.length - 1) { buff.append(","); //$NON-NLS-1$ } } return buff.toString(); } // FIXME: review error message catch (UnknownHostException e) { return null; } } public static void main(String[] args) { IpWatch w = new IpWatch(); w.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { System.out.println("Address = " + evt.getNewValue()); //$NON-NLS-1$ } }); System.out.println("Address = " + w.getCurrentIp()); //$NON-NLS-1$ new Thread(w).start(); } }
caiusb/vassal
src/VASSAL/chat/peer2peer/IpWatch.java
Java
lgpl-2.1
2,630
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. 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. *****************************************************************/ package examples.O2AInterface; import jade.core.Runtime; import jade.core.Profile; import jade.core.ProfileImpl; import jade.wrapper.*; /** * This class shows an example of how to run JADE as a library from an external program * and in particular how to start an agent and interact with it by means of the * Object-to-Agent (O2A) interface. * * @author Giovanni Iavarone - Michele Izzo */ public class O2AInterfaceExample { public static void main(String[] args) throws StaleProxyException, InterruptedException { // Get a hold to the JADE runtime Runtime rt = Runtime.instance(); // Launch the Main Container (with the administration GUI on top) listening on port 8888 System.out.println(">>>>>>>>>>>>>>> Launching the platform Main Container..."); Profile pMain = new ProfileImpl(null, 8888, null); pMain.setParameter(Profile.GUI, "true"); ContainerController mainCtrl = rt.createMainContainer(pMain); // Create and start an agent of class CounterAgent System.out.println(">>>>>>>>>>>>>>> Starting up a CounterAgent..."); AgentController agentCtrl = mainCtrl.createNewAgent("CounterAgent", CounterAgent.class.getName(), new Object[0]); agentCtrl.start(); // Wait a bit System.out.println(">>>>>>>>>>>>>>> Wait a bit..."); Thread.sleep(10000); try { // Retrieve O2A interface CounterManager1 exposed by the agent to make it activate the counter System.out.println(">>>>>>>>>>>>>>> Activate counter"); CounterManager1 o2a1 = agentCtrl.getO2AInterface(CounterManager1.class); o2a1.activateCounter(); // Wait a bit System.out.println(">>>>>>>>>>>>>>> Wait a bit..."); Thread.sleep(30000); // Retrieve O2A interface CounterManager2 exposed by the agent to make it de-activate the counter System.out.println(">>>>>>>>>>>>>>> Deactivate counter"); CounterManager2 o2a2 = agentCtrl.getO2AInterface(CounterManager2.class); o2a2.deactivateCounter(); } catch (StaleProxyException e) { e.printStackTrace(); } } }
ekiwi/jade-mirror
src/examples/O2AInterface/O2AInterfaceExample.java
Java
lgpl-2.1
3,081
import sys import time sleep = time.sleep if sys.platform == 'win32': time = time.clock else: time = time.time
egbertbouman/tribler-g
Tribler/Core/DecentralizedTracking/pymdht/core/ptime.py
Python
lgpl-2.1
124
/* * Copyright (C) 2007 Sebastian Sauer <mail@dipe.org> * * This file is part of SuperKaramba. * * SuperKaramba 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. * * SuperKaramba 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 SuperKaramba; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plasmaengine.h" #include <kdebug.h> #include <plasma/dataenginemanager.h> #if 0 #include <QFile> #include <QTextStream> #endif /// \internal helper function that translates plasma data into a QVariantMap. QVariantMap dataToMap(Plasma::DataEngine::Data data) { QVariantMap map; Plasma::DataEngine::DataIterator it(data); while( it.hasNext() ) { it.next(); map.insert(it.key(), it.value()); } return map; } /* /// \internal helper function that translates a QVariantMap into plasma data. Plasma::DataEngine::Data mapToData(QVariantMap map) { Plasma::DataEngine::Data data; for(QVariantMap::Iterator it = map.begin(); it != map.end(); ++it) data.insert(it.key(), it.value()); return data; } */ /***************************************************************************************** * PlasmaSensorConnector */ /// \internal d-pointer class. class PlasmaSensorConnector::Private { public: Meter* meter; QString source; QString format; }; PlasmaSensorConnector::PlasmaSensorConnector(Meter *meter, const QString& source) : QObject(meter), d(new Private) { //kDebug()<<"PlasmaSensorConnector Ctor"<<endl; setObjectName(source); d->meter = meter; d->source = source; } PlasmaSensorConnector::~PlasmaSensorConnector() { //kDebug()<<"PlasmaSensorConnector Dtor"<<endl; delete d; } Meter* PlasmaSensorConnector::meter() const { return d->meter; } QString PlasmaSensorConnector::source() const { return d->source; } void PlasmaSensorConnector::setSource(const QString& source) { d->source = source; } QString PlasmaSensorConnector::format() const { return d->format; } void PlasmaSensorConnector::setFormat(const QString& format) { d->format = format; } void PlasmaSensorConnector::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data) { //kDebug()<<"PlasmaSensorConnector::dataUpdated d->source="<<d->source<<" source="<<source<<endl; if( d->source.isEmpty() ) { emit sourceUpdated(source, dataToMap(data)); return; } if( source != d->source ) { return; } QString v = d->format; Plasma::DataEngine::DataIterator it(data); while( it.hasNext() ) { it.next(); QString s = QString("%%1").arg( it.key() ); v.replace(s,it.value().toString()); } d->meter->setValue(v); } /***************************************************************************************** * PlasmaSensor */ /// \internal d-pointer class. class PlasmaSensor::Private { public: Plasma::DataEngine* engine; QString engineName; explicit Private() : engine(0) {} }; PlasmaSensor::PlasmaSensor(int msec) : Sensor(msec), d(new Private) { kDebug()<<"PlasmaSensor Ctor"<<endl; } PlasmaSensor::~PlasmaSensor() { kDebug()<<"PlasmaSensor Dtor"<<endl; delete d; } Plasma::DataEngine* PlasmaSensor::engineImpl() const { return d->engine; } void PlasmaSensor::setEngineImpl(Plasma::DataEngine* engine, const QString& engineName) { d->engine = engine; d->engineName = engineName; } QString PlasmaSensor::engine() { return d->engine ? d->engineName : QString(); } void PlasmaSensor::setEngine(const QString& name) { //kDebug()<<"PlasmaSensor::setEngine name="<<name<<endl; if( d->engine ) { disconnect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString))); disconnect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString))); Plasma::DataEngineManager::self()->unloadEngine(d->engineName); } d->engineName.clear(); d->engine = Plasma::DataEngineManager::self()->engine(name); if( ! d->engine || ! d->engine->isValid() ) { d->engine = Plasma::DataEngineManager::self()->loadEngine(name); if( ! d->engine || ! d->engine->isValid() ) { kWarning()<<"PlasmaSensor::setEngine: No such engine: "<<name<<endl; return; } } d->engineName = name; connect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString))); connect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString))); //d->engine->setProperty("reportSeconds", true); } bool PlasmaSensor::isValid() const { return d->engine && d->engine->isValid(); } QStringList PlasmaSensor::sources() const { return d->engine ? d->engine->sources() : QStringList(); } QVariant PlasmaSensor::property(const QByteArray& name) const { return d->engine ? d->engine->property(name) : QVariant(); } void PlasmaSensor::setProperty(const QByteArray& name, const QVariant& value) { if( d->engine ) d->engine->setProperty(name, value); } QVariantMap PlasmaSensor::query(const QString& source) { //kDebug()<<"PlasmaSensor::query"<<endl; return d->engine ? dataToMap(d->engine->query(source)) : QVariantMap(); } QObject* PlasmaSensor::connectSource(const QString& source, QObject* visualization) { //kDebug()<<"PlasmaSensor::connectSource source="<<source<<endl; if( ! d->engine ) { kWarning()<<"PlasmaSensor::connectSource: No engine"<<endl; return 0; } if( Meter* m = dynamic_cast<Meter*>(visualization) ) { PlasmaSensorConnector* c = new PlasmaSensorConnector(m, source); d->engine->connectSource(source, c); kDebug()<<"PlasmaSensor::connectSource meter, engine isValid="<<d->engine->isValid(); return c; } d->engine->connectSource(source, visualization ? visualization : this); return 0; } void PlasmaSensor::disconnectSource(const QString& source, QObject* visualization) { //kDebug()<<"PlasmaSensor::disconnectSource"<<endl; if( Meter* m = dynamic_cast<Meter*>(visualization) ) { foreach(PlasmaSensorConnector* c, m->findChildren<PlasmaSensorConnector*>(source)) if( c->meter() == m ) delete c; } else if( d->engine ) { d->engine->disconnectSource(source, visualization ? visualization : this); } else kWarning()<<"PlasmaSensor::disconnectSource: No engine"<<endl; } void PlasmaSensor::update() { kDebug()<<"PlasmaSensor::update"<<endl; /*TODO foreach(QObject *it, *objList) { SensorParams *sp = qobject_cast<SensorParams*>(it); Meter *meter = sp->getMeter(); const QString format = sp->getParam("FORMAT"); //if (format.length() == 0) format = "%um"; //format.replace(QRegExp("%fmb", Qt::CaseInsensitive),QString::number((int)((totalMem - usedMemNoBuffers) / 1024.0 + 0.5))); //meter->setValue(format); } */ } void PlasmaSensor::dataUpdated(const QString& source, Plasma::DataEngine::Data data) { //kDebug()<<"PlasmaSensor::dataUpdated source="<<source<<endl; emit sourceUpdated(source, dataToMap(data)); } #include "plasmaengine.moc"
KDE/superkaramba
src/sensors/plasmaengine.cpp
C++
lgpl-2.1
7,725
tinymce.addI18n('it',{ "Cut": "Taglia", "Heading 5": "Intestazione 5", "Header 2": "Header 2", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Il tuo browser non supporta l'accesso diretto negli Appunti. Per favore usa i tasti di scelta rapida Ctrl+X\/C\/V.", "Heading 4": "Intestazione 4", "Div": "Div", "Heading 2": "Intestazione 2", "Paste": "Incolla", "Close": "Chiudi", "Font Family": "Famiglia font", "Pre": "Pre", "Align right": "Allinea a Destra", "New document": "Nuovo Documento", "Blockquote": "Blockquote", "Numbered list": "Elenchi Numerati", "Heading 1": "Intestazione 1", "Headings": "Intestazioni", "Increase indent": "Aumenta Rientro", "Formats": "Formattazioni", "Headers": "Intestazioni", "Select all": "Seleziona Tutto", "Header 3": "Intestazione 3", "Blocks": "Blocchi", "Undo": "Indietro", "Strikethrough": "Barrato", "Bullet list": "Elenchi Puntati", "Header 1": "Intestazione 1", "Superscript": "Apice", "Clear formatting": "Cancella Formattazione", "Font Sizes": "Dimensioni font", "Subscript": "Pedice", "Header 6": "Intestazione 6", "Redo": "Ripeti", "Paragraph": "Paragrafo", "Ok": "Ok", "Bold": "Grassetto", "Code": "Codice", "Italic": "Corsivo", "Align center": "Allinea al Cento", "Header 5": "Intestazione 5", "Heading 6": "Intestazione 6", "Heading 3": "Intestazione 3", "Decrease indent": "Riduci Rientro", "Header 4": "Intestazione 4", "Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Incolla \u00e8 in modalit\u00e0 testo normale. I contenuti sono incollati come testo normale se non disattivi l'opzione.", "Underline": "Sottolineato", "Cancel": "Annulla", "Justify": "Giustifica", "Inline": "Inlinea", "Copy": "Copia", "Align left": "Allinea a Sinistra", "Visual aids": "Elementi Visivi", "Lower Greek": "Greek Minore", "Square": "Quadrato", "Default": "Default", "Lower Alpha": "Alpha Minore", "Circle": "Cerchio", "Disc": "Disco", "Upper Alpha": "Alpha Superiore", "Upper Roman": "Roman Superiore", "Lower Roman": "Roman Minore", "Name": "Nome", "Anchor": "Fissa", "You have unsaved changes are you sure you want to navigate away?": "Non hai salvato delle modifiche, sei sicuro di andartene?", "Restore last draft": "Ripristina l'ultima bozza.", "Special character": "Carattere Speciale", "Source code": "Codice Sorgente", "B": "B", "R": "R", "G": "G", "Color": "Colore", "Right to left": "Da Destra a Sinistra", "Left to right": "Da Sinistra a Destra", "Emoticons": "Emoction", "Robots": "Robot", "Document properties": "Propriet\u00e0 Documento", "Title": "Titolo", "Keywords": "Parola Chiave", "Encoding": "Codifica", "Description": "Descrizione", "Author": "Autore", "Fullscreen": "Schermo Intero", "Horizontal line": "Linea Orizzontale", "Horizontal space": "Spazio Orizzontale", "Insert\/edit image": "Aggiungi\/Modifica Immagine", "General": "Generale", "Advanced": "Avanzato", "Source": "Fonte", "Border": "Bordo", "Constrain proportions": "Mantieni Proporzioni", "Vertical space": "Spazio Verticale", "Image description": "Descrizione Immagine", "Style": "Stile", "Dimensions": "Dimenzioni", "Insert image": "Inserisci immagine", "Zoom in": "Ingrandisci", "Contrast": "Contrasto", "Back": "Indietro", "Gamma": "Gamma", "Flip horizontally": "Rifletti orizzontalmente", "Resize": "Ridimensiona", "Sharpen": "Contrasta", "Zoom out": "Rimpicciolisci", "Image options": "Opzioni immagine", "Apply": "Applica", "Brightness": "Luminosit\u00e0", "Rotate clockwise": "Ruota in senso orario", "Rotate counterclockwise": "Ruota in senso antiorario", "Edit image": "Modifica immagine", "Color levels": "Livelli colore", "Crop": "Taglia", "Orientation": "Orientamento", "Flip vertically": "Rifletti verticalmente", "Invert": "Inverti", "Insert date\/time": "Inserisci Data\/Ora", "Remove link": "Rimuovi link", "Url": "Url", "Text to display": "Testo da Visualizzare", "Anchors": "Anchors", "Insert link": "Inserisci il Link", "New window": "Nuova Finestra", "None": "No", "The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "L'URL inserito sembra essere un collegamento esterno. Vuoi aggiungere il prefisso necessario http:\/\/?", "Target": "Target", "The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "L'URL inserito sembra essere un indirizzo email. Vuoi aggiungere il prefisso necessario mailto:?", "Insert\/edit link": "Inserisci\/Modifica Link", "Insert\/edit video": "Inserisci\/Modifica Video", "Poster": "Anteprima", "Alternative source": "Alternativo", "Paste your embed code below:": "Incolla il codice d'incorporamento qui:", "Insert video": "Inserisci Video", "Embed": "Incorporare", "Nonbreaking space": "Spazio unificatore", "Page break": "Interruzione di pagina", "Paste as text": "incolla come testo", "Preview": "Anteprima", "Print": "Stampa", "Save": "Salva", "Could not find the specified string.": "Impossibile trovare la parola specifica.", "Replace": "Sostituisci", "Next": "Successivo", "Whole words": "Parole Sbagliate", "Find and replace": "Trova e Sostituisci", "Replace with": "Sostituisci Con", "Find": "Trova", "Replace all": "Sostituisci Tutto", "Match case": "Maiuscole\/Minuscole ", "Prev": "Precedente", "Spellcheck": "Controllo ortografico", "Finish": "Termina", "Ignore all": "Ignora Tutto", "Ignore": "Ignora", "Add to Dictionary": "Aggiungi al Dizionario", "Insert row before": "Inserisci una Riga Prima", "Rows": "Righe", "Height": "Altezza", "Paste row after": "Incolla una Riga Dopo", "Alignment": "Allineamento", "Border color": "Colore bordo", "Column group": "Gruppo di Colonne", "Row": "Riga", "Insert column before": "Inserisci una Colonna Prima", "Split cell": "Dividi Cella", "Cell padding": "Padding della Cella", "Cell spacing": "Spaziatura della Cella", "Row type": "Tipo di Riga", "Insert table": "Inserisci Tabella", "Body": "Body", "Caption": "Didascalia", "Footer": "Footer", "Delete row": "Cancella Riga", "Paste row before": "Incolla una Riga Prima", "Scope": "Campo", "Delete table": "Cancella Tabella", "H Align": "Allineamento H", "Top": "In alto", "Header cell": "cella d'intestazione", "Column": "Colonna", "Row group": "Gruppo di Righe", "Cell": "Cella", "Middle": "In mezzo", "Cell type": "Tipo di Cella", "Copy row": "Copia Riga", "Row properties": "Propriet\u00e0 della Riga", "Table properties": "Propiet\u00e0 della Tabella", "Bottom": "In fondo", "V Align": "Allineamento V", "Header": "Header", "Right": "Destra", "Insert column after": "Inserisci una Colonna Dopo", "Cols": "Colonne", "Insert row after": "Inserisci una Riga Dopo", "Width": "Larghezza", "Cell properties": "Propiet\u00e0 della Cella", "Left": "Sinistra", "Cut row": "Taglia Riga", "Delete column": "Cancella Colonna", "Center": "Centro", "Merge cells": "Unisci Cella", "Insert template": "Inserisci Template", "Templates": "Template", "Background color": "Colore Background", "Custom...": "Personalizzato...", "Custom color": "Colore personalizzato", "No color": "Nessun colore", "Text color": "Colore Testo", "Show blocks": "Mostra Blocchi", "Show invisible characters": "Mostra Caratteri Invisibili", "Words: {0}": "Parole: {0}", "Insert": "Inserisci", "File": "File", "Edit": "Modifica", "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Rich Text Area. Premi ALT-F9 per il men\u00f9. Premi ALT-F10 per la barra degli strumenti. Premi ALT-0 per l'aiuto.", "Tools": "Strumenti", "View": "Visualizza", "Table": "Tabella", "Format": "Formato" });
OpenSlides/tinymce-i18n
langs/it.js
JavaScript
lgpl-2.1
7,599
# Authors: David Goodger; Gunnar Schwant # Contact: goodger@users.sourceforge.net # Revision: $Revision: 21817 $ # Date: $Date: 2005-07-21 13:39:57 -0700 (Thu, 21 Jul 2005) $ # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ German language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { 'author': 'Autor', 'authors': 'Autoren', 'organization': 'Organisation', 'address': 'Adresse', 'contact': 'Kontakt', 'version': 'Version', 'revision': 'Revision', 'status': 'Status', 'date': 'Datum', 'dedication': 'Widmung', 'copyright': 'Copyright', 'abstract': 'Zusammenfassung', 'attention': 'Achtung!', 'caution': 'Vorsicht!', 'danger': '!GEFAHR!', 'error': 'Fehler', 'hint': 'Hinweis', 'important': 'Wichtig', 'note': 'Bemerkung', 'tip': 'Tipp', 'warning': 'Warnung', 'contents': 'Inhalt'} """Mapping of node class name to label text.""" bibliographic_fields = { 'autor': 'author', 'autoren': 'authors', 'organisation': 'organization', 'adresse': 'address', 'kontakt': 'contact', 'version': 'version', 'revision': 'revision', 'status': 'status', 'datum': 'date', 'copyright': 'copyright', 'widmung': 'dedication', 'zusammenfassung': 'abstract'} """German (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
garinh/cs
docs/support/docutils/languages/de.py
Python
lgpl-2.1
1,814
<?php /** * PHPExcel 读取插件类 */ class PHPExcelReaderChajian extends Chajian{ protected function initChajian() { $this->Astr = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO,AP,AQ,AR,AS,AT,AU,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG,BH,BI,BJ,BK,BL,BM,BN,BO,BP,BQ,BR,BS,BT,BU,BV,BW,BX,BY,BZ,CA,CB,CC,CD,CE,CF,CG,CH,CI,CJ,CK,CL,CM,CN,CO,CP,CQ,CR,CS,CT,CU,CV,CW,CX,CY,CZ'; $this->A = explode(',', $this->Astr); $this->AT = array('A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5,'G'=>6,'H'=>7,'I'=>8,'J'=>9,'K'=>10,'L'=>11,'M'=>12,'N'=>13,'O'=>14,'P'=>15,'Q'=>16,'R'=>17,'S'=>18,'T'=>19,'U'=>20,'V'=>21,'W'=>22,'X'=>23,'Y'=>24,'Z'=>25,'AA'=>26,'AB'=>27,'AC'=>28,'AD'=>29,'AE'=>30,'AF'=>31,'AG'=>32,'AH'=>33,'AI'=>34,'AJ'=>35,'AK'=>36,'AL'=>37,'AM'=>38,'AN'=>39,'AO'=>40,'AP'=>41,'AQ'=>42,'AR'=>43,'AS'=>44,'AT'=>45,'AU'=>46,'AV'=>47,'AW'=>48,'AX'=>49,'AY'=>50,'AZ'=>51,'BA'=>52,'BB'=>53,'BC'=>54,'BD'=>55,'BE'=>56,'BF'=>57,'BG'=>58,'BH'=>59,'BI'=>60,'BJ'=>61,'BK'=>62,'BL'=>63,'BM'=>64,'BN'=>65,'BO'=>66,'BP'=>67,'BQ'=>68,'BR'=>69,'BS'=>70,'BT'=>71,'BU'=>72,'BV'=>73,'BW'=>74,'BX'=>75,'BY'=>76,'BZ'=>77,'CA'=>78,'CB'=>79,'CC'=>80,'CD'=>81,'CE'=>82,'CF'=>83,'CG'=>84,'CH'=>85,'CI'=>86,'CJ'=>87,'CK'=>88,'CL'=>89,'CM'=>90,'CN'=>91,'CO'=>92,'CP'=>93,'CQ'=>94,'CR'=>95,'CS'=>96,'CT'=>97,'CU'=>98,'CV'=>99,'CW'=>100,'CX'=>101,'CY'=>102,'CZ'=>103); } public function reader($filePath=null, $index=2) { if(file_exists(ROOT_PATH.'/include/PHPExcel/Reader/Excel2007.php'))include_once(ROOT_PATH.'/include/PHPExcel/Reader/Excel2007.php'); if(file_exists(ROOT_PATH.'/include/PHPExcel/Reader/Excel5.php'))include_once(ROOT_PATH.'/include/PHPExcel/Reader/Excel5.php'); $help = c('xinhu')->helpstr('phpexcel'); if(!class_exists('PHPExcel_Reader_Excel2007'))return '没有安装PHPExcel插件'.$help.''; if($filePath==null)$filePath = $_FILES['file']['tmp_name']; $PHPReader = new PHPExcel_Reader_Excel2007(); if(!$PHPReader->canRead($filePath)){ $PHPReader = new PHPExcel_Reader_Excel5(); if(!$PHPReader->canRead($filePath)){ return '不是正规的Excel文件'.$help.''; } } $PHPExcel = $PHPReader->load($filePath); $rows = array(); $sheet = $PHPExcel->getSheet(0); //第一个表 $allColumn = $sheet->getHighestColumn(); $allRow = $sheet->getHighestRow(); $allCell = $this->AT[$allColumn]; for($row = $index; $row <= $allRow; $row++){ $arr = array(); for($cell= 0; $cell<= $allCell; $cell++){ $val = $sheet->getCellByColumnAndRow($cell, $row)->getValue(); $arr[$this->A[$cell]] = $val; } $rows[] = $arr; } return $rows; } /** 导入到表 */ public function importTable($table, $rows, $fields) { } }
holmesian/xinhu-project
include/chajian/PHPExcelReaderChajian.php
PHP
lgpl-2.1
2,818
#include "nova_renderer/util/platform.hpp" #ifdef NOVA_LINUX #include "x11_window.hpp" namespace nova::renderer { x11_window::x11_window(uint32_t width, uint32_t height, const std::string& title) { display = XOpenDisplay(nullptr); if(display == nullptr) { throw window_creation_error("Failed to open XDisplay"); } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) int screen = DefaultScreen(display); window = XCreateSimpleWindow(display, RootWindow(display, screen), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) 50, 50, width, height, 1, BlackPixel(display, screen), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) WhitePixel(display, screen)); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) XStoreName(display, window, title.c_str()); wm_protocols = XInternAtom(display, "WM_PROTOCOLS", 0); wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0); XSetWMProtocols(display, window, &wm_delete_window, 1); XSelectInput(display, window, ExposureMask | ButtonPressMask | KeyPressMask); XMapWindow(display, window); } x11_window::~x11_window() { XUnmapWindow(display, window); XDestroyWindow(display, window); XCloseDisplay(display); } Window& x11_window::get_x11_window() { return window; } Display* x11_window::get_display() { return display; } void x11_window::on_frame_end() { XEvent event; while(XPending(display) != 0) { XNextEvent(display, &event); switch(event.type) { case ClientMessage: { if(event.xclient.message_type == wm_protocols && event.xclient.data.l[0] == static_cast<long>(wm_delete_window)) { should_window_close = true; } break; } default: break; } } } bool x11_window::should_close() const { return should_window_close; } glm::uvec2 x11_window::get_window_size() const { Window root_window; int x_pos; int y_pos; uint32_t width; uint32_t height; uint32_t border_width; uint32_t depth; XGetGeometry(display, window, &root_window, &x_pos, &y_pos, &width, &height, &border_width, &depth); return {width, height}; } } // namespace nova::renderer #endif
DethRaid/vulkan-mod
src/render_engine/vulkan/x11_window.cpp
C++
lgpl-2.1
2,769
package codechicken.lib.math; import net.minecraft.util.math.BlockPos; //TODO cleanup. public class MathHelper { public static final double phi = 1.618033988749894; public static final double pi = Math.PI; public static final double todeg = 57.29577951308232; public static final double torad = 0.017453292519943; public static final double sqrt2 = 1.414213562373095; public static double[] SIN_TABLE = new double[65536]; static { for (int i = 0; i < 65536; ++i) { SIN_TABLE[i] = Math.sin(i / 65536D * 2 * Math.PI); } SIN_TABLE[0] = 0; SIN_TABLE[16384] = 1; SIN_TABLE[32768] = 0; SIN_TABLE[49152] = 1; } public static double sin(double d) { return SIN_TABLE[(int) ((float) d * 10430.378F) & 65535]; } public static double cos(double d) { return SIN_TABLE[(int) ((float) d * 10430.378F + 16384.0F) & 65535]; } /** * @param a The value * @param b The value to approach * @param max The maximum step * @return the closed value to b no less than max from a */ public static float approachLinear(float a, float b, float max) { return (a > b) ? (a - b < max ? b : a - max) : (b - a < max ? b : a + max); } /** * @param a The value * @param b The value to approach * @param max The maximum step * @return the closed value to b no less than max from a */ public static double approachLinear(double a, double b, double max) { return (a > b) ? (a - b < max ? b : a - max) : (b - a < max ? b : a + max); } /** * @param a The first value * @param b The second value * @param d The interpolation factor, between 0 and 1 * @return a+(b-a)*d */ public static float interpolate(float a, float b, float d) { return a + (b - a) * d; } /** * @param a The first value * @param b The second value * @param d The interpolation factor, between 0 and 1 * @return a+(b-a)*d */ public static double interpolate(double a, double b, double d) { return a + (b - a) * d; } /** * @param a The value * @param b The value to approach * @param ratio The ratio to reduce the difference by * @return a+(b-a)*ratio */ public static double approachExp(double a, double b, double ratio) { return a + (b - a) * ratio; } /** * @param a The value * @param b The value to approach * @param ratio The ratio to reduce the difference by * @param cap The maximum amount to advance by * @return a+(b-a)*ratio */ public static double approachExp(double a, double b, double ratio, double cap) { double d = (b - a) * ratio; if (Math.abs(d) > cap) { d = Math.signum(d) * cap; } return a + d; } /** * @param a The value * @param b The value to approach * @param ratio The ratio to reduce the difference by * @param c The value to retreat from * @param kick The difference when a == c * @return */ public static double retreatExp(double a, double b, double c, double ratio, double kick) { double d = (Math.abs(c - a) + kick) * ratio; if (d > Math.abs(b - a)) { return b; } return a + Math.signum(b - a) * d; } /** * @param value The value * @param min The min value * @param max The max value * @return The clipped value between min and max */ public static double clip(double value, double min, double max) { if (value > max) { value = max; } if (value < min) { value = min; } return value; } /** * @param value The value * @param min The min value * @param max The max value * @return The clipped value between min and max */ public static float clip(float value, float min, float max) { if (value > max) { value = max; } if (value < min) { value = min; } return value; } /** * @param value The value * @param min The min value * @param max The max value * @return The clipped value between min and max */ public static int clip(int value, int min, int max) { if (value > max) { value = max; } if (value < min) { value = min; } return value; } /** * Maps a value range to another value range. * * @param valueIn The value to map. * @param inMin The minimum of the input value range. * @param inMax The maximum of the input value range * @param outMin The minimum of the output value range. * @param outMax The maximum of the output value range. * @return The mapped value. */ public static double map(double valueIn, double inMin, double inMax, double outMin, double outMax) { return (valueIn - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; } /** * Maps a value range to another value range. * * @param valueIn The value to map. * @param inMin The minimum of the input value range. * @param inMax The maximum of the input value range * @param outMin The minimum of the output value range. * @param outMax The maximum of the output value range. * @return The mapped value. */ public static float map(float valueIn, float inMin, float inMax, float outMin, float outMax) { return (valueIn - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; } /** * Rounds the number of decimal places based on the given multiplier.<br> * e.g.<br> * Input: 17.5245743<br> * multiplier: 1000<br> * Output: 17.534<br> * multiplier: 10<br> * Output 17.5<br><br> * * @param number The input value. * @param multiplier The multiplier. * @return The input rounded to a number of decimal places based on the multiplier. */ public static double round(double number, double multiplier) { return Math.round(number * multiplier) / multiplier; } /** * Rounds the number of decimal places based on the given multiplier.<br> * e.g.<br> * Input: 17.5245743<br> * multiplier: 1000<br> * Output: 17.534<br> * multiplier: 10<br> * Output 17.5<br><br> * * @param number The input value. * @param multiplier The multiplier. * @return The input rounded to a number of decimal places based on the multiplier. */ public static float round(float number, float multiplier) { return Math.round(number * multiplier) / multiplier; } /** * @return min <= value <= max */ public static boolean between(double min, double value, double max) { return min <= value && value <= max; } public static int approachExpI(int a, int b, double ratio) { int r = (int) Math.round(approachExp(a, b, ratio)); return r == a ? b : r; } public static int retreatExpI(int a, int b, int c, double ratio, int kick) { int r = (int) Math.round(retreatExp(a, b, c, ratio, kick)); return r == a ? b : r; } public static int floor(double d) { return net.minecraft.util.math.MathHelper.floor_double(d); } public static int floor(float d) { return net.minecraft.util.math.MathHelper.floor_float(d); } public static int ceil(double d) { return net.minecraft.util.math.MathHelper.ceiling_double_int(d); } public static int ceil(float d) { return net.minecraft.util.math.MathHelper.ceiling_float_int(d); } public static float sqrt(float f) { return net.minecraft.util.math.MathHelper.sqrt_float(f); } public static float sqrt(double f) { return net.minecraft.util.math.MathHelper.sqrt_double(f); } public static int roundAway(double d) { return (int) (d < 0 ? Math.floor(d) : Math.ceil(d)); } public static int compare(int a, int b) { return a == b ? 0 : a < b ? -1 : 1; } public static int compare(double a, double b) { return a == b ? 0 : a < b ? -1 : 1; } public static int absSum(BlockPos pos) { return (pos.getX() < 0 ? -pos.getX() : pos.getX()) + (pos.getY() < 0 ? -pos.getY() : pos.getY()) + (pos.getZ() < 0 ? -pos.getZ() : pos.getZ()); } public static boolean isAxial(BlockPos pos) { return pos.getX() == 0 ? (pos.getY() == 0 || pos.getZ() == 0) : (pos.getY() == 0 && pos.getZ() == 0); } public static int toSide(BlockPos pos) { if (!isAxial(pos)) { return -1; } if (pos.getY() < 0) { return 0; } if (pos.getY() > 0) { return 1; } if (pos.getZ() < 0) { return 2; } if (pos.getZ() > 0) { return 3; } if (pos.getX() < 0) { return 4; } if (pos.getX() > 0) { return 5; } return -1; } }
darkeports/tc5-port
src/main/java/thaumcraft/codechicken/lib/math/MathHelper.java
Java
lgpl-2.1
9,265
/******************************************************************************* * Copyright 2002 National Student Clearinghouse * * This code is part of the Meteor system as defined and specified * by the National Student Clearinghouse and the Meteor Sponsors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ******************************************************************************/ package org.meteornetwork.meteor.common.abstraction.index; import org.meteornetwork.meteor.common.xml.indexresponse.DataProvider; import org.meteornetwork.meteor.common.xml.indexresponse.DataProviders; import org.meteornetwork.meteor.common.xml.indexresponse.IndexProviderData; import org.meteornetwork.meteor.common.xml.indexresponse.IndexProviderMessages; import org.meteornetwork.meteor.common.xml.indexresponse.Message; import org.meteornetwork.meteor.common.xml.indexresponse.MeteorIndexResponse; import org.meteornetwork.meteor.common.xml.indexresponse.types.RsMsgLevelEnum; public class MeteorIndexResponseWrapper { private final MeteorIndexResponse response; public MeteorIndexResponseWrapper() { response = new MeteorIndexResponse(); response.setDataProviders(new DataProviders()); } /** * Add index provider information to the response. * * @param id * the ID of this index provider * @param name * the name of this index provider * @param url * the contact URL of this index provider */ public void setIndexProviderData(String id, String name, String url) { IndexProviderData data = new IndexProviderData(); data.setEntityID(id); data.setEntityName(name); data.setEntityURL(url); response.setIndexProviderData(data); } /** * Add a message to this response * * @param messageText * the text of the message * @param level * the severity level of the message */ public void addMessage(String messageText, RsMsgLevelEnum level) { Message message = new Message(); message.setRsMsg(messageText); message.setRsMsgLevel(level.name()); if (response.getIndexProviderMessages() == null) { response.setIndexProviderMessages(new IndexProviderMessages()); } response.getIndexProviderMessages().addMessage(message); } /** * Add one or more Data Provider objects to the response * * @param dataProviders * the data providers to add to the response */ public void addDataProviders(DataProvider... dataProviders) { for (DataProvider dataProvider : dataProviders) { response.getDataProviders().addDataProvider(dataProvider); } } /** * Add Data Provider objects to the response * * @param dataProviders * an iterable collection of Data Providers to add to the * response */ public void addDataProviders(Iterable<DataProvider> dataProviders) { for (DataProvider dataProvider : dataProviders) { response.getDataProviders().addDataProvider(dataProvider); } } /** * Access a mutable version of the response. * * @return A mutable version of the internal MeteorIndexResponse object */ public MeteorIndexResponse getResponse() { return response; } }
NationalStudentClearinghouse/Meteor4
meteorlib/src/main/java/org/meteornetwork/meteor/common/abstraction/index/MeteorIndexResponseWrapper.java
Java
lgpl-2.1
3,856