code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MULTIPLY_CONJUGATE_CC_H #define INCLUDED_GR_MULTIPLY_CONJUGATE_CC_H #include <gr_core_api.h> #include <gr_sync_block.h> class gr_multiply_conjugate_cc; typedef boost::shared_ptr<gr_multiply_conjugate_cc> gr_multiply_conjugate_cc_sptr; GR_CORE_API gr_multiply_conjugate_cc_sptr gr_make_multiply_conjugate_cc (size_t vlen=1); /*! * \brief Multiplies a stream by the conjugate of the second stream * \ingroup math_blk */ class GR_CORE_API gr_multiply_conjugate_cc : public gr_sync_block { private: friend GR_CORE_API gr_multiply_conjugate_cc_sptr gr_make_multiply_conjugate_cc (size_t vlen); gr_multiply_conjugate_cc (size_t vlen); size_t d_vlen; public: virtual int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; #endif /* INCLUDED_GR_MULTIPLY_CONJUGATE_CC_H */
owaiskhan/Retransmission-Combining
gnuradio-core/src/lib/general/gr_multiply_conjugate_cc.h
C
gpl-3.0
1,703
/** * Copyright 2015 Poznań Supercomputing and Networking Center * * Licensed under the GNU General Public License, Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/gpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.psnc.synat.wrdz.ru.dao.services.descriptors; import java.util.Collection; import pl.psnc.synat.wrdz.common.dao.GenericQueryFilterFactory; import pl.psnc.synat.wrdz.common.dao.QueryFilter; import pl.psnc.synat.wrdz.ru.entity.services.descriptors.SemanticDescriptor; /** * Specified set of filters for queries concerning {@link SemanticDescriptor} entities. */ public interface SemanticDescriptorFilterFactory extends GenericQueryFilterFactory<SemanticDescriptor> { /** * Filters services' semantic descriptors by their schema names. * * @param name * name of the schema. * @return produced filter. */ QueryFilter<SemanticDescriptor> bySchemaName(String name); /** * Filters services' semantic descriptors by the service identifier. * * @param serviceId * identifier of the service. * @return produced filter. */ QueryFilter<SemanticDescriptor> byService(long serviceId); /** * Filters descriptors by their visibility. * * @param exposed * if <code>true</code> searches for public services, otherwise searches for private ones. * @return produced filter. */ QueryFilter<SemanticDescriptor> byVisibility(boolean exposed); /** * Filters descriptors by their location. * * @param local * if <code>true</code> searches for locally defined services, otherwise for the remote (harvested) ones. * @return produced filter. */ QueryFilter<SemanticDescriptor> byLocation(boolean local); /** * Filters the descriptors by their deletion marker. * * @param deleted * whether or not the semantic descriptor is marked as deleted. * @return produced filter. */ QueryFilter<SemanticDescriptor> byDeleted(boolean deleted); /** * Filters the descriptors by their location. * * @param locationUrl * location of semantic descriptor. * @return produced filter. */ QueryFilter<SemanticDescriptor> byLocationUrl(String locationUrl); /** * Filters the descriptors by primary keys. * * @param ids * collection of primary key values. * @return produced filter. */ QueryFilter<SemanticDescriptor> byIdIn(Collection<Long> ids); }
psnc-dl/darceo
wrdz/wrdz-ru/dao/src/main/java/pl/psnc/synat/wrdz/ru/dao/services/descriptors/SemanticDescriptorFilterFactory.java
Java
gpl-3.0
3,016
#ifndef SXRMBFOURELEMENTVORTEXDETECTORVIEW_H #define SXRMBFOURELEMENTVORTEXDETECTORVIEW_H #include "ui/beamline/AMXRFDetailedDetectorView.h" #include "beamline/SXRMB/SXRMBFourElementVortexDetector.h" /// Sublcass that allows for setting the maximum energy and peaking time to the four element vortex detector. class SXRMBFourElementVortexDetectorView : public AMXRFDetailedDetectorView { Q_OBJECT public: /// Constructor. SXRMBFourElementVortexDetectorView(SXRMBFourElementVortexDetector *detector, QWidget *parent = 0); /// Destructor. virtual ~SXRMBFourElementVortexDetectorView(){} /// Re-implementing to add the peaking time spin box. virtual void buildDetectorView(); protected slots: /// Handles setting the peaking time. void onPeakingTimeChanged(); protected: /// Implementation method for setMaximumEnergy. The view handles all the visuals, but if there is something specific that needs to be passed on to the detector or viewing subclass, you can implement that here. virtual void setMaximumEnergyImplementation(double energy); /// Pointer to the actual VESPERSSingleElementVortexDetector for setting the peaking time and maximum energy. SXRMBFourElementVortexDetector *fourElementVortexDetector_; /// Spin box for the peaking time. QDoubleSpinBox *peakingTimeSpinBox_; }; #endif // SXRMBFOURELEMENTVORTEXDETECTORVIEW_H
acquaman/acquaman
source/ui/SXRMB/SXRMBFourElementVortexDetectorView.h
C
gpl-3.0
1,355
#include <iostream> #include <string> #include <string.h> #include <stdlib.h> using namespace std; int main() { int N, total, i; char alpha['z' + 1]; size_t len; string frase; cin >> N; getline(cin, frase); while(N--) { memset(alpha, 0, 'z' + 1); getline(cin, frase); len = frase.size(); while(len--) { if(frase[len] < 'a' || 'z' < frase[len] ) { continue; } alpha[frase[len]] = 1; } for(total = 0, i = 'a'; i <= 'z'; i++) { if(alpha[i]) { total++; } } cout << "frase "; if(total == 26) { cout << "completa"; } else if(total >= 13) { cout << "quase completa"; } else { cout << "mal elaborada"; } cout << endl; } return 0; }
chaws/personal
learning/cprogramming/uri/1551/prog.cpp
C++
gpl-3.0
723
package rpg /** Base class of attributes. Almost all RPG systems use a very limited set of attributes, so it is * useful to implement them using a sealed class hierarchy and case objects: * * {{{ * sealed abstract class MyAttribute extends Attribute * * case object Strength extends MyAttribute * case object Charisma extends MyAttribute * case object Intelligence extends MyAttribute * }}} * * This has certain advantages: * * - own super-type, which is useful for abstract and parameterized types * - sealed hierarchy and case objects come in handy for pattern matching * - `toString` will nicely return the name of the case object * * Attributes should never hold their actual value, because they are usually saved in an * attribute-value map. * * @see [[rpg.Attributes]] for how attributes are usually saved */ abstract class Attribute
wookietreiber/arpgt
src/main/scala/Attribute.scala
Scala
gpl-3.0
894
using DevOps.Abstractions.Core.Services; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; namespace DevOps.Abstractions.SourceCode.TypeDeclarations.EntityFramework.Services { public class ClassDeclarationUpsertService<TDbContext> : UpsertService<TDbContext, ClassDeclaration> where TDbContext : SourceCodeTypeDeclarationsDbContext { private readonly IUpsertUniqueListService<TDbContext, Attribute, AttributeListCollection, AttributeListCollectionAssociation> _attributeLists; private readonly IUpsertUniqueListService<TDbContext, BaseType, BaseList, BaseListAssociation> _baseLists; private readonly IUpsertUniqueListService<TDbContext, ConstraintClause, ConstraintClauseList, ConstraintClauseListAssociation> _constraintClauseLists; private readonly IUpsertUniqueListService<TDbContext, Constructor, ConstructorList, ConstructorListAssociation> _constuctorLists; private readonly IUpsertUniqueListService<TDbContext, DocumentationComment, DocumentationCommentList, DocumentationCommentListAssociation> _documentationCommentLists; private readonly IUpsertUniqueListService<TDbContext, Field, FieldList, FieldListAssociation> _fieldLists; private readonly IUpsertService<TDbContext, Finalizer> _finalizers; private readonly IUpsertService<TDbContext, Identifier> _identifiers; private readonly IUpsertUniqueListService<TDbContext, Method, MethodList, MethodListAssociation> _methodLists; private readonly IUpsertUniqueListService<TDbContext, SyntaxToken, ModifierList, ModifierListAssociation> _modifierLists; private readonly IUpsertService<TDbContext, Namespace> _namespaces; private readonly IUpsertUniqueListService<TDbContext, Property, PropertyList, PropertyListAssociation> _propertyLists; private readonly IUpsertUniqueListService<TDbContext, TypeParameter, TypeParameterList, TypeParameterListAssociation> _typeParameterLists; private readonly IUpsertUniqueListService<TDbContext, UsingDirective, UsingDirectiveList, UsingDirectiveListAssociation> _usingDirectiveLists; public ClassDeclarationUpsertService(ICacheService<ClassDeclaration> cache, TDbContext database, ILogger<UpsertService<TDbContext, ClassDeclaration>> logger, IUpsertUniqueListService<TDbContext, Attribute, AttributeListCollection, AttributeListCollectionAssociation> attributeLists, IUpsertUniqueListService<TDbContext, BaseType, BaseList, BaseListAssociation> baseLists, IUpsertUniqueListService<TDbContext, ConstraintClause, ConstraintClauseList, ConstraintClauseListAssociation> constraintClauseLists, IUpsertUniqueListService<TDbContext, DocumentationComment, DocumentationCommentList, DocumentationCommentListAssociation> documentationCommentLists, IUpsertUniqueListService<TDbContext, Field, FieldList, FieldListAssociation> fieldLists, IUpsertService<TDbContext, Finalizer> finalizers, IUpsertService<TDbContext, Identifier> identifiers, IUpsertUniqueListService<TDbContext, Method, MethodList, MethodListAssociation> methodLists, IUpsertUniqueListService<TDbContext, SyntaxToken, ModifierList, ModifierListAssociation> modifierLists, IUpsertService<TDbContext, Namespace> namespaces, IUpsertUniqueListService<TDbContext, Property, PropertyList, PropertyListAssociation> propertyLists, IUpsertUniqueListService<TDbContext, TypeParameter, TypeParameterList, TypeParameterListAssociation> typeParameterLists, IUpsertUniqueListService<TDbContext, UsingDirective, UsingDirectiveList, UsingDirectiveListAssociation> usingDirectiveLists) : base(cache, database, logger, database.ClassDeclarations) { CacheKey = record => $"{nameof(SourceCode)}.{nameof(ClassDeclaration)}={record.AttributeListCollectionId}:{record.BaseListId}:{record.ConstraintClauseListId}:{record.ConstructorListId}:{record.DocumentationCommentListId}:{record.FieldListId}:{record.FinalizerId}:{record.IdentifierId}:{record.MethodListId}:{record.ModifierListId}:{record.NamespaceId}:{record.PropertyListId}:{record.TypeParameterListId}:{record.UsingDirectiveListId}"; _attributeLists = attributeLists ?? throw new ArgumentNullException(nameof(attributeLists)); _baseLists = baseLists ?? throw new ArgumentNullException(nameof(baseLists)); _constraintClauseLists = constraintClauseLists ?? throw new ArgumentNullException(nameof(constraintClauseLists)); _documentationCommentLists = documentationCommentLists ?? throw new ArgumentNullException(nameof(documentationCommentLists)); _fieldLists = fieldLists ?? throw new ArgumentNullException(nameof(fieldLists)); _finalizers = finalizers ?? throw new ArgumentNullException(nameof(finalizers)); _identifiers = identifiers ?? throw new ArgumentNullException(nameof(identifiers)); _methodLists = methodLists ?? throw new ArgumentNullException(nameof(methodLists)); _modifierLists = modifierLists ?? throw new ArgumentNullException(nameof(modifierLists)); _namespaces = namespaces ?? throw new ArgumentNullException(nameof(namespaces)); _propertyLists = propertyLists ?? throw new ArgumentNullException(nameof(propertyLists)); _typeParameterLists = typeParameterLists ?? throw new ArgumentNullException(nameof(typeParameterLists)); _usingDirectiveLists = usingDirectiveLists ?? throw new ArgumentNullException(nameof(usingDirectiveLists)); } protected override async Task<ClassDeclaration> AssignUpsertedReferences(ClassDeclaration record) { record.AttributeListCollection = await _attributeLists.UpsertAsync(record.AttributeListCollection); record.AttributeListCollectionId = record.AttributeListCollection?.AttributeListCollectionId ?? record.AttributeListCollectionId; record.BaseList = await _baseLists.UpsertAsync(record.BaseList); record.BaseListId = record.BaseList?.BaseListId ?? record.BaseListId; record.ConstraintClauseList = await _constraintClauseLists.UpsertAsync(record.ConstraintClauseList); record.ConstraintClauseListId = record.ConstraintClauseList?.ConstraintClauseListId ?? record.ConstraintClauseListId; record.ConstructorList = await _constuctorLists.UpsertAsync(record.ConstructorList); record.ConstructorListId = record.ConstructorList?.ConstructorListId ?? record.ConstructorListId; record.DocumentationCommentList = await _documentationCommentLists.UpsertAsync(record.DocumentationCommentList); record.DocumentationCommentListId = record.DocumentationCommentList?.DocumentationCommentListId ?? record.DocumentationCommentListId; record.FieldList = await _fieldLists.UpsertAsync(record.FieldList); record.FieldListId = record.FieldList?.FieldListId ?? record.FieldListId; record.Finalizer = await _finalizers.UpsertAsync(record.Finalizer); record.FinalizerId = record.Finalizer?.FinalizerId ?? record.FinalizerId; record.Identifier = await _identifiers.UpsertAsync(record.Identifier); record.IdentifierId = record.Identifier?.IdentifierId ?? record.IdentifierId; record.MethodList = await _methodLists.UpsertAsync(record.MethodList); record.MethodListId = record.MethodList?.MethodListId ?? record.MethodListId; record.ModifierList = await _modifierLists.UpsertAsync(record.ModifierList); record.ModifierListId = record.ModifierList?.ModifierListId ?? record.ModifierListId; record.Namespace = await _namespaces.UpsertAsync(record.Namespace); record.NamespaceId = record.Namespace?.NamespaceId ?? record.NamespaceId; record.PropertyList = await _propertyLists.UpsertAsync(record.PropertyList); record.PropertyListId = record.PropertyList?.PropertyListId ?? record.PropertyListId; record.TypeParameterList = await _typeParameterLists.UpsertAsync(record.TypeParameterList); record.TypeParameterListId = record.TypeParameterList?.TypeParameterListId ?? record.TypeParameterListId; record.UsingDirectiveList = await _usingDirectiveLists.UpsertAsync(record.UsingDirectiveList); record.UsingDirectiveListId = record.UsingDirectiveList?.UsingDirectiveListId ?? record.UsingDirectiveListId; return record; } protected override IEnumerable<object> EnumerateReferences(ClassDeclaration record) { yield return record.AttributeListCollection; yield return record.BaseList; yield return record.ConstraintClauseList; yield return record.ConstructorList; yield return record.DocumentationCommentList; yield return record.FieldList; yield return record.Finalizer; yield return record.Identifier; yield return record.MethodList; yield return record.ModifierList; yield return record.Namespace; yield return record.PropertyList; yield return record.TypeParameterList; yield return record.UsingDirectiveList; } protected override Expression<Func<ClassDeclaration, bool>> FindExisting(ClassDeclaration record) => existing => existing.IdentifierId == record.IdentifierId && existing.NamespaceId == record.NamespaceId; } }
cdorst/DevOps
src/Abstractions.SourceCode.TypeDeclarations/EntityFramework/Services/ClassDeclarationUpsertService.cs
C#
gpl-3.0
9,730
{% extends "requerimientos/base_requerimientos.html" %} {% block cuerpo %} <h3>Requerimientos</h3> <div class="row"> <div class="col-lg-10"> {% if perms.requerimientos.add_requerimiento %} <a href="{% url 'requerimientos:crear_requerimiento' %}" class="btn btn-primary"> Crear</a> {% endif %} {% if perms.requerimientos.cargar_requerimientos %} <a href="#" class="btn btn-default"> Importar </a> {% endif %} </div> <div class="col-lg-2 text-right"> <div class="btn-group"> {% if perms.requerimientos.ver_reporte_requerimientos_excel %} <button class="btn btn-default" type="button" onclick="location.href='{% url 'requerimientos:maestro_requerimientos_excel' %}';"> <span class="glyphicon glyphicon-list-alt"></span> </button> {% endif %} </div> </div> </div> <hr/> <div class="row"> <div class="col-lg-12"> <table id="tabla" class="display" cellspacing="0" width="100%"> <thead> <tr> <th class="text-center">CODIGO</th> <th class="text-center">OFICINA SOLICITA</th> <th class="text-center">NIVEL APROB.</th> <th class="text-center">APROB.</th> <th class="text-center">ESTADO.</th> <th class="text-center">FEC_OPER.</th> </tr> </thead> <tbody> {% for requerimiento in requerimientos %} {% if perms.requerimientos.ver_detalle_requerimiento %} <tr onclick="location.href='{% url 'requerimientos:detalle_requerimiento' requerimiento.codigo %}';"> {% else %} <tr> {% endif %} <td>{{ requerimiento.codigo }}</td> <td>{{ requerimiento.oficina }}</td> <td>{{ requerimiento.aprobacionrequerimiento.nivel }}</td> {% if requerimiento.aprobacionrequerimiento.estado %} <td>SI</td> {% else %} <td>NO</td> {% endif %} <td>{{ requerimiento.get_estado_display }}</td> <td>{{ requerimiento.created|date:"d/m/y" }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock cuerpo %} {% block js %} <script> $(document).ready(function() { var table = $('#tabla').DataTable({ "language" : { url : "/static/localizacion/es_ES.json" } }); $('#tabla tr').hover(function() { $(this).css("cursor","pointer"); }); }); </script> {% endblock js %}
joseamaya/tambox
templates/requerimientos/listado_requerimientos.html
HTML
gpl-3.0
2,679
'use strict'; var gulp = require('gulp'); var gutil = require('gulp-util'); var rename = require('gulp-rename'); var concat = require('gulp-concat'); // Style Dependencies var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var minify = require('gulp-minify-css'); // Js Dependencies var uglify = require('gulp-uglify'); var jquery = './node_modules/jquery/dist/jquery.js'; var typedJs = './node_modules/typed.js/lib/typed.js'; //ASSETS var sassFiles = './assets/sass/**/*.scss'; var jsFiles = './assets/js/**/*.js'; //TASKS gulp.task('css', function() { var scss = gulp.src(sassFiles) .pipe(sass({ includePaths: require('node-normalize-scss').includePaths }).on('error', sass.logError)) .pipe(autoprefixer()) .pipe(concat('main.css')) .pipe(minify()) .pipe(gulp.dest('./css')); }); gulp.task('js', function() { return gulp.src([jquery, typedJs, jsFiles]) .pipe(concat('main.js')) .pipe(gulp.dest('./js')) .pipe(rename('main.min.js')) .pipe(uglify()) .pipe(gulp.dest('./js')); }); gulp.task('watch', function() { gulp.watch(sassFiles, ['css']); gulp.watch(jsFiles, ['js']); }); gulp.task('default', ['css', 'js', 'watch']);
canbakis/contactpage
gulpfile.js
JavaScript
gpl-3.0
1,229
<?php /** * TrcIMPLAN Sitio Web - SMIIndicadoresLaLaguna SeguridadAccidentesDeTransito * * Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package TrcIMPLANSitioWeb */ namespace SMIIndicadoresLaLaguna; /** * Clase SeguridadAccidentesDeTransito */ class SeguridadAccidentesDeTransito extends \SMIBase\PublicacionWeb { /** * Constructor */ public function __construct() { // Ejecutar constructor en el padre parent::__construct(); // Título y fecha $this->nombre = 'Accidentes de Tránsito en La Laguna'; $this->fecha = '2014-10-21T16:19:49'; // El nombre del archivo a crear $this->archivo = 'seguridad-accidentes-de-transito'; // La descripción y claves dan información a los buscadores y redes sociales $this->descripcion = 'Cantidad total de accidentes de tránsito por año.'; $this->claves = 'IMPLAN, La Laguna, Vialidad, Movilidad, Seguridad, Sector Automotriz'; // Para el Organizador $this->categorias = array('Vialidad', 'Movilidad', 'Seguridad', 'Sector Automotriz'); $this->fuentes = array('INEGI'); $this->regiones = array('La Laguna'); } // constructor /** * Datos Estructura * * @return array Arreglo con arreglos asociativos */ public function datos_estructura() { return array( 'fecha' => array('enca' => 'Fecha', 'formato' => 'fecha'), 'valor' => array('enca' => 'Dato', 'formato' => 'cantidad'), 'fuente_nombre' => array('enca' => 'Fuente', 'formato' => 'texto'), 'notas' => array('enca' => 'Notas', 'formato' => 'texto')); } // datos_estructura /** * Datos * * @return array Arreglo con arreglos asociativos */ public function datos() { return array( array('fecha' => '1997-12-31', 'valor' => '4404', 'fuente_nombre' => 'INEGI'), array('fecha' => '1998-12-31', 'valor' => '5709', 'fuente_nombre' => 'INEGI'), array('fecha' => '1999-12-31', 'valor' => '6208', 'fuente_nombre' => 'INEGI'), array('fecha' => '2000-12-31', 'valor' => '8169', 'fuente_nombre' => 'INEGI'), array('fecha' => '2001-12-31', 'valor' => '8933', 'fuente_nombre' => 'INEGI'), array('fecha' => '2002-12-31', 'valor' => '8986', 'fuente_nombre' => 'INEGI'), array('fecha' => '2003-12-31', 'valor' => '8507', 'fuente_nombre' => 'INEGI'), array('fecha' => '2005-12-31', 'valor' => '9366', 'fuente_nombre' => 'INEGI'), array('fecha' => '2006-12-31', 'valor' => '10324', 'fuente_nombre' => 'INEGI'), array('fecha' => '2007-12-31', 'valor' => '9612', 'fuente_nombre' => 'INEGI'), array('fecha' => '2008-12-31', 'valor' => '8831', 'fuente_nombre' => 'INEGI'), array('fecha' => '2009-12-31', 'valor' => '6995', 'fuente_nombre' => 'INEGI'), array('fecha' => '2010-12-31', 'valor' => '5577', 'fuente_nombre' => 'INEGI'), array('fecha' => '2011-12-31', 'valor' => '4568', 'fuente_nombre' => 'INEGI'), array('fecha' => '2012-12-31', 'valor' => '4107', 'fuente_nombre' => 'INEGI', 'notas' => 'Número de accidentes registrados durante el año 2012.'), array('fecha' => '2013-12-31', 'valor' => '3362', 'fuente_nombre' => 'INEGI'), array('fecha' => '2014-12-31', 'valor' => '6509', 'fuente_nombre' => 'INEGI'), array('fecha' => '2015-12-31', 'valor' => '7013', 'fuente_nombre' => 'INEGI'), array('fecha' => '2016-12-31', 'valor' => '7275', 'fuente_nombre' => 'INEGI'), array('fecha' => '2017-12-31', 'valor' => '7413', 'fuente_nombre' => 'INEGI'), array('fecha' => '2018-12-31', 'valor' => '7059', 'fuente_nombre' => 'INEGI')); // formateado 0, valor 42, crudo 22 } // datos /** * Otras Regiones Estructura * * @return array Arreglo con arreglos asociativos */ public function otras_regiones_estructura() { return array( 'region_nombre' => array('enca' => 'Región', 'formato' => 'texto'), 'fecha' => array('enca' => 'Fecha', 'formato' => 'fecha'), 'valor' => array('enca' => 'Dato', 'formato' => 'cantidad'), 'fuente_nombre' => array('enca' => 'Fuente', 'formato' => 'texto'), 'notas' => array('enca' => 'Notas', 'formato' => 'texto')); } // otras_regiones_estructura /** * Otras regiones * * @return array Arreglo con arreglos asociativos */ public function otras_regiones() { return array( array('region_nombre' => 'Torreón', 'fecha' => '2018-12-31', 'valor' => '4182', 'fuente_nombre' => 'INEGI'), array('region_nombre' => 'Gómez Palacio', 'fecha' => '2018-12-31', 'valor' => '2506', 'fuente_nombre' => 'INEGI'), array('region_nombre' => 'Lerdo', 'fecha' => '2018-12-31', 'valor' => '243', 'fuente_nombre' => 'INEGI'), array('region_nombre' => 'Matamoros', 'fecha' => '2018-12-31', 'valor' => '128', 'fuente_nombre' => 'INEGI'), array('region_nombre' => 'La Laguna', 'fecha' => '2018-12-31', 'valor' => '7059', 'fuente_nombre' => 'INEGI'), array('region_nombre' => 'Coahuila', 'fecha' => '2018-12-31', 'valor' => '13249', 'fuente_nombre' => 'INEGI'), array('region_nombre' => 'Durango', 'fecha' => '2018-12-31', 'valor' => '6147', 'fuente_nombre' => 'INEGI')); } // otras_regiones /** * Mapas * * @return string Código HTML con el iframe de Carto */ public function mapas() { return NULL; } // mapas /** * Observaciones * * @return string Markdown */ public function observaciones() { return <<<OBSERVACIONES_FINAL Consulta la [Base de Datos](http://www.inegi.org.mx/sistemas/olap/Proyectos/bd/continuas/transporte/accidentes.asp?s=est&c=13159&proy=atus_accidentes) OBSERVACIONES_FINAL; } // observaciones } // Clase SeguridadAccidentesDeTransito ?>
TRCIMPLAN/trcimplan.github.io
lib/SMIIndicadoresLaLaguna/SeguridadAccidentesDeTransito.php
PHP
gpl-3.0
6,778
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. ************************************************************************/ Espo.define('Views.ScheduledJob.List', 'Views.List', function (Dep) { return Dep.extend({ searchPanel: false, setup: function () { Dep.prototype.setup.call(this); this.createView('search', 'Base', { el: '#main > .search-container', template: 'scheduled-job.cronjob' }); }, afterRender: function () { Dep.prototype.afterRender.call(this); $.ajax({ type: 'GET', url: 'Admin/action/cronMessage', error: function (x) { }.bind(this) }).done(function (data) { this.$el.find('.cronjob .message').html(data.message); this.$el.find('.cronjob .command').html('<strong>' + data.command + '</strong>'); }.bind(this)); }, }); });
lucasmattos/crm
client/src/views/scheduled-job/list.js
JavaScript
gpl-3.0
1,677
#include <stdio.h> enum error { NOT_FOUND = 404, SERVER_ERRO = 500, INVALID_OPERATION = 505 }; int main() { int i = 3; switch (i) { case 0: puts("Nol"); break; case 1: puts("Odin"); break; case 77: case 777: case 7777: puts("Bingo!"); break; default: puts("Error"); break; } }
atommed/OP_repo
lessons/lesson4/switch.c
C
gpl-3.0
330
/* Copyright (C) 2016 Bengt Martensson. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package org.harctoolbox.guicomponents; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; import java.awt.Cursor; import java.awt.Desktop; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.util.List; import javax.swing.DefaultComboBoxModel; import org.harctoolbox.harchardware.HarcHardwareException; import org.harctoolbox.harchardware.comm.LocalSerialPort; import org.harctoolbox.harchardware.comm.LocalSerialPortBuffered; import org.harctoolbox.harchardware.comm.TcpSocketPort; import org.harctoolbox.harchardware.ir.GirsClient; import org.harctoolbox.irscrutinizer.Props; public final class GirsClientBean extends javax.swing.JPanel implements ISendingReceivingBean { public static final String PROP_IPNAME = "PROP_IPNAME"; public static final String PROP_TYPE = "PROP_TYPE"; private static final int defaultPingTimeout = 5000; private static final int defaultBaudRate = 115200; private static final int defaultPortNumber = 33333; private static final int defaultSerialTimeout = 12000; // 10 seconds + margin private static final Type defaultType = Type.serial; private static final String defaultPortName = "/dev/arduino"; private static final String defaultHost = "localhost"; private static final String notInitialized = "not initialized"; private static final String notConnected = "not connected"; private String portName; private int baudRate; private GuiUtils guiUtils; private transient GirsClient<?> hardware; private int portNumber; private String ipName; private int pingTimeout; private Type type; private final Props properties; public void initHardware() throws HarcHardwareException, IOException { if (hardware != null) { if (hardware.isValid()) return; else { hardware.close(); enableStuff(false); setVersion(); } } boolean verbose = properties.getVerbose(); switch (getType()) { case serial: { try { LocalSerialPortBuffered comm = new LocalSerialPortBuffered(getPortName(), getBaudRate(), defaultSerialTimeout, verbose); hardware = new GirsClient<>(comm); } catch (NoSuchPortException | PortInUseException | UnsupportedCommOperationException | IOException | HarcHardwareException ex) { guiUtils.error(ex); } } break; case tcp: { try { TcpSocketPort comm = new TcpSocketPort(ipName, portNumber, defaultSerialTimeout, verbose, TcpSocketPort.ConnectionMode.keepAlive); hardware = new GirsClient<>(comm); } catch (HarcHardwareException | IOException ex) { guiUtils.error(ex); } } break; default: throw new IllegalArgumentException("Type " + getType() + " not yet supported"); } } public static enum Type { serial, tcp, upd, http } public GirsClientBean() { this(null, null); } public GirsClientBean(GuiUtils guiUtils, Props properties) { this.guiUtils = guiUtils; this.properties = properties; this.pingTimeout = defaultPingTimeout; initComponents(); String initialPort = properties != null ? properties.getGirsClientSerialPortName() : defaultPortName; DefaultComboBoxModel<String> model; try { List<String> portList = LocalSerialPort.getSerialPortNames(true); model = new DefaultComboBoxModel<>(portList.toArray(new String[portList.size()])); } catch (IOException | LinkageError ex) { model = new DefaultComboBoxModel<>(new String[]{ initialPort != null ? initialPort : notInitialized }); } portComboBox.setModel(model); boolean hit = false; if (initialPort != null) { for (int i = 0; i < model.getSize(); i++) { if (initialPort.equalsIgnoreCase(model.getElementAt(i))) { hit = true; portComboBox.setSelectedIndex(i); break; } } } String actualPort = initialPort; if (!hit) { // Got a problem here, want to select a port that is not there, at least not now if (model.getSize() > 0) { portComboBox.setSelectedIndex(0); actualPort = portComboBox.getItemAt(0); } } setPortName(actualPort); setBaudRate(properties != null ? properties.getGirsClientSerialPortBaudRate() : defaultBaudRate); setIpName(properties != null ? properties.getGirsClientIPName() : defaultHost); setPortNumber(properties != null ? properties.getGirsClientPortNumber() : defaultPortNumber); setType(properties != null ? Type.valueOf(properties.getGirsClientType()) : defaultType); if (properties != null) { // to be javabeans safe... properties.addVerboseChangeListener((String name1, Object oldValue, Object newValue) -> { if (hardware != null) hardware.setVerbose((Boolean) newValue); }); } } private void setType(Type type) { Type oldType = this.type; this.type = type; propertyChangeSupport.firePropertyChange(PROP_TYPE, oldType, type); if (properties != null) properties.setGirsClientType(type.toString()); } public Type getType() { return type; } /** * @return the port */ public String getPortName() { return portName; } /** * @param portName the port to set */ private void setPortName(String portName) { if (portName == null || portName.isEmpty()) return; String oldPort = this.portName; this.portName = portName; propertyChangeSupport.firePropertyChange(PROP_PORTNAME, oldPort, portName); if (properties != null) properties.setGirsClientSerialPortName(portName); } /** * @return the baudRate */ public int getBaudRate() { return baudRate; } private void setBaudRate(int baudRate) { int oldBaud = this.baudRate; this.baudRate = baudRate; this.baudComboBox.setSelectedItem(Integer.toString(baudRate)); propertyChangeSupport.firePropertyChange(PROP_BAUD, oldBaud, baudRate); if (properties != null) properties.setGirsClientSerialPortBaudRate(baudRate); } /** * @return the version */ public String getVersion() { return isValid() ? versionTextField.getText() : null; } private void setVersion(String version) { versionLabel.setEnabled(hardware.isValid()); versionTextField.setEnabled(hardware.isValid()); versionTextField.setText(version); } private void setVersion() { try { setVersion(hardware.isValid() ? hardware.getVersion() : notConnected); setModules(hardware.isValid() ? hardware.getModules() : null); } catch (IOException ex) { setVersion(notConnected); setModules(null); } } private void setModules(List<String>modules) { modulesTextField.setText(modules == null ? "" : String.join(" ", modules)); } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { // just to be Javabeans safe if (propertyChangeSupport == null) super.addPropertyChangeListener(listener); else propertyChangeSupport.addPropertyChangeListener(listener); } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } private final PropertyChangeSupport propertyChangeSupport = new java.beans.PropertyChangeSupport(this); private void setupPortComboBox(boolean useCached) throws IOException { if (hardware != null) hardware.close(); List<String> portNames = LocalSerialPort.getSerialPortNames(useCached); portNames.add(0, ""); DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(portNames.toArray(new String[portNames.size()])); portComboBox.setModel(model); } private void setIpName(String name) { ipNameTextField.setText(name); String old = ipName; ipName = name; propertyChangeSupport.firePropertyChange(PROP_IPNAME, old, name); if (properties != null) properties.setGirsClientIPName(name); } private void setPortNumber(int val) { portNumberTextField.setText(Integer.toString(val)); int old = portNumber; portNumber = val; propertyChangeSupport.firePropertyChange(PROP_PORTNAME, old, val); if (properties != null) properties.setGirsClientPortNumber(val); } public void setPingTimeout(int val) { pingTimeout = val; } public GirsClient<?> getHardware() { return hardware; } public boolean isPingable(boolean useGui) { Cursor oldCursor = setBusyCursor(); boolean success = false; try { success = InetAddress.getByName(ipName).isReachable(pingTimeout); if (useGui) guiUtils.info(ipName + (success ? " is reachable" : " is not reachable (using Java's isReachable)")); } catch (IOException ex) { if (useGui) guiUtils.info(ipName + " is not reachable (using Java's isReachable): " + ex.getMessage()); } finally { resetCursor(oldCursor); } return success; } private void openClose(boolean opening) throws IOException, HarcHardwareException { Cursor oldCursor = setBusyCursor(); boolean oldIsOpen = hardware.isValid(); try { if (opening) { initHardware(); hardware.open(); boolean canCapture = hardware.hasCaptureModule(); useReceiveForCaptureCheckBox.setEnabled(canCapture); useReceiveForCaptureCheckBox.setSelected(! canCapture); } else { hardware.close(); useReceiveForCaptureCheckBox.setSelected(false); } propertyChangeSupport.firePropertyChange(PROP_ISOPEN, oldIsOpen, hardware.isValid()); } finally { resetCursor(oldCursor); enableStuff(opening && hardware.isValid()); setVersion(); } } private void enableStuff(boolean isOpen) { serialTcpTabbedPane.setEnabled(!isOpen); refreshButton.setEnabled(!isOpen); baudComboBox.setEnabled(!isOpen /*&& settableBaudRate*/); baudRateLabel.setEnabled(!isOpen); portComboBox.setEnabled(!isOpen); serialPortLabel.setEnabled(!isOpen); ipNameTextField.setEnabled(!isOpen); ipLabel.setEnabled(!isOpen); portNumberTextField.setEnabled(!isOpen); portNumberLabel.setEnabled(!isOpen); //typeComboBox.setEnabled(!isOpen); typeLabel.setEnabled(!isOpen); modulesTextField.setEnabled(isOpen); modulesLabel.setEnabled(isOpen); openToggleButton.setSelected(isOpen); useReceiveForCaptureCheckBox.setEnabled(isOpen && hardware.hasCaptureModule()); } private Cursor setBusyCursor() { Cursor oldCursor = getCursor(); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); return oldCursor; } private void resetCursor(Cursor cursor) { setCursor(cursor); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { serialTcpTabbedPane = new javax.swing.JTabbedPane(); serialPanel = new javax.swing.JPanel(); refreshButton = new javax.swing.JButton(); portComboBox = new javax.swing.JComboBox<>(); baudComboBox = new javax.swing.JComboBox<>(); serialPortLabel = new javax.swing.JLabel(); baudRateLabel = new javax.swing.JLabel(); ethernetPanel = new javax.swing.JPanel(); ipLabel = new javax.swing.JLabel(); ipNameTextField = new javax.swing.JTextField(); portNumberLabel = new javax.swing.JLabel(); portNumberTextField = new javax.swing.JTextField(); browseButton = new javax.swing.JButton(); pingButton = new javax.swing.JButton(); typeComboBox = new javax.swing.JComboBox<>(); typeLabel = new javax.swing.JLabel(); openToggleButton = new javax.swing.JToggleButton(); versionLabel = new javax.swing.JLabel(); versionTextField = new javax.swing.JTextField(); modulesTextField = new javax.swing.JTextField(); modulesLabel = new javax.swing.JLabel(); useReceiveForCaptureCheckBox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(800, 120)); serialPanel.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { serialPanelComponentShown(evt); } }); refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Crystal-Clear/22x22/actions/reload.png"))); // NOI18N refreshButton.setText("Refresh"); refreshButton.setToolTipText("Reload list of available serial ports."); refreshButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { refreshButtonActionPerformed(evt); } }); portComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { notInitialized })); portComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { portComboBoxActionPerformed(evt); } }); baudComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "115200", "57600", "38400", "19200", "9600", "4800", "2400", "1200" })); baudComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { baudComboBoxActionPerformed(evt); } }); serialPortLabel.setText("Serial Port"); baudRateLabel.setText("bits/s"); javax.swing.GroupLayout serialPanelLayout = new javax.swing.GroupLayout(serialPanel); serialPanel.setLayout(serialPanelLayout); serialPanelLayout.setHorizontalGroup( serialPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(serialPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(refreshButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(serialPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(portComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(serialPortLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(serialPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(baudRateLabel) .addComponent(baudComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); serialPanelLayout.setVerticalGroup( serialPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, serialPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(serialPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(serialPortLabel) .addComponent(baudRateLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(serialPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(refreshButton) .addComponent(portComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(baudComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); serialTcpTabbedPane.addTab("Serial", serialPanel); ethernetPanel.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { ethernetPanelComponentShown(evt); } }); ipLabel.setText("IP Name/Address"); ipNameTextField.setText("192.168.1.29"); ipNameTextField.setToolTipText("IP-Name or -address of host"); ipNameTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ipNameTextFieldActionPerformed(evt); } }); portNumberLabel.setText("Port"); portNumberTextField.setText("33333"); portNumberTextField.setToolTipText("Port Number"); portNumberTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { portNumberTextFieldActionPerformed(evt); } }); browseButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Crystal-Clear/22x22/apps/browser.png"))); // NOI18N browseButton.setMnemonic('B'); browseButton.setText("Browse"); browseButton.setToolTipText("Browse WWW server at host"); browseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseButtonActionPerformed(evt); } }); pingButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Crystal-Clear/22x22/apps/bell.png"))); // NOI18N pingButton.setMnemonic('P'); pingButton.setText("Ping"); pingButton.setToolTipText("Try to ping host"); pingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pingButtonActionPerformed(evt); } }); typeComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "tcp", "udp", "http" })); typeComboBox.setToolTipText("Socket type"); typeComboBox.setEnabled(false); typeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { typeComboBoxActionPerformed(evt); } }); typeLabel.setText("Type"); javax.swing.GroupLayout ethernetPanelLayout = new javax.swing.GroupLayout(ethernetPanel); ethernetPanel.setLayout(ethernetPanelLayout); ethernetPanelLayout.setHorizontalGroup( ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ethernetPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ipLabel) .addComponent(ipNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(portNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(portNumberLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ethernetPanelLayout.createSequentialGroup() .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(browseButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pingButton)) .addComponent(typeLabel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); ethernetPanelLayout.setVerticalGroup( ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ethernetPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ipLabel) .addComponent(portNumberLabel) .addComponent(typeLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(ethernetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ipNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(portNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(browseButton) .addComponent(pingButton)) .addContainerGap()) ); serialTcpTabbedPane.addTab("Ethernet", ethernetPanel); openToggleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Crystal-Clear/22x22/actions/connect_creating.png"))); // NOI18N openToggleButton.setText("Open"); openToggleButton.setToolTipText("Open or close connection to device."); openToggleButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openToggleButtonActionPerformed(evt); } }); versionLabel.setText("Version"); versionLabel.setEnabled(false); versionTextField.setEditable(false); versionTextField.setEnabled(false); modulesTextField.setEditable(false); modulesTextField.setEnabled(false); modulesLabel.setText("Modules:"); modulesLabel.setEnabled(false); useReceiveForCaptureCheckBox.setText("Use receive for capture"); useReceiveForCaptureCheckBox.setEnabled(false); useReceiveForCaptureCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { useReceiveForCaptureCheckBoxActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(serialTcpTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 535, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(versionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(versionTextField)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(openToggleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(useReceiveForCaptureCheckBox)) .addGap(0, 54, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addComponent(modulesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(modulesTextField))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(openToggleButton) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(versionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(versionLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(useReceiveForCaptureCheckBox)) .addComponent(serialTcpTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modulesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modulesLabel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed Cursor oldCursor = setBusyCursor(); try { setupPortComboBox(false); } catch (IOException ex) { guiUtils.error(ex); } finally { resetCursor(oldCursor); } }//GEN-LAST:event_refreshButtonActionPerformed private void portComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portComboBoxActionPerformed setPortName((String) portComboBox.getSelectedItem()); }//GEN-LAST:event_portComboBoxActionPerformed private void baudComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_baudComboBoxActionPerformed setBaudRate(Integer.parseInt((String) baudComboBox.getSelectedItem())); }//GEN-LAST:event_baudComboBoxActionPerformed private void ipNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ipNameTextFieldActionPerformed setIpName(ipNameTextField.getText()); }//GEN-LAST:event_ipNameTextFieldActionPerformed private void portNumberTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portNumberTextFieldActionPerformed try { int val = Integer.parseInt(portNumberTextField.getText()); setPortNumber(val); } catch (NumberFormatException ex) { guiUtils.error("Cannot parse " + portNumberTextField.getText()); } }//GEN-LAST:event_portNumberTextFieldActionPerformed private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed try { Desktop.getDesktop().browse(URI.create("http://" + ipName)); } catch (IOException ex) { guiUtils.error(ex); } }//GEN-LAST:event_browseButtonActionPerformed private void pingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pingButtonActionPerformed setIpName(ipNameTextField.getText()); isPingable(true); }//GEN-LAST:event_pingButtonActionPerformed private void typeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeComboBoxActionPerformed setType(Type.valueOf((String)typeComboBox.getSelectedItem())); }//GEN-LAST:event_typeComboBoxActionPerformed private void openToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openToggleButtonActionPerformed try { openClose(openToggleButton.isSelected()); } catch (IOException | HarcHardwareException ex) { guiUtils.error(ex); } finally { openToggleButton.setSelected(hardware.isValid()); } }//GEN-LAST:event_openToggleButtonActionPerformed private void serialPanelComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_serialPanelComponentShown setType(Type.serial); }//GEN-LAST:event_serialPanelComponentShown private void ethernetPanelComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_ethernetPanelComponentShown setType(Type.valueOf((String)typeComboBox.getSelectedItem())); }//GEN-LAST:event_ethernetPanelComponentShown private void useReceiveForCaptureCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useReceiveForCaptureCheckBoxActionPerformed if (hardware.isValid()) try { hardware.setUseReceiveForCapture(useReceiveForCaptureCheckBox.isSelected()); } catch (HarcHardwareException ex) { guiUtils.error("Girs server does not support capture"); } }//GEN-LAST:event_useReceiveForCaptureCheckBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> baudComboBox; private javax.swing.JLabel baudRateLabel; private javax.swing.JButton browseButton; private javax.swing.JPanel ethernetPanel; private javax.swing.JLabel ipLabel; private javax.swing.JTextField ipNameTextField; private javax.swing.JLabel modulesLabel; private javax.swing.JTextField modulesTextField; private javax.swing.JToggleButton openToggleButton; private javax.swing.JButton pingButton; private javax.swing.JComboBox<String> portComboBox; private javax.swing.JLabel portNumberLabel; private javax.swing.JTextField portNumberTextField; private javax.swing.JButton refreshButton; private javax.swing.JPanel serialPanel; private javax.swing.JLabel serialPortLabel; private javax.swing.JTabbedPane serialTcpTabbedPane; private javax.swing.JComboBox<String> typeComboBox; private javax.swing.JLabel typeLabel; private javax.swing.JCheckBox useReceiveForCaptureCheckBox; private javax.swing.JLabel versionLabel; private javax.swing.JTextField versionTextField; // End of variables declaration//GEN-END:variables }
bengtmartensson/harctoolboxbundle
src/main/java/org/harctoolbox/guicomponents/GirsClientBean.java
Java
gpl-3.0
34,230
package meghanada; public class Enum1 { public enum KeyType { ZEROZERO("00", null) { @Override public int calc(int old) { String newVal = old + getKeyValue(); return Integer.valueOf(newVal); } }, ZERO("0", null) { @Override public int calc(int old) { return ZEROZERO.calc(old); } }, ONE("1", null), TWO("2", null), THREE("3", null), FOUR("4", null), FIVE("5", null), SIX("6", null), SEVEN("7", null), EIGHT("8", null), NINE("9", null), DELETE("delete", "ic_backspace") { @Override public int calc(int old) { return 0; } }; private final String regionName; private final String number; KeyType(String number, String regionName) { this.number = number; this.regionName = regionName; } public boolean isText() { return regionName == null; } public int calc(int old) { String sOld = String.valueOf(old); if (sOld.equals("0")) { return Integer.valueOf(getKeyValue()); } String newVal = old + getKeyValue(); return Integer.valueOf(newVal); } public String getKeyValue() { return number; } } }
mopemope/meghanada-server
server/src/test/java/meghanada/Enum1.java
Java
gpl-3.0
1,247
package uk.co.lgs.text.service.label; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import simplenlg.framework.NLGFactory; import simplenlg.lexicon.Lexicon; import simplenlg.phrasespec.NPPhraseSpec; import uk.co.lgs.model.graph.GraphModel; import uk.co.lgs.model.segment.graph.GraphSegment; import uk.co.lgs.model.segment.series.SeriesSegment; /** * I am responsible for converting the series labels as received from the * original data into a readable form. * * @author bouncysteve * */ @Component public class LabelServiceImpl implements LabelService { private static final Lexicon LEXICON = Lexicon.getDefaultLexicon(); /** * There is no easy way to tell if a label represents a plural term, so * maintaining a list here for now. This is needed for agreement between the * label and the rest of the phrase. TODO: this needs revisiting as it does * not handle "men", etc. */ private static final List<String> COMMON_PLURAL_TERMS = Arrays.asList("sales", "men", "women"); /** * If either label is shorten than this many words then it doesn't make * sense to shorten them. */ private static final int LIMIT = 6; private final NLGFactory nlgFactory = new NLGFactory(LEXICON); @Override public List<NPPhraseSpec> getLabelsForInitialUse(final GraphModel graphModel) { return getLabelsForInitialUse(graphModel.getGraphSegments().get(0)); } @Override public List<NPPhraseSpec> getLabelsForInitialUse(final GraphSegment graphSegment) { final List<String> labels = Arrays.asList(null, graphSegment.getSeriesSegment(0).getLabel(), graphSegment.getSeriesSegment(1).getLabel()); final List<String> descriptions = Arrays.asList(null, graphSegment.getSeriesSegment(0).getDescription(), graphSegment.getSeriesSegment(1).getDescription()); return getLabelsForInitialUse(descriptions, labels); } @Override public List<NPPhraseSpec> getLabelsForInitialUse(final List<String> descriptions, final List<String> labels) { final List<String> descriptionsWithoutTimeSeries = descriptions.subList(1, descriptions.size()); final List<String> shortLabels = shortenLabels(labels.subList(1, labels.size())); final List<String> newLabels = new ArrayList<>(); for (int index = 0; index < descriptionsWithoutTimeSeries.size(); index++) { String description = descriptionsWithoutTimeSeries.get(index); final String shortLabel = shortLabels.get(index); if (StringUtils.isEmpty(description)) { description = shortLabel; } if (description.equals(shortLabel)) { newLabels.add(description); } else { newLabels.add(description + " (" + shortLabel + ")"); } } final NPPhraseSpec firstSeriesLabel = pluralise(newLabels.get(0)); final NPPhraseSpec secondSeriesLabel = pluralise(newLabels.get(1)); return Arrays.asList(firstSeriesLabel, secondSeriesLabel); } @Override public List<NPPhraseSpec> getLabelsForCommonUse(final GraphSegment graphSegment) { final List<String> shortLabels = shortenLabels(Arrays.asList(graphSegment.getSeriesSegment(0).getLabel(), graphSegment.getSeriesSegment(1).getLabel())); final NPPhraseSpec firstSeriesShortLabel = pluralise(shortLabels.get(0)); final NPPhraseSpec secondSeriesShortLabel = pluralise(shortLabels.get(1)); return Arrays.asList(firstSeriesShortLabel, secondSeriesShortLabel); } @Override public List<NPPhraseSpec> getLabelsForCommonUse(final GraphModel graphModel) { // First label is the time series final List<String> shortLabels = shortenLabels( Arrays.asList(graphModel.getLabels().get(1), graphModel.getLabels().get(2))); final NPPhraseSpec firstSeriesShortLabel = pluralise(shortLabels.get(0)); final NPPhraseSpec secondSeriesShortLabel = pluralise(shortLabels.get(1)); return Arrays.asList(firstSeriesShortLabel, secondSeriesShortLabel); } /** * If labels are long, we can remove common elements to use only the unique * parts. * * @param firstSeriesLabel * @param secondSeriesLabel * @return */ private List<String> shortenLabels(final List<String> seriesLabels) { final List<String> shortLabels = new ArrayList<>(); final String firstSeriesLabel = seriesLabels.get(0); final String secondSeriesLabel = seriesLabels.get(1); final List<String> firstSeriesWords = Arrays.asList(firstSeriesLabel.split(" ")); final List<String> secondSeriesWords = Arrays.asList(secondSeriesLabel.split(" ")); if (firstSeriesWords.size() < LIMIT || secondSeriesWords.size() < LIMIT) { return seriesLabels; } StringBuilder builder = new StringBuilder(); String commonStart = ""; for (final char letter : firstSeriesLabel.toCharArray()) { builder.append(letter); if (secondSeriesLabel.startsWith(builder.toString())) { commonStart = builder.toString(); } else { break; } } if (!commonStart.isEmpty()) { shortLabels.add(capitaliseFirstLetter(firstSeriesLabel.substring(commonStart.length()))); shortLabels.add(capitaliseFirstLetter(secondSeriesLabel.substring(commonStart.length()))); } else { final String reverseFirstSeriesLabel = new StringBuilder(firstSeriesLabel).reverse().toString(); String commonEnd = ""; builder = new StringBuilder(); for (final char letter : reverseFirstSeriesLabel.toCharArray()) { builder.insert(0, letter); if (secondSeriesLabel.endsWith(builder.toString())) { commonEnd = builder.toString(); } else { break; } } if (!commonEnd.isEmpty()) { shortLabels.add(capitaliseFirstLetter( firstSeriesLabel.substring(0, firstSeriesLabel.length() - commonEnd.length()))); shortLabels.add(capitaliseFirstLetter( secondSeriesLabel.substring(0, secondSeriesLabel.length() - commonEnd.length()))); } else { return seriesLabels; } } return shortLabels; } /** * Simple NLG doesn't seem to cope with being given nouns already in the * plural form, so we replace them with the singlular version, and then * pluralise them. * * @param subject * @return */ private NPPhraseSpec pluralise(final String nounString) { boolean initiallyPlural = false; for (final String term : COMMON_PLURAL_TERMS) { if (nounString.toLowerCase().contains(term)) { initiallyPlural = true; break; } } final NPPhraseSpec noun = this.nlgFactory.createNounPhrase(nounString); if (initiallyPlural) { noun.setPlural(true); noun.setHead(nounString); noun.setPlural(true); } return noun; } @Override public NPPhraseSpec getLabelForCommonUse(final GraphSegment graphSegment, final SeriesSegment seriesSegment) { final List<String> shortLabels = shortenLabels(Arrays.asList(graphSegment.getSeriesSegment(0).getLabel(), graphSegment.getSeriesSegment(1).getLabel())); final String shortLabel = shortLabels.get(graphSegment.indexOf(seriesSegment)); return pluralise(shortLabel); } private String capitaliseFirstLetter(final String input) { return input.substring(0, 1).toUpperCase() + input.substring(1); } }
bouncysteve/lineGraphSummariser
src/main/java/uk/co/lgs/text/service/label/LabelServiceImpl.java
Java
gpl-3.0
8,054
{% if data|length > 0 %} <span class="badge"><span class="fa fa-bell"></span> {{ data|length }}</span> {% else %} <span class="fa fa-navicon"></span> {% endif %}
AlexandreDecan/Lexpage
app/notifications/js_templates/button.html
HTML
gpl-3.0
169
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from copy import deepcopy from base import Base class Container(Base): """ Component that allows an entity to contain one or more child entities. """ def __init__(self): Base.__init__(self, children=list, max_bulk=int) @property def saveable_fields(self): fields = self.fields.keys() fields.remove("children") return fields class BulkLimitError(Exception): """Error that gets raised when the item would exceed the bulk limit of the container.""" def __init__(self, bulk, max_bulk): self.bulk = bulk self.max_bulk = max_bulk def __str__(self): return "Item would exceed the bulk limit of the container." class NoFreeSlotError(Exception): """Error that gets raised when the container has no free slots.""" def __str__(self): return "Container can't hold any more items." def get_free_slot(container): """Returns the first slot of the container that is not occupied.""" index = 0 for child in container.children: if not child: return index index += 1 raise NoFreeSlotError def get_total_bulk(container): """Returns the bulk of all items in the container.""" total_bulk = 0 for child in container.children: if child: total_bulk += child.bulk return total_bulk def get_total_weight(container): """Returns the weight of all items in the container.""" total_weight = 0 for child in container.children: if child: total_weight += child.weight return total_weight def get_item(container, slot_or_type): """Returns the item that is in the slot, or has the given type.""" if type(slot_or_type) == int: if len(container.children) >= (slot_or_type + 1): return container.children[slot_or_type] else: for child in container.children: if child and child.item_type == slot_or_type: return child return None def remove_item(container, slot_or_type): """Removes the item at the given slot, or with the given type.""" if type(slot_or_type) == int: item = get_item(container, slot_or_type) if item: container.children[slot_or_type] = None item.container = None item.slot = -1 else: for child in container.children: if child and child.item_type == slot_or_type: container.children[child.slot] = None child.container = None child.slot = -1 def take_item(container, slot_or_type): """Moves the item at the given slot, or with the given type, out of the container and returns it.""" item = get_item(container, slot_or_type) if item: remove_item(container, slot_or_type) return item def put_item(container, item, slot=-1): """Puts the item at the given slot in the container. Returns the item previously at the slot.""" if slot == -1: slot = get_free_slot(container) total_bulk = get_total_bulk(container) total_bulk += item.bulk old_item = get_item(container, slot) if old_item: total_bulk -= old_item.bulk if total_bulk > container.max_bulk: raise BulkLimitError(total_bulk, container.max_bulk) remove_item(container, slot) container.children[slot] = item if item.container: remove_item(item.container, item.slot) item.container = container item.slot = slot return old_item
parpg/parpg
parpg/components/container.py
Python
gpl-3.0
4,212
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>libopencm3: Alternate Function Remap Controls for Timer 2</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">libopencm3 </div> <div id="projectbrief">A free/libre/open-source firmware library for various ARM Cortex-M3 microcontrollers.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>libopencm3</span></a></li> <li><a href="pages.html"><span>General&#160;Information</span></a></li> <li><a href="../../html/index.html"><span>Back&#160;to&#160;Top</span></a></li> <li><a href="../../cm3/html/modules.html"><span>CM3&#160;Core</span></a></li> <li><a href="../../usb/html/modules.html"><span>Generic&#160;USB</span></a></li> <li><a href="../../stm32f0/html/modules.html"><span>STM32F0</span></a></li> <li class="current"><a href="modules.html"><span>STM32F1</span></a></li> <li><a href="../../stm32f2/html/modules.html"><span>STM32F2</span></a></li> <li><a href="../../stm32f3/html/modules.html"><span>STM32F3</span></a></li> <li><a href="../../stm32f4/html/modules.html"><span>STM32F4</span></a></li> <li><a href="../../stm32l0/html/modules.html"><span>STM32L0</span></a></li> <li><a href="../../stm32l1/html/modules.html"><span>STM32L1</span></a></li> <li><a href="../../lm3s/html/modules.html"><span>LM3S</span></a></li> <li><a href="../../lm4f/html/modules.html"><span>LM4F</span></a></li> <li><a href="../../lpc13xx/html/modules.html"><span>LPC13</span></a></li> <li><a href="../../lpc17xx/html/modules.html"><span>LPC17</span></a></li> <li><a href="../../lpc43xx/html/modules.html"><span>LPC43</span></a></li> <li><a href="../../efm32g/html/modules.html"><span>EFM32&#160;Gecko</span></a></li> <li><a href="../../efm32gg/html/modules.html"><span>EFM32&#160;Giant&#160;Gecko</span></a></li> <li><a href="../../efm32lg/html/modules.html"><span>EFM32&#160;Leopard&#160;Gecko</span></a></li> <li><a href="../../efm32tg/html/modules.html"><span>EFM32&#160;Tiny&#160;Gecko</span></a></li> <li><a href="../../sam3a/html/modules.html"><span>SAM3A</span></a></li> <li><a href="../../sam3n/html/modules.html"><span>SAM3N</span></a></li> <li><a href="../../sam3s/html/modules.html"><span>SAM3S</span></a></li> <li><a href="../../sam3u/html/modules.html"><span>SAM3U</span></a></li> <li><a href="../../sam3x/html/modules.html"><span>SAM3X</span></a></li> <li><a href="../../vf6xx/html/modules.html"><span>VF6XX</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('group__afio__remap__tim2.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#define-members">Macros</a> </div> <div class="headertitle"> <div class="title">Alternate Function Remap Controls for Timer 2<div class="ingroups"><a class="el" href="group__STM32F1xx__defines.html">STM32F1xx Defines</a> &raquo; <a class="el" href="group__gpio__defines.html">GPIO Defines</a></div></div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Collaboration diagram for Alternate Function Remap Controls for Timer 2:</div> <div class="dyncontent"> <center><table><tr><td><img src="group__afio__remap__tim2.png" border="0" alt="" usemap="#group____afio____remap____tim2"/> <map name="group____afio____remap____tim2" id="group____afio____remap____tim2"> </map> </td></tr></table></center> </div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="define-members"></a> Macros</h2></td></tr> <tr class="memitem:gaee84b54c82d3504e609d4ff50d9a0940"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__afio__remap__tim2.html#gaee84b54c82d3504e609d4ff50d9a0940">AFIO_MAPR_TIM2_REMAP_NO_REMAP</a>&#160;&#160;&#160;(0x0 &lt;&lt; 8)</td></tr> <tr class="separator:gaee84b54c82d3504e609d4ff50d9a0940"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga12a3bec07757913c8fc51832bc21f9ad"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__afio__remap__tim2.html#ga12a3bec07757913c8fc51832bc21f9ad">AFIO_MAPR_TIM2_REMAP_PARTIAL_REMAP1</a>&#160;&#160;&#160;(0x1 &lt;&lt; 8)</td></tr> <tr class="separator:ga12a3bec07757913c8fc51832bc21f9ad"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7fcac592ae24b3da3c964a59d745545c"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__afio__remap__tim2.html#ga7fcac592ae24b3da3c964a59d745545c">AFIO_MAPR_TIM2_REMAP_PARTIAL_REMAP2</a>&#160;&#160;&#160;(0x2 &lt;&lt; 8)</td></tr> <tr class="separator:ga7fcac592ae24b3da3c964a59d745545c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7ea079b8eebbdd10b292038fc059ec43"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__afio__remap__tim2.html#ga7ea079b8eebbdd10b292038fc059ec43">AFIO_MAPR_TIM2_REMAP_FULL_REMAP</a>&#160;&#160;&#160;(0x3 &lt;&lt; 8)</td></tr> <tr class="separator:ga7ea079b8eebbdd10b292038fc059ec43"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <h2 class="groupheader">Macro Definition Documentation</h2> <a class="anchor" id="ga7ea079b8eebbdd10b292038fc059ec43"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define AFIO_MAPR_TIM2_REMAP_FULL_REMAP&#160;&#160;&#160;(0x3 &lt;&lt; 8)</td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="gpio_8h_source.html#l00859">859</a> of file <a class="el" href="gpio_8h_source.html">gpio.h</a>.</p> </div> </div> <a class="anchor" id="gaee84b54c82d3504e609d4ff50d9a0940"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define AFIO_MAPR_TIM2_REMAP_NO_REMAP&#160;&#160;&#160;(0x0 &lt;&lt; 8)</td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="gpio_8h_source.html#l00856">856</a> of file <a class="el" href="gpio_8h_source.html">gpio.h</a>.</p> </div> </div> <a class="anchor" id="ga12a3bec07757913c8fc51832bc21f9ad"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define AFIO_MAPR_TIM2_REMAP_PARTIAL_REMAP1&#160;&#160;&#160;(0x1 &lt;&lt; 8)</td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="gpio_8h_source.html#l00857">857</a> of file <a class="el" href="gpio_8h_source.html">gpio.h</a>.</p> </div> </div> <a class="anchor" id="ga7fcac592ae24b3da3c964a59d745545c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define AFIO_MAPR_TIM2_REMAP_PARTIAL_REMAP2&#160;&#160;&#160;(0x2 &lt;&lt; 8)</td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="gpio_8h_source.html#l00858">858</a> of file <a class="el" href="gpio_8h_source.html">gpio.h</a>.</p> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Sun May 8 2016 03:29:27 for libopencm3 by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
Aghosh993/TARS_codebase
libopencm3/doc/stm32f1/html/group__afio__remap__tim2.html
HTML
gpl-3.0
11,163
<?php /** * MobileFrontend.hooks.php */ /** * Hook handlers for MobileFrontend extension * * Hook handler method names should be in the form of: * on<HookName>() * For intance, the hook handler for the 'RequestContextCreateSkin' would be called: * onRequestContextCreateSkin() */ class MobileFrontendHooks { /** * LinksUpdate hook handler - saves a count of h2 elements that occur in the WikiPage * @see https://www.mediawiki.org/wiki/Manual:Hooks/LinksUpdate * * @param LinksUpdate $lu * @return bool */ public static function onLinksUpdate( LinksUpdate $lu ) { if ( $lu->getTitle()->isTalkPage() ) { $parserOutput = $lu->getParserOutput(); $sections = $parserOutput->getSections(); $numTopics = 0; foreach ( $sections as $section ) { if ( $section['toclevel'] == 1 ) { $numTopics += 1; } } if ( $numTopics ) { $lu->mProperties['page_top_level_section_count'] = $numTopics; } } return true; } /** * Enables the global booleans $wgHTMLFormAllowTableFormat and $wgUseMediaWikiUIEverywhere * for mobile users. */ private static function enableMediaWikiUI() { // FIXME: Temporary variables, will be deprecated in core in the future global $wgHTMLFormAllowTableFormat, $wgUseMediaWikiUIEverywhere; $mobileContext = MobileContext::singleton(); if ( $mobileContext->shouldDisplayMobileView() && !$mobileContext->isBlacklistedPage() ) { // Force non-table based layouts (see bug 63428) $wgHTMLFormAllowTableFormat = false; // Turn on MediaWiki UI styles so special pages with form are styled. // FIXME: Remove when this becomes the default. $wgUseMediaWikiUIEverywhere = true; } } /** * Obtain the default mobile skin * * @param IContextSource $context * @param MobileContext $mobileContext * @return Skin */ protected static function getDefaultMobileSkin( RequestContext $context, MobileContext $mobileContext ) { $skinName = $mobileContext->getMFConfig()->get( 'MFDefaultSkinClass' ); $betaSkinName = $skinName . 'Beta'; // Force beta for test mode to sure all modules can run $name = $context->getTitle()->getDBkey(); if ( $mobileContext->isBetaGroupMember() && class_exists( $betaSkinName ) ) { $skinName = $betaSkinName; } $skin = new $skinName( $context ); return $skin; } /** * RequestContextCreateSkin hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/RequestContextCreateSkin * * @param IContextSource $context * @param Skin|null|string $skin * @return bool */ public static function onRequestContextCreateSkin( $context, &$skin ) { // FIXME: This shouldn't be a global, it should be possible for other extensions // to set this via a static variable or set function in ULS global $wgULSPosition; $mobileContext = MobileContext::singleton(); $mobileContext->doToggling(); if ( !$mobileContext->shouldDisplayMobileView() || $mobileContext->isBlacklistedPage() ) { return true; } // enable wgUseMediaWikiUIEverywhere self::enableMediaWikiUI(); // FIXME: Remove hack around Universal Language selector bug 57091 $wgULSPosition = 'none'; // Handle any X-Analytics header values in the request by adding them // as log items. X-Analytics header values are serialized key=value // pairs, separated by ';', used for analytics purposes. $xanalytics = $mobileContext->getRequest()->getHeader( 'X-Analytics' ); if ( $xanalytics ) { $xanalytics_arr = explode( ';', $xanalytics ); if ( count( $xanalytics_arr ) > 1 ) { foreach ( $xanalytics_arr as $xanalytics_item ) { $mobileContext->addAnalyticsLogItemFromXAnalytics( $xanalytics_item ); } } else { $mobileContext->addAnalyticsLogItemFromXAnalytics( $xanalytics ); } } // log whether user is using beta/stable $mobileContext->logMobileMode(); // Allow overriding of skin by useskin e.g. useskin=vector&useformat=mobile or by // setting the mobileskin preferences (api only currently) $userSkin = $context->getRequest()->getVal( 'useskin', $context->getUser()->getOption( 'mobileskin' ) ); if ( $userSkin ) { // Normalize the key in case the user is passing gibberish or has old preferences $normalizedSkin = Skin::normalizeKey( $userSkin ); // If the skin has been normalized and is different from user input use it if ( $normalizedSkin === $userSkin ) { $skin = $normalizedSkin; return false; } } $skin = self::getDefaultMobileSkin( $context, $mobileContext ); return false; } /** * MediaWikiPerformAction hook handler (enable mwui for all pages) * @see https://www.mediawiki.org/wiki/Manual:Hooks/MediaWikiPerformAction * * @param OutputPage $output * @param Article $article * @param Title $title * @param User $user * @param RequestContext $request * @param MediaWiki $wiki * @return bool */ public static function onMediaWikiPerformAction( $output, $article, $title, $user, $request, $wiki ) { self::enableMediaWikiUI(); // don't prevent performAction to do anything return true; } /** * SkinTemplateOutputPageBeforeExec hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/SkinTemplateOutputPageBeforeExec * * Adds a link to view the current page in 'mobile view' to the desktop footer. * * @param SkinTemplate $skin * @param QuickTemplate $tpl * @return bool */ public static function onSkinTemplateOutputPageBeforeExec( &$skin, &$tpl ) { MobileFrontendSkinHooks::prepareFooter( $skin, $tpl ); return true; } public static function onSkinAfterBottomScripts( $sk, &$html ) { $context = MobileContext::singleton(); // TODO: We may want to enable the following script on Desktop Minerva... // ... when Minerva is widely used. if ( $context->shouldDisplayMobileView() && $context->isLazyLoadImagesEnabled() ) { $html .= Html::inlineScript( ResourceLoader::filter( 'minify-js', MobileFrontendSkinHooks::gradeCImageSupport() ) ); } return true; } /** * OutputPageBeforeHTML hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/OutputPageBeforeHTML * * Applies MobileFormatter to mobile viewed content * * @param OutputPage $out * @param string $text the HTML to be wrapped inside the #mw-content-text element * @return bool */ public static function onOutputPageBeforeHTML( &$out, &$text ) { $context = MobileContext::singleton(); // Perform a few extra changes if we are in mobile mode if ( $context->shouldDisplayMobileView() ) { $text = ExtMobileFrontend::DOMParse( $out, $text, $context->isBetaGroupMember() ); } return true; } /** * BeforePageRedirect hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageRedirect * * Ensures URLs are handled properly for select special pages. * @param OutputPage $out * @param string $redirect * @param string $code * @return bool */ public static function onBeforePageRedirect( $out, &$redirect, &$code ) { $context = MobileContext::singleton(); $shouldDisplayMobileView = $context->shouldDisplayMobileView(); if ( !$shouldDisplayMobileView ) { return true; } // Bug 43123: force mobile URLs only for local redirects if ( $context->isLocalUrl( $redirect ) ) { $out->addVaryHeader( 'X-Subdomain' ); $out->addVaryHeader( 'X-CS' ); $redirect = $context->getMobileUrl( $redirect ); } return true; } /** * DiffViewHeader hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/DiffViewHeader * * Redirect Diff page to mobile version if appropriate * * @param DifferenceEngine $diff DifferenceEngine object that's calling * @param Revision $oldRev Revision object of the "old" revision (may be null/invalid) * @param Revision $newRev Revision object of the "new" revision * @return bool */ public static function onDiffViewHeader( $diff, $oldRev, $newRev ) { $context = MobileContext::singleton(); // Only do redirects to MobileDiff if user is in mobile view and it's not a special page if ( $context->shouldDisplayMobileView() && !$diff->getContext()->getTitle()->isSpecialPage() ) { $output = $context->getOutput(); $newRevId = $newRev->getId(); // The MobileDiff page currently only supports showing a single revision, so // only redirect to MobileDiff if we are sure this isn't a multi-revision diff. if ( $oldRev ) { // Get the revision immediately before the new revision $prevRev = $newRev->getPrevious(); if ( $prevRev ) { $prevRevId = $prevRev->getId(); $oldRevId = $oldRev->getId(); if ( $prevRevId === $oldRevId ) { $output->redirect( SpecialPage::getTitleFor( 'MobileDiff', $newRevId )->getFullURL() ); } } } else { $output->redirect( SpecialPage::getTitleFor( 'MobileDiff', $newRevId )->getFullURL() ); } } return true; } /** * ResourceLoaderTestModules hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderTestModules * * @param array $testModules * @param ResourceLoader $resourceLoader * @return bool */ public static function onResourceLoaderTestModules( array &$testModules, ResourceLoader &$resourceLoader ) { // FIXME: Global core variable don't use it. global $wgResourceModules; $testFiles = array(); $dependencies = array(); $localBasePath = dirname( __DIR__ ); // find test files for every RL module foreach ( $wgResourceModules as $key => $module ) { $hasTests = false; if ( substr( $key, 0, 7 ) === 'mobile.' && isset( $module['scripts'] ) ) { foreach ( $module['scripts'] as $script ) { $testFile = 'tests/' . dirname( $script ) . '/test_' . basename( $script ); // For resources folder $testFile = str_replace( 'tests/resources/', 'tests/qunit/', $testFile ); // if a test file exists for a given JS file, add it if ( file_exists( $localBasePath . '/' . $testFile ) ) { $testFiles[] = $testFile; $hasTests = true; } } // if test files exist for given module, create a corresponding test module if ( $hasTests ) { $dependencies[] = $key; } } } $testModule = array( 'dependencies' => $dependencies, 'templates' => array( 'section.hogan' => 'tests/qunit/tests.mobilefrontend/section.hogan', 'issues.hogan' => 'tests/qunit/tests.mobilefrontend/issues.hogan', 'page.html' => 'tests/qunit/tests.mobilefrontend/page.html', 'page2.html' => 'tests/qunit/tests.mobilefrontend/page2.html', 'pageWithStrippedRefs.html' => 'tests/qunit/tests.mobilefrontend/pageWithStrippedRefs.html', 'references.html' => 'tests/qunit/tests.mobilefrontend/references.html', 'refSection.html' => 'tests/qunit/tests.mobilefrontend/refSection.html', ), 'localBasePath' => $localBasePath, 'remoteExtPath' => 'MobileFrontend', 'targets' => array( 'mobile', 'desktop' ), 'scripts' => $testFiles, ); // Expose templates module $testModules['qunit']["tests.mobilefrontend"] = $testModule; return true; } /** * GetCacheVaryCookies hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/GetCacheVaryCookies * * @param OutputPage $out * @param array $cookies * @return bool */ public static function onGetCacheVaryCookies( $out, &$cookies ) { $context = MobileContext::singleton(); $mobileUrlTemplate = $context->getMobileUrlTemplate(); // Enables mobile cookies on wikis w/o mobile domain $cookies[] = MobileContext::USEFORMAT_COOKIE_NAME; // Don't redirect to mobile if user had explicitly opted out of it $cookies[] = 'stopMobileRedirect'; if ( $context->shouldDisplayMobileView() || !$mobileUrlTemplate ) { $cookies[] = 'optin'; // beta cookie } // Redirect people who want so from HTTP to HTTPS. Ideally, should be // only for HTTP but we don't vary on protocol. $cookies[] = 'forceHTTPS'; return true; } /** * PageRenderingHash hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/PageRenderingHash * * @param string &$confstr Reference to a hash key string which can be modified * @param User $user User object that is requesting the page * @param array &$forOptions Array of options used to generate the $confstr hash key */ public static function onPageRenderingHash( &$confstr, User $user, &$forOptions ) { $context = MobileContext::singleton(); if ( !$context->shouldDisplayMobileView() ) { return; } if ( $context->isLazyLoadImagesEnabled() ) { $confstr .= '!lazyloadimages'; } if ( $context->imagesDisabled() ) { $confstr .= '!noimg'; } } /** * SkinPreloadExistence hook handler * Disables TOC in output before it grabs HTML * @see https://www.mediawiki.org/wiki/Manual:Hooks/SkinPreloadExistence * * @param Title[] $titles * @param Skin $skin * @return bool */ public static function onSkinPreloadExistence( array &$titles, Skin $skin ) { $context = MobileContext::singleton(); if ( $context->shouldDisplayMobileView() && !$context->isBlacklistedPage() ) { $skin->getOutput()->setTarget( 'mobile' ); } return true; } /** * ResourceLoaderGetConfigVars hook handler * This should be used for variables which: * - vary with the html * - variables that should work cross skin including anonymous users * - used for both, stable and beta mode (don't use * MobileContext::isBetaGroupMember in this function - T127860) * * @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderGetConfigVars * * @param array $vars * @return boolean */ public static function onResourceLoaderGetConfigVars( &$vars ) { $context = MobileContext::singleton(); $config = $context->getMFConfig(); $lessVars = $config->get( 'ResourceLoaderLESSVars' ); $pageProps = $config->get( 'MFQueryPropModules' ); $searchParams = $config->get( 'MFSearchAPIParams' ); // Avoid API warnings and allow integration with optional extensions. if ( defined( 'PAGE_IMAGES_INSTALLED' ) ) { $pageProps[] = 'pageimages'; $searchParams = array_merge_recursive( $searchParams, array( 'piprop' => 'thumbnail', 'pithumbsize' => MobilePage::SMALL_IMAGE_WIDTH, 'pilimit' => 50, ) ); } // We need to check that first descriptions are enabled (the server admin has installed // Wikidata) and then secondly that it is okay to display them prominently in the UI // For instance a server admin may want to make them available in the page via JS for gadgets // but not build them into their experience. $displayDescriptions = $config->get( 'MFDisplayWikibaseDescription' ); $useDescriptions = $config->get( 'MFUseWikibaseDescription' ); // When set turn on Wikidata descriptions // https://phabricator.wikimedia.org/T101719 if ( $useDescriptions && $displayDescriptions ) { if ( !in_array( 'pageterms', $pageProps ) ) { $pageProps[] = 'pageterms'; } $searchParams = array_merge_recursive( $searchParams, array( 'wbptterms' => 'description', ) ); } // Get the licensing agreement that is displayed in the uploading interface. $vars += array( 'wgMFSearchAPIParams' => $searchParams, 'wgMFQueryPropModules' => $pageProps, 'wgMFSearchGenerator' => $config->get( 'MFSearchGenerator' ), 'wgMFNearbyEndpoint' => $config->get( 'MFNearbyEndpoint' ), 'wgMFThumbnailSizes' => array( 'tiny' => MobilePage::TINY_IMAGE_WIDTH, 'small' => MobilePage::SMALL_IMAGE_WIDTH, ), 'wgMFContentNamespace' => $config->get( 'MFContentNamespace' ), 'wgMFEditorOptions' => $config->get( 'MFEditorOptions' ), 'wgMFLicense' => MobileFrontendSkinHooks::getLicense( 'editor' ), 'wgMFSchemaEditSampleRate' => $config->get( 'MFSchemaEditSampleRate' ), 'wgMFSchemaMobileWebLanguageSwitcherSampleRate' => $config->get( 'MFSchemaMobileWebLanguageSwitcherSampleRate' ), 'wgMFExperiments' => $config->get( 'MFExperiments' ), 'wgMFIgnoreEventLoggingBucketing' => $config->get( 'MFIgnoreEventLoggingBucketing' ), 'wgMFEnableJSConsoleRecruitment' => $config->get( 'MFEnableJSConsoleRecruitment' ), 'wgMFPhotoUploadEndpoint' => $config->get( 'MFPhotoUploadEndpoint' ) ? $config->get( 'MFPhotoUploadEndpoint' ) : '', 'wgMFDeviceWidthTablet' => $lessVars['deviceWidthTablet'], 'wgMFCollapseSectionsByDefault' => $config->get( 'MFCollapseSectionsByDefault' ), ); if ( $context->shouldDisplayMobileView() ) { $vars['wgImagesDisabled'] = $context->imagesDisabled(); } // add CodeMirror specific things, if it is installed (for CodeMirror editor) if ( class_exists( 'CodeMirrorHooks' ) ) { $vars += CodeMirrorHooks::getGlobalVariables( MobileContext::singleton() ); $vars['wgMFCodeMirror'] = true; } return true; } /** * Hook for SpecialPage_initList in SpecialPageFactory. * * @param array $list list of special page classes * @return bool hook return value */ public static function onSpecialPage_initList( &$list ) { $ctx = MobileContext::singleton(); // Perform substitutions of pages that are unsuitable for mobile // FIXME: Upstream these changes to core. if ( $ctx->shouldDisplayMobileView() ) { // Replace the standard watchlist view with our custom one $list['Watchlist'] = 'SpecialMobileWatchlist'; $list['EditWatchlist'] = 'SpecialMobileEditWatchlist'; $list['Preferences'] = 'SpecialMobilePreferences'; /* Special:MobileContributions redefines Special:History in * such a way that for Special:Contributions/Foo, Foo is a * username (in Special:History/Foo, Foo is a page name). * Redirect people here as this is essential * Special:Contributions without the bells and whistles. */ $list['Contributions'] = 'SpecialMobileContributions'; } // add Special:Nearby only, if Nearby is activated if ( $ctx->getMFConfig()->get( 'MFNearby' ) ) { $list['Nearby'] = 'SpecialNearby'; } return true; } /** * ListDefinedTags and ChangeTagsListActive hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/ListDefinedTags * @see https://www.mediawiki.org/wiki/Manual:Hooks/ChangeTagsListActive * * @param array $tags * @return bool */ public static function onListDefinedTags( &$tags ) { $tags[] = 'mobile edit'; $tags[] = 'mobile web edit'; return true; } /** * RecentChange_save hook handler that tags mobile changes * @see https://www.mediawiki.org/wiki/Manual:Hooks/RecentChange_save * * @param RecentChange $rc * @return bool */ public static function onRecentChange_save( RecentChange $rc ) { $context = MobileContext::singleton(); $userAgent = $context->getRequest()->getHeader( "User-agent" ); $logType = $rc->getAttribute( 'rc_log_type' ); // Only log edits and uploads if ( $context->shouldDisplayMobileView() && ( $logType === 'upload' || is_null( $logType ) ) ) { $rcId = $rc->getAttribute( 'rc_id' ); $revId = $rc->getAttribute( 'rc_this_oldid' ); $logId = $rc->getAttribute( 'rc_logid' ); ChangeTags::addTags( 'mobile edit', $rcId, $revId, $logId ); // Tag as mobile web edit specifically, if it isn't coming from the apps if ( strpos( $userAgent, 'WikipediaApp/' ) !== 0 ) { ChangeTags::addTags( 'mobile web edit', $rcId, $revId, $logId ); } } return true; } /** * AbuseFilter-GenerateUserVars hook handler that adds a user_mobile variable. * Altering the variables generated for a specific user * * @see hooks.txt in AbuseFilter extension * @param AbuseFilterVariableHolder $vars object to add vars to * @param User $user object * @return bool */ public static function onAbuseFilterGenerateUserVars( $vars, $user ) { $context = MobileContext::singleton(); if ( $context->shouldDisplayMobileView() ) { $vars->setVar( 'user_mobile', true ); } else { $vars->setVar( 'user_mobile', false ); } return true; } /** * AbuseFilter-builder hook handler that adds user_mobile variable to list * of valid vars * * @param array $builder Array in AbuseFilter::getBuilderValues to add to. * @return bool */ public static function onAbuseFilterBuilder( &$builder ) { $builder['vars']['user_mobile'] = 'user-mobile'; return true; } /** * Invocation of hook SpecialPageBeforeExecute * * We use this hook to ensure that login/account creation pages * are redirected to HTTPS if they are not accessed via HTTPS and * $wgSecureLogin == true - but only when using the * mobile site. * * @param SpecialPage $special * @param string $subpage * @return bool */ public static function onSpecialPageBeforeExecute( SpecialPage $special, $subpage ) { $mobileContext = MobileContext::singleton(); $isMobileView = $mobileContext->shouldDisplayMobileView(); $context = $special->getContext(); $out = $context->getOutput(); $secureLogin = $context->getConfig()->get( 'SecureLogin' ); $request = $special->getContext()->getRequest(); $skin = $out->getSkin()->getSkinName(); $name = $special->getName(); // Ensure desktop version of Special:Preferences page gets mobile targeted modules // FIXME: Upstream to core (?) if ( $skin === 'minerva' ) { if ( $name === 'Preferences' ) { $out->addModules( 'skins.minerva.special.preferences.scripts' ); } // Add default warning message to Special:UserLogin and Special:UserCreate // if no warning message set. if ( $name === 'Userlogin' && !$request->getVal( 'warning', null ) && !$context->getUser()->isLoggedIn() ) { $request->setVal( 'warning', 'mobile-frontend-generic-login-new' ); } } if ( $isMobileView ) { if ( $name === 'Search' ) { $out->addModuleStyles( 'skins.minerva.special.search.styles' ); } elseif ( $name === 'Userlogin' ) { $out->addModuleStyles( 'skins.minerva.special.userlogin.styles' ); $out->addModules( 'mobile.special.userlogin.scripts' ); } } return true; } /** * UserLoginComplete hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/UserLoginComplete * * Used here to handle watchlist actions made by anons to be handled after * login or account creation. * * @param User $currentUser * @param string $injected_html * @return bool */ public static function onUserLoginComplete( &$currentUser, &$injected_html ) { $context = MobileContext::singleton(); if ( !$context->shouldDisplayMobileView() ) { return true; } // If 'watch' is set from the login form, watch the requested article $watch = $context->getRequest()->getVal( 'watch' ); if ( !is_null( $watch ) ) { $title = Title::newFromText( $watch ); // protect against watching special pages (these cannot be watched!) if ( !is_null( $title ) && !$title->isSpecialPage() ) { WatchAction::doWatch( $title, $currentUser ); } } return true; } /** * Decide if the login/usercreate page should be overwritten by a mobile only * special specialpage. If not, do some changes to the template. * @param QuickTemplate $tpl Login or Usercreate template * @param String $mode Is this function called in context of UserCreate or UserLogin? */ public static function changeUserLoginCreateForm( &$tpl ) { $context = MobileContext::singleton(); // otherwise just(tm) add a logoheader, if there is any $mfLogo = $context->getMFConfig() ->get( 'MobileFrontendLogo' ); // do nothing in desktop mode if ( $context->shouldDisplayMobileView() && $mfLogo ) { $tpl->extend( 'formheader', Html::openElement( 'div', array( 'class' => 'watermark' ) ) . Html::element( 'img', array( 'src' => $mfLogo, 'alt' => '', ) ) . Html::closeElement( 'div' ) ); } } /** * UserLoginForm hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/UserLoginForm * * @param QuickTemplate $template Login form template object * @return bool */ public static function onUserLoginForm( &$template ) { self::changeUserLoginCreateForm( $template ); return true; } /** * UserCreateForm hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/UserCreateForm * * @param QuickTemplate $template Account creation form template object * @return bool */ public static function onUserCreateForm( &$template ) { self::changeUserLoginCreateForm( $template ); return true; } /** * BeforePageDisplay hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageDisplay * * @param OutputPage $out * @param Skin $sk * @return bool */ public static function onBeforePageDisplay( &$out, &$sk ) { global $wgWPBSkinBlacklist, $wgWPBEnableDefaultBanner; $context = MobileContext::singleton(); $config = $context->getMFConfig(); $mfEnableXAnalyticsLogging = $config->get( 'MFEnableXAnalyticsLogging' ); $mfAppPackageId = $config->get( 'MFAppPackageId' ); $mfAppScheme = $config->get( 'MFAppScheme' ); $mfNoIndexPages = $config->get( 'MFNoindexPages' ); $mfMobileUrlTemplate = $context->getMobileUrlTemplate(); $lessVars = $config->get( 'ResourceLoaderLESSVars' ); $noJsEditing = $config->get( 'MFAllowNonJavaScriptEditing' ); // show banners using WikidataPageBanner, if installed and all pre-conditions fulfilled if ( ExtensionRegistry::getInstance()->isLoaded( 'WikidataPageBanner' ) && $context->isBetaGroupMember() ) { // turn default banners on $wgWPBEnableDefaultBanner = true; // Turn on the banner experiment $needle = array_search( 'minerva', $wgWPBSkinBlacklist ); if ( $needle !== false ) { unset( $wgWPBSkinBlacklist[$needle] ); } } $title = $sk->getTitle(); $request = $context->getRequest(); // Migrate prefixed disableImages cookie to unprefixed cookie. if ( isset( $_COOKIE[$config->get( 'CookiePrefix' ) . 'disableImages'] ) ) { if ( (bool)$request->getCookie( 'disableImages' ) ) { $context->setDisableImagesCookie( true ); } $request->response()->clearCookie( 'disableImages' ); } # Add deep link to a mobile app specified by $wgMFAppScheme if ( ( $mfAppPackageId !== false ) && ( $title->isContentPage() ) && ( $request->getRawQueryString() === '' ) ) { $fullUrl = $title->getFullURL(); $mobileUrl = $context->getMobileUrl( $fullUrl ); $path = preg_replace( "/^([a-z]+:)?(\/)*/", '', $mobileUrl, 1 ); $scheme = 'http'; if ( $mfAppScheme !== false ) { $scheme = $mfAppScheme; } else { $protocol = $request->getProtocol(); if ( $protocol != '' ) { $scheme = $protocol; } } $hreflink = 'android-app://' . $mfAppPackageId . '/' . $scheme . '/' . $path; $out->addLink( array( 'rel' => 'alternate', 'href' => $hreflink ) ); } // an canonical/alternate link is only useful, if the mobile and desktop URL are different // and $wgMFNoindexPages needs to be true if ( $mfMobileUrlTemplate && $mfNoIndexPages ) { if ( !$context->shouldDisplayMobileView() ) { // add alternate link to desktop sites - bug T91183 $desktopUrl = $title->getFullUrl(); $link = array( 'rel' => 'alternate', 'media' => 'only screen and (max-width: ' . $lessVars['deviceWidthTablet'] . ')', 'href' => $context->getMobileUrl( $desktopUrl ), ); } else { // add canonical link to mobile pages, instead of noindex - bug T91183 $link = array( 'rel' => 'canonical', 'href' => $title->getFullUrl(), ); } $out->addLink( $link ); } // set the vary header to User-Agent, if mobile frontend auto detects, if the mobile // view should be delivered and the same url is used for desktop and mobile devices // Bug: T123189 if ( $config->get( 'MFVaryOnUA' ) && $config->get( 'MFAutodetectMobileView' ) && !$config->get( 'MobileUrlTemplate' ) ) { $out->addVaryHeader( 'User-Agent' ); } // Set X-Analytics HTTP response header if necessary if ( $context->shouldDisplayMobileView() ) { $analyticsHeader = ( $mfEnableXAnalyticsLogging ? $context->getXAnalyticsHeader() : false ); if ( $analyticsHeader ) { $resp = $out->getRequest()->response(); $resp->header( $analyticsHeader ); } // in mobile view: always add vary header $out->addVaryHeader( 'Cookie' ); // Allow modifications in mobile only mode Hooks::run( 'BeforePageDisplayMobile', array( &$out, &$sk ) ); // add fallback editor styles to action=edit page $requestAction = $out->getRequest()->getVal( 'action' ); if ( $noJsEditing && ( $requestAction === 'edit' || $requestAction === 'submit' ) ) { $out->addModuleStyles( array( 'skins.minerva.fallbackeditor', 'mobile.messageBox' ) ); } } return true; } /** * AfterBuildFeedLinks hook handler. Remove all feed links in mobile view. * * @param array &$tags Added feed links */ public static function onAfterBuildFeedLinks( array &$tags ) { $context = MobileContext::singleton(); if ( $context->shouldDisplayMobileView() && !$context->getMFConfig()->get( 'MFRSSFeedLink' ) ) { $tags = array(); } } /** * CustomEditor hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/CustomEditor * * @param Article $article * @param User $user * @return bool */ public static function onCustomEditor( $article, $user ) { $context = MobileContext::singleton(); // redirect to Special:MobileEditor if no-JS editing disabled if ( !$context->getMFConfig()->get( 'MFAllowNonJavaScriptEditing' ) ) { // redirect to mobile editor instead of showing desktop editor if ( $context->shouldDisplayMobileView() && !$context->getRequest()->wasPosted() ) { $output = $context->getOutput(); $data = $output->getRequest()->getValues(); // Unset these to avoid a redirect loop but make sure we pass other // parameters to edit e.g. undo actions unset( $data['action'] ); unset( $data['title'] ); $output->redirect( SpecialPage::getTitleFor( 'MobileEditor', $article->getTitle() ) ->getFullURL( $data ) ); return false; } } return true; } /** * Check whether Minerva has been enabled as a desktop skin via the Minerva * beta feature. * * @param User $user * * @return bool */ private static function hasEnabledMinervaBetaFeature( $user ) { $config = MobileContext::singleton()->getMFConfig(); $mfEnableMinervaBetaFeature = $config->get( 'MFEnableMinervaBetaFeature' ); $canEnableMinervaFeature = class_exists( 'BetaFeatures' ) && $mfEnableMinervaBetaFeature; return $canEnableMinervaFeature && BetaFeatures::isFeatureEnabled( $user, 'betafeatures-minerva' ); } /** * GetPreferences hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/GetPreferences * * @param User $user * @param array $preferences * * @return bool */ public static function onGetPreferences( $user, &$preferences ) { $config = MobileContext::singleton()->getMFConfig(); $defaultSkin = $config->get( 'DefaultSkin' ); $definition = array( 'type' => 'api', 'default' => '', ); $preferences[SpecialMobileWatchlist::FILTER_OPTION_NAME] = $definition; $preferences[SpecialMobileWatchlist::VIEW_OPTION_NAME] = $definition; // Remove the Minerva skin from the preferences unless Minerva has been enabled in // BetaFeatures provided that the user has not set it as the default skin. if ( $defaultSkin !== 'minerva' && !self::hasEnabledMinervaBetaFeature( $user ) ) { // Preference key/values are backwards. The value is the name of the skin. The // key is the text+links to display. if ( !empty( $preferences['skin']['options'] ) ) { $key = array_search( 'minerva', $preferences['skin']['options'] ); unset( $preferences['skin']['options'][$key] ); } } // preference that allow a user to set the preffered mobile skin using the api $preferences['mobileskin'] = array( 'type' => 'api', 'default' => '', ); return true; } /** * GetBetaFeaturePreferences hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/GetPreferences * * @param User $user * @param array $preferences * * @return bool */ public static function onGetBetaFeaturePreferences( $user, &$preferences ) { $context = MobileContext::singleton(); $extensionAssetsPath = $context->getConfig()->get( 'ExtensionAssetsPath' ); $mfEnableMinervaBetaFeature = $context->getMFConfig()->get( 'MFEnableMinervaBetaFeature' ); if ( $mfEnableMinervaBetaFeature ) { // Enable the mobile skin on desktop $preferences['betafeatures-minerva'] = array( 'label-message' => 'beta-feature-minerva', 'desc-message' => 'beta-feature-minerva-description', 'info-link' => '//www.mediawiki.org/wiki/Beta_Features/Minerva', 'discussion-link' => '//www.mediawiki.org/wiki/Talk:Beta_Features/Minerva', 'screenshot' => array( 'ltr' => "$extensionAssetsPath/MobileFrontend/images/BetaFeatures/minerva-ltr.svg", 'rtl' => "$extensionAssetsPath/MobileFrontend/images/BetaFeatures/minerva-rtl.svg", ), ); } return true; } /** * Gadgets::allowLegacy hook handler * * @return bool */ public static function onAllowLegacyGadgets() { return !MobileContext::singleton()->shouldDisplayMobileView(); } /** * UnitTestsList hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/UnitTestsList * * @param array $files * @return bool */ public static function onUnitTestsList( &$files ) { $files[] = __DIR__ . '/../tests/phpunit'; return true; } /** * CentralAuthLoginRedirectData hook handler * Saves mobile host so that the CentralAuth wiki could redirect back properly * * @see CentralAuthHooks::doCentralLoginRedirect in CentralAuth extension * @param CentralAuthUser $centralUser * @param array $data * * @return bool */ public static function onCentralAuthLoginRedirectData( $centralUser, &$data ) { $context = MobileContext::singleton(); $server = $context->getConfig()->get( 'Server' ); if ( $context->shouldDisplayMobileView() ) { $data['mobileServer'] = $context->getMobileUrl( $server ); } return true; } /** * CentralAuthSilentLoginRedirect hook handler * Points redirects from CentralAuth wiki to mobile domain if user has logged in from it * @see SpecialCentralLogin in CentralAuth extension * @param CentralAuthUser $centralUser * @param string $url to redirect to * @param array $info token information * * @return bool */ public static function onCentralAuthSilentLoginRedirect( $centralUser, &$url, $info ) { if ( isset( $info['mobileServer'] ) ) { $mobileUrlParsed = wfParseUrl( $info['mobileServer'] ); $urlParsed = wfParseUrl( $url ); $urlParsed['host'] = $mobileUrlParsed['host']; $url = wfAssembleUrl( $urlParsed ); } return true; } /** * ResourceLoaderRegisterModules hook handler. * * Registers: * * * EventLogging schema modules, if the EventLogging extension is loaded; * * Modules for the Visual Editor overlay, if the VisualEditor extension is loaded; and * * Modules for the notifications overlay, if the Echo extension is loaded. * * @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderRegisterModules * * @param ResourceLoader &$resourceLoader The ResourceLoader object * @return bool Always true */ public static function onResourceLoaderRegisterModules( ResourceLoader &$resourceLoader ) { $resourceBoilerplate = array( 'localBasePath' => dirname( __DIR__ ), 'remoteExtPath' => 'MobileFrontend', ); self::registerMobileLoggingSchemasModule( $resourceLoader ); // add VisualEditor related modules only, if VisualEditor seems to be installed - T85007 if ( class_exists( 'VisualEditorHooks' ) ) { $resourceLoader->register( array( 'mobile.editor.ve' => $resourceBoilerplate + array( 'dependencies' => array( 'ext.visualEditor.mobileArticleTarget', 'mobile.editor.common', 'mobile.overlays', ), 'styles' => array( 'resources/mobile.editor.ve/VisualEditorOverlay.less', ), 'scripts' => array( 'resources/mobile.editor.ve/ve.init.mw.MobileFrontendArticleTarget.js', 'resources/mobile.editor.ve/VisualEditorOverlay.js', ), 'templates' => array( 'contentVE.hogan' => 'resources/mobile.editor.ve/contentVE.hogan', 'toolbarVE.hogan' => 'resources/mobile.editor.ve/toolbarVE.hogan', ), 'messages' => array( 'mobile-frontend-page-edit-summary', 'mobile-frontend-editor-editing', ), 'targets' => array( 'mobile', ), ), ) ); } // add Echo, if it's installed if ( class_exists( 'MWEchoNotifUser' ) ) { $resourceLoader->register( array( 'skins.minerva.notifications' => $resourceBoilerplate + array( 'dependencies' => array( 'mobile.overlays', 'skins.minerva.scripts', 'mediawiki.ui.anchor' ), 'scripts' => array( 'resources/skins.minerva.notifications/init.js', ), 'targets' => array( 'mobile', 'desktop' ), ), 'mobile.notifications.overlay' => $resourceBoilerplate + array( 'dependencies' => array( 'mobile.overlays', 'ext.echo.ui', ), 'scripts' => array( 'resources/mobile.notifications.overlay/NotificationsOverlay.js', ), 'styles' => array( 'resources/mobile.notifications.overlay/NotificationsOverlay.less', ), 'messages' => array( // defined in Echo 'echo-none', 'notifications', 'echo-overlay-link', ), 'targets' => array( 'mobile', 'desktop' ), ), ) ); }; return true; } /** * ResourceLoaderGetLessVars hook handler * * Add the context-based less variables. * * @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderGetLessVars * @param array &$lessVars Variables already added */ public static function onResourceLoaderGetLessVars( &$lessVars ) { $config = MobileContext::singleton()->getMFConfig(); $lessVars = array_merge( $lessVars, array( 'wgMFDeviceWidthMobileSmall' => "{$config->get( 'MFDeviceWidthMobileSmall' )}px", 'wgMFThumbnailTiny' => MobilePage::TINY_IMAGE_WIDTH . 'px', 'wgMFThumbnailSmall' => MobilePage::SMALL_IMAGE_WIDTH . 'px' ) ); } /** * EventLoggingRegisterSchemas hook handler. * * Registers our EventLogging schemas so that they can be converted to * ResourceLoaderSchemaModules by the EventLogging extension. * * If the module has already been registered in * onResourceLoaderRegisterModules, then it is overwritten. * * @param array $schemas The schemas currently registered with the EventLogging * extension * @return bool Always true */ public static function onEventLoggingRegisterSchemas( &$schemas ) { $schemas['MobileWebMainMenuClickTracking'] = 11568715; $schemas['MobileWebSearch'] = 12054448; $schemas['MobileWebLanguageSwitcher'] = 15302503; return true; } /** * Registers the mobile.logging.* modules. * * If the EventLogging extension is loaded, then the modules are defined such that they * depend on their associated EventLogging-created schema module. * * If, however, the EventLogging extension isn't loaded, then the modules are defined such * that no additional assets are requested by the ResourceLoader, i.e. they are stub * modules. * * @param ResourceLoader &$resourceLoader The ResourceLoader object */ private static function registerMobileLoggingSchemasModule( $resourceLoader ) { $mfResourceFileModuleBoilerplate = array( 'localBasePath' => dirname( __DIR__ ), 'remoteExtPath' => 'MobileFrontend', 'targets' => array( 'mobile', 'desktop' ), ); $schemaEdit = $mfResourceFileModuleBoilerplate; $schemaMobileWebLanguageSwitcher = $mfResourceFileModuleBoilerplate; $schemaMobileWebMainMenuClickTracking = $mfResourceFileModuleBoilerplate; $schemaMobileWebSearch = $mfResourceFileModuleBoilerplate; if ( class_exists( 'EventLogging' ) ) { // schema.Edit is provided by WikimediaEvents if ( $resourceLoader->isModuleRegistered( 'schema.Edit' ) ) { $schemaEdit += array( 'dependencies' => array( 'schema.Edit', 'mobile.user' ), 'scripts' => array( 'resources/mobile.loggingSchemas/schemaEdit.js', ) ); } $schemaMobileWebLanguageSwitcher += array( 'dependencies' => array( 'schema.MobileWebLanguageSwitcher', 'mobile.context' ), 'scripts' => array( 'resources/mobile.loggingSchemas/schemaMobileWebLanguageSwitcher.js', ), ); $schemaMobileWebMainMenuClickTracking += array( 'dependencies' => array( 'schema.MobileWebMainMenuClickTracking', 'mobile.context', 'mobile.user' ), 'scripts' => array( 'resources/mobile.loggingSchemas/schemaMobileWebMainMenuClickTracking.js', ) ); $schemaMobileWebSearch += array( 'dependencies' => array( 'schema.MobileWebSearch', 'mobile.context' ), 'scripts' => array( 'resources/mobile.loggingSchemas/schemaMobileWebSearch.js', ) ); } $resourceLoader->register( array( 'mobile.loggingSchemas.edit' => $schemaEdit, 'mobile.loggingSchemas.mobileWebLanguageSwitcher' => $schemaMobileWebLanguageSwitcher, 'mobile.loggingSchemas.mobileWebMainMenuClickTracking' => $schemaMobileWebMainMenuClickTracking, 'mobile.loggingSchemas.mobileWebSearch' => $schemaMobileWebSearch, ) ); } /** * OutputPageParserOutput hook handler * Disables TOC in output before it grabs HTML * @see https://www.mediawiki.org/wiki/Manual:Hooks/OutputPageParserOutput * * @param OutputPage $outputPage * @param ParserOutput $po * @return bool */ public static function onOutputPageParserOutput( $outputPage, ParserOutput $po ) { global $wgMFWikibaseImageCategory; $context = MobileContext::singleton(); $isBeta = $context->isBetaGroupMember(); $mfUseWikibaseDescription = $context->getMFConfig()->get( 'MFUseWikibaseDescription' ); if ( $context->shouldDisplayMobileView() ) { $outputPage->enableTOC( false ); $outputPage->setProperty( 'MFTOC', $po->getTOCHTML() !== '' ); if ( $mfUseWikibaseDescription && $isBeta ) { $item = $po->getProperty( 'wikibase_item' ); if ( $item ) { $desc = ExtMobileFrontend::getWikibaseDescription( $item ); $category = ExtMobileFrontend::getWikibasePropertyValue( $item, $wgMFWikibaseImageCategory ); if ( $desc ) { $outputPage->setProperty( 'wgMFDescription', $desc ); } if ( $category ) { $outputPage->setProperty( 'wgMFImagesCategory', $category ); } } } } return true; } /** * HTMLFileCache::useFileCache hook handler * Disables file caching for mobile pageviews * @see https://www.mediawiki.org/wiki/Manual:Hooks/HTMLFileCache::useFileCache * * @return bool */ public static function onHTMLFileCache_useFileCache() { return !MobileContext::singleton()->shouldDisplayMobileView(); } /** * Omit srcset attributes from thumbnail image tags, to conserve bandwidth. * * @param ThumbnailImage $thumbnail * @param array &$attribs * @param array &$linkAttribs */ public static function onThumbnailBeforeProduceHTML( $thumbnail, &$attribs, &$linkAttribs ) { if ( MobileContext::singleton()->shouldDisplayMobileView() ) { unset( $attribs['srcset'] ); } } /** * LoginFormValidErrorMessages hook handler to promote MF specific error message be valid. * * @param array $messages Array of already added messages */ public static function onLoginFormValidErrorMessages( &$messages ) { $messages = array_merge( $messages, array( 'mobile-frontend-watchlist-signup-action', // watchstart sign up CTA 'mobile-frontend-watchlist-purpose', // Watchlist and watchstar sign in CTA 'mobile-frontend-donate-image-anon', // Uploads link 'mobile-frontend-edit-login-action', // Edit button sign in CTA 'mobile-frontend-edit-signup-action', // Edit button sign-up CTA 'mobile-frontend-donate-image-login-action', 'mobile-frontend-generic-login-new', // default message ) ); } /** * Handler for MakeGlobalVariablesScript hook. * For values that depend on the current page, user or request state. * * @see http://www.mediawiki.org/wiki/Manual:Hooks/MakeGlobalVariablesScript * @param &$vars array Variables to be added into the output * @param $outputPage OutputPage instance calling the hook * @return bool true in all cases */ public static function onMakeGlobalVariablesScript( array &$vars, OutputPage $out ) { // If the device is a mobile, Remove the category entry. $context = MobileContext::singleton(); if ( $context->shouldDisplayMobileView() ){ unset( $vars['wgCategories'] ); $vars['wgMFMode'] = $context->isBetaGroupMember() ? 'beta' : 'stable'; $vars['wgMFLazyLoadImages'] = $context->isLazyLoadImagesEnabled(); $vars['wgMFLazyLoadReferences'] = $context->isLazyLoadReferencesEnabled(); } $title = $out->getTitle(); $vars['wgPreferredVariant'] = $title->getPageLanguage()->getPreferredVariant(); return true; } /** * Handler for TitleSquidURLs hook to add copies of the cache purge * URLs which are transformed according to the wgMobileUrlTemplate, so * that both mobile and non-mobile URL variants get purged. * * @see * http://www.mediawiki.org/wiki/Manual:Hooks/TitleSquidURLs * @param Title $title the article title * @param array &$urls the set of URLs to purge */ public static function onTitleSquidURLs( Title $title, array &$urls ) { $context = MobileContext::singleton(); foreach ( $urls as $url ) { $newUrl = $context->getMobileUrl( $url ); if ( $newUrl !== false && $newUrl !== $url ) { $urls[] = $newUrl; } } } /** * Handler for the AuthChangeFormFields hook to add a logo on top of * the login screen. This is the AuthManager equivalent of changeUserLoginCreateForm. * @param AuthenticationRequest[] $requests * @param array $fieldInfo Field description as given by AuthenticationRequest::mergeFieldInfo * @param array $formDescriptor A form descriptor suitable for the HTMLForm constructor * @param string $action One of the AuthManager::ACTION_* constants */ public static function onAuthChangeFormFields( array $requests, array $fieldInfo, array &$formDescriptor, $action ) { $context = MobileContext::singleton(); $mfLogo = $context->getMFConfig()->get( 'MobileFrontendLogo' ); // do nothing in desktop mode if ( $context->shouldDisplayMobileView() && $mfLogo ) { $logoHtml = Html::rawElement( 'div', [ 'class' => 'watermark' ], Html::element( 'img', [ 'src' => $mfLogo, 'alt' => '' ] ) ); $formDescriptor = [ 'mfLogo' => [ 'type' => 'info', 'default' => $logoHtml, 'raw' => true, ], ] + $formDescriptor; } } /** * Handler for Extension registration callback */ public static function onRegistration() { global $wgResourceLoaderLESSImportPaths, $wgMinervaPageActions, $wgMinervaEnableSiteNotice, $wgDisableAuthManager, $wgAuthManagerAutoConfig; // modify login/registration form if ( class_exists( \MediaWiki\Auth\AuthManager::class ) && !$wgDisableAuthManager ) { Hooks::register( 'AuthChangeFormFields', 'MobileFrontendHooks::onAuthChangeFormFields' ); } else { Hooks::register( 'UserLoginForm', 'MobileFrontendHooks::onUserLoginForm' ); Hooks::register( 'UserCreateForm', 'MobileFrontendHooks::onUserCreateForm' ); } // Set LESS importpath $wgResourceLoaderLESSImportPaths[] = dirname( __DIR__ ) . "/minerva.less/"; $config = MobileContext::singleton()->getConfig(); // For backwards compatiblity update new Minerva prefixed global with old MF value if ( $config->has( 'MFPageActions' ) ) { // FIXME: Use wfDeprecated to officially deprecate in later patchset $wgMinervaPageActions = $config->get( 'MFPageActions' ); } // For backwards compatiblity. if ( $config->has( 'MFEnableSiteNotice' ) ) { // FIXME: Use wfDeprecated to officially deprecate in later patchset $wgMinervaEnableSiteNotice = $config->get( 'MFEnableSiteNotice' ); } } }
Facerafter/starcitizen-tools
extensions/MobileFrontend/includes/MobileFrontend.hooks.php
PHP
gpl-3.0
47,931
#pragma once #include "imp.hpp" namespace horizon { class ImpLayer : public ImpBase { friend class ImpInterface; public: using ImpBase::ImpBase; bool is_layered() const override { return true; }; protected: void construct_layer_box(bool pack = true); class LayerBox *layer_box; Glib::RefPtr<Glib::Binding> work_layer_binding; Glib::RefPtr<Glib::Binding> layer_opacity_binding; void apply_preferences() override; void get_save_meta(json &j) override; virtual void load_default_layers(); CanvasPreferences *get_canvas_preferences() override { return &preferences.canvas_layer; } ~ImpLayer() { } }; } // namespace horizon
carrotIndustries/horizon
src/imp/imp_layer.hpp
C++
gpl-3.0
713
#!/usr/bin/env python from flask import Flask, render_template, request, jsonify, session, redirect, escape, url_for import MySQLdb import bcrypt from esipy import App from esipy import EsiClient from esipy import EsiSecurity from esipy.exceptions import APIException import time import json import requests import datetime import math app = Flask(__name__) class ServerError(Exception):pass class DB: conn = None def connect(self): config = {} execfile("config.conf",config) self.conn = MySQLdb.connect( host=config['dbHost'], user=config['dbUser'], passwd=config['dbPass'], db=config['dbBase'] ) self.conn.autocommit(True) self.conn.set_character_set('utf8') def query(self, sql, args=None): try: cursor = self.conn.cursor() cursor.execute(sql,args) except (AttributeError, MySQLdb.OperationalError): self.connect() cursor = self.conn.cursor() cursor.execute(sql,args) return cursor if __name__ == '__main__': config = {} execfile("config.conf",config) serverIP = config['serverIP'] serverPort = config['serverPort'] rounds = 10 debug = config['debug'] cer = config['ssl_cer'] key = config['ssl_key'] context = (cer,key) app.secret_key = config['appKey'] esi_app = App.create('https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility') security = EsiSecurity( app=esi_app, redirect_uri=config['callbackURL'], client_id=config['clientID'], secret_key=config['secretKey'] ) client = EsiClient(security=security) scopes = ['esi-location.read_location.v1','esi-skills.read_skillqueue.v1','esi-skills.read_skills.v1','esi-clones.read_clones.v1'] db = DB() def profit(): extractorID = "40519" injectorID = "40520" plexID = "44992" priceList = [] url = "http://api.eve-central.com/api/marketstat/json?regionlimit=10000002&typeid=" try: prices = requests.get(url+extractorID).json()[0] extractorPrice = prices['buy']['fivePercent'] extractorPricen= prices['sell']['fivePercent'] prices = requests.get(url+injectorID).json()[0] injectorPrice = prices['sell']['fivePercent'] injectorPricen= prices['buy']['fivePercent'] prices = requests.get(url+plexID).json()[0] plexPrice = prices['buy']['fivePercent'] plexPricen= prices['sell']['fivePercent'] injectorsMonth = 3.888 profit = round(((injectorsMonth * (injectorPrice - extractorPrice)) - (plexPrice * 500))/1000000,2) nonoptimal = round(((injectorsMonth * (injectorPricen - extractorPricen)) - (plexPricen * 500))/1000000,2) return "<a href='https://market.madpilot.nl/static/graph/farm-month.png'>Projected profits: (min)"+str(nonoptimal)+"mil - (max)"+str(profit)+"mil </a>" except: return "<a href='https://market.madpilot.nl/static/graph/farm-month.png'>Projected profits: (min)"+str(0)+"mil - (max)"+str(0)+"mil </a>" def isk(extractors): extractorID = "40519" injectorID = "40520" plexID = "44992" priceList = [] url = "http://api.eve-central.com/api/marketstat/json?regionlimit=10000002&typeid=" try: prices = requests.get(url+extractorID).json()[0] extractorPrice = prices['buy']['fivePercent'] extractorPricen= prices['sell']['fivePercent'] prices = requests.get(url+injectorID).json()[0] injectorPrice = prices['sell']['fivePercent'] injectorPricen= prices['buy']['fivePercent'] prices = requests.get(url+plexID).json()[0] plexPrice = prices['buy']['fivePercent'] plexPricen= prices['sell']['fivePercent'] maxProfit = round(((injectorPrice - extractorPrice) * extractors)/1000000,2) minProfit = round(((injectorPricen - extractorPricen) * extractors)/1000000,2) except: maxProfit = 0 minProfit = 0 return [maxProfit, minProfit] def isReady(char_id): checkDelay = 1800 cur = db.query("SELECT UNIX_TIMESTAMP(updated) FROM cache_table WHERE character_id = %s",[char_id]) lastChecked = cur.fetchone() curTime = int(time.time()) if lastChecked: lastCheckedEpoch = lastChecked[0] if (curTime - lastCheckedEpoch) < checkDelay: print("Checktime is less than "+str(checkDelay)+" Seconds (current: "+str(curTime - lastCheckedEpoch)+"). Skipping") return False return True return True @app.route('/') def index(): error = None if 'username' not in session: error = "Not logged in" return redirect(url_for('login', error=error)) secure = security.get_auth_uri(scopes=scopes) cur = db.query("SELECT id FROM users WHERE user = %s;", [session['username']]) for row in cur.fetchall(): userID = row[0] characters = [] cur = db.query("SELECT character_id, access_token, refresh_token, expires, expires_in, added, updated FROM characters WHERE owner_id = %s;", [userID]) allSP = 0 extractableSP = 0 numExtract = 0 for row in cur.fetchall(): epoch = round(time.time()) expires = row[3] - row[4] - epoch if expires < 0: expires = 0 refresh = {u'access_token': row[1], u'refresh_token': row[2], u'expires_in': expires} security.update_token(refresh) ready = isReady(row[0]) if not ready: cur = db.query("SELECT * FROM cache_table WHERE character_id=%s",[row[0]]) cache = cur.fetchall()[0] #Get character name charName = esi_app.op['get_characters_names'](character_ids=[row[0]]) result = client.request(charName) charName = json.loads(result.raw)[0].get('character_name') print "Character "+charName #Get character location if ready: charLocation = esi_app.op['get_characters_character_id_location'](character_id=row[0]) result = client.request(charLocation) location = json.loads(result.raw) sol = esi_app.op['get_universe_systems_system_id'](system_id=location.get('solar_system_id')) sol = json.loads(client.request(sol).raw).get('name') cur = db.query("INSERT INTO cache_table (character_id,char_location) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_location=%s",[row[0],result.raw,result.raw]) else: location = json.loads(cache[3]) sol = esi_app.op['get_universe_systems_system_id'](system_id=location.get('solar_system_id')) sol = json.loads(client.request(sol).raw).get('name') #Get current training skill + queue if ready: charTrain = esi_app.op['get_characters_character_id_skillqueue'](character_id=row[0]) result = client.request(charTrain) training = json.loads(result.raw) cur = db.query("INSERT INTO cache_table (character_id,char_queue) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_queue=%s",[row[0],result.raw,result.raw]) else: training = json.loads(cache[4]) currentlyTrainingStart = training[0].get('start_date') currentlyTrainingEnd = training[0].get('finish_date') startTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ"))) endTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))) if endTrainEpoch < epoch: while endTrainEpoch < epoch and len(training)>1: del training[0] currentlyTrainingStart = training[0].get('start_date') currentlyTrainingEnd = training[0].get('finish_date') startTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ"))) endTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))) trainedSpCur = training[0].get('training_start_sp') - training[0].get('level_start_sp') endQueue = training[-1].get('finish_date') currentlyTraining = training[0].get('skill_id') currentlyTrainingLevel = training[0].get('finished_level') curSkillStartSP = training[0].get('level_start_sp') curSkillEndSP = training[0].get('level_end_sp') curSkillSP = curSkillEndSP - curSkillStartSP #Get currently training name skillName = esi_app.op['get_universe_types_type_id'](type_id=currentlyTraining) result = client.request(skillName) skillName = json.loads(result.raw).get('name') #Get character total sp if ready: charSkill = esi_app.op['get_characters_character_id_skills'](character_id=row[0]) result = client.request(charSkill) sp = json.loads(result.raw) totalSp = sp.get('total_sp') cur = db.query("INSERT INTO cache_table (character_id,char_skills) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_skills=%s",[row[0],result.raw,result.raw]) else: sp = json.loads(cache[5]) totalSp = sp.get('total_sp') #Get current training skill rank skillRank = esi_app.op['universe_types_type_id'](type_id=currentlyTraining) result = client.request(skillRank) skillDogma = json.loads(result.raw).get('dogma_attributes') print skillDogma skillRank = 5 # for skill in skillDogma: # if skill.get('attribute_id') == 275: # skillRank = skill.get('value') # break; startTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ"))) endTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))) totalTrainTime = endTrainEpoch - startTrainEpoch trainedTime = epoch - startTrainEpoch # skillStartSP = (250 * math.pow(5.65685,currentlyTrainingLevel-1)) # skillEndSP = (250 * math.pow(5.65685,currentlyTrainingLevel)) spPerSec = float(curSkillSP) / float(totalTrainTime) trainedSP = int(spPerSec * trainedTime) totalSp += trainedSP allSP += totalSp #Prettify dates timeLeftCurrent = datetime.datetime.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ").replace(microsecond=0) - datetime.datetime.now().replace(microsecond=0) endQueueLeft = datetime.datetime.strptime(endQueue, "%Y-%m-%dT%H:%M:%SZ").replace(microsecond=0) - datetime.datetime.now().replace(microsecond=0) currentlyTrainingEnd = time.strftime("%Y-%m-%d %H:%M",time.gmtime(int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))))) endQueue = time.strftime("%Y-%m-%d %H:%M",time.gmtime(int(time.mktime(time.strptime(endQueue, "%Y-%m-%dT%H:%M:%SZ"))))) #Get Cybernetics skill for skill in sp.get('skills'): if skill.get('skill_id') == 3411: cyberLevel = skill.get('current_skill_level') break; #Get character attributes #Assume 2700(max) for now, until attributes are added to ESI startTime = time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ")) timeDone = epoch - startTime spAdded = int(timeDone / 60 / 60 * 2700) if totalSp > 5500000: exSP = totalSp - 5000000 extractableSP += exSP exSP = int(exSP / 500000) numExtract += exSP totalSp = format(totalSp, "8,d") queueStatus = None if endTrainEpoch < epoch: queueStatus = "Queue empty!" characters.append( { "characterName": charName, "characterID": row[0], "characterImage": "https://image.eveonline.com/Character/"+str(row[0])+"_64.jpg", "totalSP": totalSp, "characterLocation": sol, "currentEnd":currentlyTrainingEnd, "queueEnd": endQueue, "currentlyTraining": currentlyTraining, "timeLeftCurrent": timeLeftCurrent, "endQueueLeft": endQueueLeft, "currentlyTrainingLevel": currentlyTrainingLevel, "currentlyTrainingName": skillName, "cyberneticsLevel": cyberLevel, "queueStatus": queueStatus }) print "----------" allSP = format(allSP, "8,d") extractableSP = format(extractableSP, "8,d") stats = [{ "allSP": allSP, "exSP": extractableSP, "numEx": numExtract }] profits = isk(numExtract) return render_template('index.html',secUrl=secure, characters=characters, stats=stats, profit=profit(), profits=profits) @app.route('/login', methods=['GET', 'POST']) def login(): error = None error = request.args['error'] if 'username' in session: return redirect(url_for('index')) try: if request.method == 'POST': username = request.form['username'] cur = db.query("SELECT COUNT(1) FROM users WHERE user = %s", [username]) if not cur.fetchone()[0]: raise ServerError('Incorrect username / password') password = request.form['password'] cur = db.query("SELECT pass FROM users WHERE user = %s;", [username]) for row in cur.fetchall(): if bcrypt.hashpw(password.encode('utf-8'), row[0]) == row[0]: session['username'] = request.form['username'] return redirect(url_for('index')) raise ServerError('Incorrect username / password') except ServerError as e: error = str(e) return render_template('login.html', error=error) @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) @app.route('/register', methods=['GET', 'POST']) def register(): error = None if 'username' not in session: try: if request.method == 'POST': username = request.form['username'] password = request.form['password'] email = request.form['email'] if not username or not password or not email: raise ServerError('Fill in all fields please') password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds)) cur = db.query("INSERT INTO users (`user`, `pass`, `email`) VALUES (%s,%s,%s)", [username, password, email]) except ServerError as e: error = str(e) return render_template('register.html', error=error) if config['registerEnabled']: return render_template('register.html') error = "Registration is disabled by the admin" return redirect(url_for('login', error=error)) if session['username'] == 'admin': return render_template('register.html') error = "Only available to admins" return redirect(url_for('login', error=error)) @app.route('/userPage', methods=['GET','POST']) def userPage(): return "User! :-)" @app.route('/oauth') def oauth(): code = request.args.get('code') if not code: return redirect(url_for('index')) token = security.auth(code) access_token = token['access_token'] refresh_token = token['refresh_token'] expires_in = token['expires_in'] cur = db.query("SELECT id FROM users WHERE user = %s;", [session['username']]) for row in cur.fetchall(): userID = row[0] verify = security.verify() charID = verify.get('CharacterID') print userID print charID print token print token['access_token'] print token['refresh_token'] print token['expires_in'] epoch = round(time.time()) expires = epoch + int(expires_in) cur = db.query("INSERT INTO characters (owner_id, character_id, access_token, refresh_token, expires, expires_in) VALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE access_token=%s, refresh_token=%s, expires=%s, expires_in=%s",[userID,charID,access_token,refresh_token,expires,int(expires_in),access_token,refresh_token,expires,int(expires_in)]) return redirect(url_for('index')) if __name__ == '__main__': if config['ssl']: app.run( host=serverIP, port=serverPort, ssl_context=context, debug=debug ) else: app.run( host=serverIP, port=serverPort, debug=debug )
Madpilot0/EVE-Farm
app.py
Python
gpl-3.0
14,554
package tmp.generated_ecmascript; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class ArrayLiteral2 extends ArrayLiteral { public ArrayLiteral2(ElementList elementList, Elision elision1, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<ElementList>("elementList", elementList), new PropertyOne<Elision>("elision1", elision1) }, firstToken, lastToken); } public ArrayLiteral2(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public IASTNode deepCopy() { return new ArrayLiteral2(cloneProperties(),firstToken,lastToken); } public ElementList getElementList() { return ((PropertyOne<ElementList>)getProperty("elementList")).getValue(); } public Elision getElision1() { return ((PropertyOne<Elision>)getProperty("elision1")).getValue(); } }
ckaestne/CIDE
CIDE_Language_ECMAScript/src/tmp/generated_ecmascript/ArrayLiteral2.java
Java
gpl-3.0
952
/* * Copyright (C) 2020 ~ 2021 Uniontech Software Technology Co., Ltd. * * Author: ZouYa <zouya@uniontech.com> * * Maintainer: WangYu <wangyu@uniontech.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DBUSUTILS_H #define DBUSUTILS_H #include <QVariant> #include <QDBusConnection> class DBusUtils { public: DBusUtils(); static QVariant readDBusProperty(const QString &service, const QString &path, const QString &interface = QString(), const char *propert = "", QDBusConnection connection = QDBusConnection::sessionBus()); // static QVariant readDBusMethod(const QString &service, const QString &path, const QString &interface, const char *method); }; #endif // DBUSUTILS_H
linuxdeepin/deepin-music
src/music-player/core/util/dbusutils.h
C
gpl-3.0
1,296
// Decompiled with JetBrains decompiler // Type: UIWorldMap_Common // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 19851F1B-4780-4223-BA01-2C20F2CD781E // Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Assembly-CSharp.dll using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; using Wb.Lpw.AssetPipeline.Client; using Wb.Lpw.Game.Common; using Wb.Lpw.Game.Common.Descriptions; using Wb.Lpw.Game.Common.GameModule; using Wb.Lpw.Game.Common.Logging; using Wb.Lpw.Platform.Protocol; using Wb.Lpw.Shared.Client.UnityEngine; using Wb.Lpw.Shared.Common; using Wb.Lpw.Shared.Network; public abstract class UIWorldMap_Common : FordUIPanel { private const int _CameraXLimitPerTile = 180; private const int _CameraYLimitPerTile = 300; private const int _CameraYLimitPerTileOffset = 800; private const int _numRows = 14; private const int _numCols = 14; public const string Cond_UserClosedWM = "UserClosedWM"; public const string Cond_WMOpenedDone = "WMOpenedDone"; public const string Cond_LoadingDone = "LoadingDone"; public GameObject ZoomControlsParent; public UIButton Close; public GameObject RegionMapHook; public Camera RegionMapCamera; public GameObject Loots; public int MaxZoomValue; public int MinZoomValue; private RegionMapDescription _regionMapDesc; public UIWorldMap_Common.WeaponInfos _weaponInfos; public Material DefaultMaterial; public WBSpriteText TitleText; public GameObject TitleBar; public string WMOpenSound; public string WMRegionOver; public string WMCloseSound; public string WMRegionSelectSound; private WMLocalPlayer _playerArrow; private Dictionary<string, List<WMFriend>> _FriendTags; private WMPortal _highestActivatedPortal; private bool _init; private MatTexTracker _materialTracker; private GoalArrow2D _2dGoalArrow; private GoalArrow3D _3dGoalArrow; private PlayerGoalProgression.WorldMapGoalInfo _goalInfo; private Vector3 _goalArrowLookAt; private Vector3 _goalArrowUp; private Vector3 _newGoalPosition; private WildernessRegion _currentRegionMap; protected GameObject _currentRegionMapObject; protected Dictionary<WildernessRegion, long> _regionMapsIds; private Dictionary<WildernessRegion, string> _regionMapBundlePrefixes; private UIWorldMap_Common.RegionMapSpecs _regionMapSpecs; private UIWorldMap_Common.MapSubsection[,] _regionSections; private UIWorldMap_Common.CameraExtents _minCamExtents; private UIWorldMap_Common.CameraExtents _maxCamExtents; private bool _startDragged; private Vector3 _position; protected GameObject _vfxGoalPointer; protected GameObjectItemRef VFXGoalPointerBundle; protected bool m_ShowVFXGlitter; public bool unitTestReady; private UIButton.CONTROL_STATE m_lastButtonChangedState; private Camera mainCamera; private bool _chiPortalUiState; public bool IsOpenedViaDomain; protected UIWorldMapTopLevel _topLevelWorldMap; private List<WBLoader.BundleRequest> _pendingRequests; private string[] unlockConditions; private Vector3 _LootInspectorForcePosition; private bool _OpenInspector; private bool _inspectorOpened; private bool _inspectorShouldClose; private string _inspectorMessage; private string _inspectorTitle; private float _inspectorIconAspect; private int _inspectorWeaponFootprint; private int _inspectorWeaponLevel; private Texture2D _inspectorTexture; private int _totalPlaceFriendsInProgress; private Mesh _quad; public int CurrZoomValue { get { return (int) ((Component) this.RegionMapCamera).get_transform().get_localPosition().z; } } public static bool DisplayingRegionMap { get; private set; } protected UIWorldMap_Common() { string[] strArray = new string[7]; int index1 = 0; string str1 = "UserClosedWM"; strArray[index1] = str1; int index2 = 1; string str2 = "UserClosedAbilityLoadOut"; strArray[index2] = str2; int index3 = 2; string str3 = "OnJoinRoom"; strArray[index3] = str3; int index4 = 3; string str4 = "OnTeleportToSpawnPoint"; strArray[index4] = str4; int index5 = 4; string str5 = "OnLocalTeleport"; strArray[index5] = str5; int index6 = 5; string str6 = "OnSwitchLayout"; strArray[index6] = str6; int index7 = 6; string str7 = "LoadingDone"; strArray[index7] = str7; this.unlockConditions = strArray; this._LootInspectorForcePosition = Vector3.get_zero(); this._OpenInspector = true; this._inspectorShouldClose = true; this._inspectorMessage = string.Empty; this._inspectorTitle = string.Empty; this._inspectorIconAspect = 1f; // ISSUE: explicit constructor call base.\u002Ector(); } public override bool Initialization() { if (this._init) return false; base.Initialization(); this.Close.onClickDelegate = new Action<UIButton>(this.OnClickClose); this._init = true; ((Component) this.RegionMapCamera).get_gameObject().AddComponent<CameraNoFog>(); GameObject go = new GameObject("3dArrowHook"); go.get_transform().set_parent(((Component) this).get_transform()); FordUtility.SetLayerRecursively(go, LayerMask.NameToLayer("WorldMap")); this._2dGoalArrow = GoalArrow2D.Create(((Component) this).get_transform()); this._3dGoalArrow = GoalArrow3D.Create(go.get_transform()); this._3dGoalArrow.SetScale(175f); this.TitleText.Text = FordLocalizationMgr.Menu.GetStringFromId("WORLD_MAP_HEADER", string.Empty, string.Empty); UIWorldMap_Common.DisplayingRegionMap = false; return true; } [DebuggerHidden] private IEnumerator WaitAndCreateVfxGoal() { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CWaitAndCreateVfxGoal\u003Ec__Iterator164() { \u003C\u003Ef__this = this }; } public override void OpenMenu(object parameter, Action done) { base.OpenMenu(parameter, done); this._regionMapDesc = (RegionMapDescription) null; FlashAnimationX.ForceStopAllChildAnimations(((Component) this).get_gameObject(), "GL_Outro", true); FordInputMgr.Instance.FireInputUnlockCondition("WMOpenedDone"); FordInputMgr.Instance.DisableAllInputs(false, "WorldMap", this.unlockConditions); WBAudioManager.Instance.Play(this.WMOpenSound, (Object) this, AudioResourceUsage.Clear, (Transform) null, 0.0f, (AudioCompletionCallback) null); if (Object.op_Inequality((Object) FordGameRoom.Instance, (Object) null)) this.IsOpenedViaDomain = FordGameRoom.Instance.IsDomain(); ((Component) this.RegionMapCamera).get_transform().set_localPosition(Vector3.get_zero()); FordPanelManager.Instance.OverheadPanelManager.HideAll(); ((Component) this).get_gameObject().SetActive(true); if (Object.op_Inequality((Object) FordGameRoom.Instance, (Object) null) && FordGameRoom.Instance.Roger.WorldMapGoalVfx != null) { this.VFXGoalPointerBundle = (GameObjectItemRef) FordGameRoom.Instance.Roger.WorldMapGoalVfx; this.VFXGoalPointerBundle.Load((object) this); } this.StartCoroutine("WaitAndCreateVfxGoal"); FlashAnimationX.PlayAllChildAnimations(((Component) this).get_gameObject(), "GL_Intro", done, 0.0f, 1f, false); this.Loots.SetActive(false); this.LoadRegionMapsData(WbAssetDatabase.Instance.Db.GetAllItemIds("Region Map", false)); if (this.IsOpenedViaDomain || FordGameRoom.Instance is TreasureHuntRoom) { this.SetupUI(this.IsOpenedViaDomain); this.DisplayWorldMap(); } else if (Object.op_Inequality((Object) FordGameRoom.Instance, (Object) null)) this.DisplayRegionMap(((int) FordGameRoom.Instance.WildernessReg).ToString()); ((Behaviour) this.RegionMapCamera).set_enabled(true); this.mainCamera = !Object.op_Inequality((Object) IsoCamera.Instance, (Object) null) ? (Camera) null : ((Component) IsoCamera.Instance).get_camera(); if (Object.op_Inequality((Object) this.mainCamera, (Object) null)) ((Behaviour) this.mainCamera).set_enabled(false); this.AlignUIElements(); NetworkMgr.Instance.BIGameModule.SendEventWorldMapEnter((Action<OperationResult, GameModuleProtocol.BI.SendEventWorldMapEnterResponse>) null); } protected virtual void SetupUI(bool enabledOnceLoaded) { this.StartCoroutine(this.WaitAndSetupUI(enabledOnceLoaded)); } [DebuggerHidden] private IEnumerator WaitAndSetupUI(bool enabledOnceLoaded) { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CWaitAndSetupUI\u003Ec__Iterator165() { enabledOnceLoaded = enabledOnceLoaded, \u003C\u0024\u003EenabledOnceLoaded = enabledOnceLoaded, \u003C\u003Ef__this = this }; } private void DisplayWorldMap() { if (Object.op_Equality((Object) this._topLevelWorldMap, (Object) null) || Object.op_Equality((Object) this._topLevelWorldMap.GetWorldMap(), (Object) null)) this.SetupUI(true); else if (!((Component) this._topLevelWorldMap).get_gameObject().get_activeSelf()) this._topLevelWorldMap.SetEnabled(true); this.StartCoroutine(this.WaitAndDisplayWorldMap()); } [DebuggerHidden] private IEnumerator WaitAndDisplayWorldMap() { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CWaitAndDisplayWorldMap\u003Ec__Iterator166() { \u003C\u003Ef__this = this }; } protected void LoadRegionMapsData(IEnumerable<long> regionMapsIDs) { foreach (long itemId in regionMapsIDs) { RegionMapDescription objectSync = WbAssetDatabase.Instance.Db.GetObjectSync<RegionMapDescription>(itemId); this._regionMapBundlePrefixes[objectSync.RegionType] = objectSync.RegionMapPrefix; this._regionMapsIds[objectSync.RegionType] = itemId; } } protected void PopulateBundleGrid(string regionMapBundlePrefix) { this._regionSections = new UIWorldMap_Common.MapSubsection[14, 14]; for (int number = 0; number < 14; ++number) { for (int index = 0; index < 14; ++index) { this._regionSections[number, index] = new UIWorldMap_Common.MapSubsection(); this._regionSections[number, index].bundleName = regionMapBundlePrefix + (object) this.ConvertPositionFromNumberToLetter(number) + (string) (object) index; } } } protected void PrefetchRegionBundles() { UIWorldMap_Common.MapSubsection[,] mapSubsectionArray = this._regionSections; int length1 = mapSubsectionArray.GetLength(0); int length2 = mapSubsectionArray.GetLength(1); for (int index1 = 0; index1 < length1; ++index1) { for (int index2 = 0; index2 < length2; ++index2) WBLoader.Instance.PrefetchAssetBundle(AssetPath.BuildPlatformAssetBundleName("RegionMaps", mapSubsectionArray[index1, index2].bundleName)); } } protected virtual void OnInstantiateRegionMapBegin(WildernessRegion toDisplay) { this.PopulateBundleGrid(this._regionMapBundlePrefixes[toDisplay]); this.PrefetchRegionBundles(); } protected abstract void OnInstantiateRegionMapDone(WildernessRegion toDisplay); protected abstract void OnClearRegionMap(); protected void CreateRegionMapSections() { GameObject gameObject1 = ((WMRegion) this._currentRegionMapObject.GetComponent<WMRegion>()).MainMap; Vector3 localPosition = gameObject1.get_transform().get_localPosition(); Bounds bounds1 = gameObject1.get_renderer().get_bounds(); // ISSUE: explicit reference operation float num1 = (float) (-((Bounds) @bounds1).get_extents().x + localPosition.x); // ISSUE: explicit reference operation float num2 = (float) (((Bounds) @bounds1).get_extents().y + localPosition.z); // ISSUE: explicit reference operation float width = (float) (((Bounds) @bounds1).get_size().x / 14.0); // ISSUE: explicit reference operation float height = (float) (((Bounds) @bounds1).get_size().y / 14.0); this._regionMapSpecs.topX = num1; this._regionMapSpecs.topY = num2; this._regionMapSpecs.subsectionWidth = width; this._regionMapSpecs.subsectionHeight = height; if (Object.op_Equality((Object) gameObject1.GetComponent<BoxCollider>(), (Object) null)) { BoxCollider boxCollider = (BoxCollider) gameObject1.AddComponent<BoxCollider>(); boxCollider.set_size(Vector3.op_Multiply(boxCollider.get_size(), 1.2f)); } GameObject gameObject2 = new GameObject(); gameObject2.set_layer(LayerMask.NameToLayer("WorldMap")); MeshRenderer meshRenderer = (MeshRenderer) gameObject2.AddComponent<MeshRenderer>(); ((Renderer) meshRenderer).set_sharedMaterial(new Material(Shader.Find("DiffuseNoFog"))); ((Renderer) meshRenderer).set_castShadows(false); ((Renderer) meshRenderer).set_receiveShadows(false); ((Renderer) meshRenderer).set_enabled(false); ((MeshFilter) gameObject2.AddComponent<MeshFilter>()).set_sharedMesh(this.CreateQuad(width, height)); float num3 = (float) gameObject1.get_transform().get_localPosition().y; gameObject1.get_transform().set_localPosition(new Vector3((float) gameObject1.get_transform().get_localPosition().x, (float) (gameObject1.get_transform().get_localPosition().y - 1.0), (float) gameObject1.get_transform().get_localPosition().z)); for (int number = 0; number < 14; ++number) { for (int index = 0; index < 14; ++index) { float num4 = num1 + (float) index * width; float num5 = num2 - (float) number * height; Vector3 vector3; // ISSUE: explicit reference operation ((Vector3) @vector3).\u002Ector(num4 + width / 2f, num3, num5 - height / 2f); GameObject gameObject3 = (GameObject) Object.Instantiate((Object) gameObject2, vector3, Quaternion.get_identity()); ((Object) gameObject3).set_name("Region" + (object) this.ConvertPositionFromNumberToLetter(number) + (string) (object) index); gameObject3.get_transform().set_parent(this.RegionMapHook.get_transform()); gameObject3.get_transform().set_localPosition(vector3); this._regionSections[number, index].regionObject = gameObject3; Bounds bounds2 = gameObject3.get_renderer().get_bounds(); // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation this._regionSections[number, index].topLeft = new Vector3((float) (((Bounds) @bounds2).get_center().x - ((Bounds) @bounds2).get_extents().x), (float) (((Bounds) @bounds2).get_center().y + ((Bounds) @bounds2).get_extents().y), (float) gameObject3.get_transform().get_position().z); // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation this._regionSections[number, index].topRight = new Vector3((float) (((Bounds) @bounds2).get_center().x + ((Bounds) @bounds2).get_extents().x), (float) (((Bounds) @bounds2).get_center().y + ((Bounds) @bounds2).get_extents().y), (float) gameObject3.get_transform().get_position().z); // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation this._regionSections[number, index].bottomLeft = new Vector3((float) (((Bounds) @bounds2).get_center().x - ((Bounds) @bounds2).get_extents().x), (float) (((Bounds) @bounds2).get_center().y - ((Bounds) @bounds2).get_extents().y), (float) gameObject3.get_transform().get_position().z); // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation this._regionSections[number, index].bottomRight = new Vector3((float) (((Bounds) @bounds2).get_center().x + ((Bounds) @bounds2).get_extents().x), (float) (((Bounds) @bounds2).get_center().y - ((Bounds) @bounds2).get_extents().y), (float) gameObject3.get_transform().get_position().z); this._regionSections[number, index].isUnloaded = true; } } Object.Destroy((Object) gameObject2); this.CalibrateRegionMap(); } private void CalibrateRegionMap() { Vector3 position1 = ((Component) this.RegionMapCamera).get_transform().get_position(); Vector3 position2 = this._currentRegionMapObject.get_transform().get_position(); position2.z = ((Component) this.RegionMapCamera).get_transform().get_position().z; ((Component) this.RegionMapCamera).get_transform().set_position(position2); this.ZoomRegionMap((float) this.MinZoomValue, Vector3.get_zero()); this._minCamExtents = this.GetCameraExtents(); this.ZoomRegionMap((float) this.MaxZoomValue, Vector3.get_zero()); this._maxCamExtents = this.GetCameraExtents(); ((Component) this.RegionMapCamera).get_transform().set_position(position1); } private UIWorldMap_Common.CameraExtents GetCameraExtents() { RaycastHit raycastHit; Physics.Raycast(this.RegionMapCamera.ViewportPointToRay(new Vector3(1f, 0.0f, 0.0f)), ref raycastHit); // ISSUE: explicit reference operation Vector3 point1 = ((RaycastHit) @raycastHit).get_point(); Physics.Raycast(this.RegionMapCamera.ViewportPointToRay(new Vector3(1f, 1f, 0.0f)), ref raycastHit); // ISSUE: explicit reference operation Vector3 point2 = ((RaycastHit) @raycastHit).get_point(); Physics.Raycast(this.RegionMapCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0.0f)), ref raycastHit); // ISSUE: explicit reference operation Vector3 point3 = ((RaycastHit) @raycastHit).get_point(); UIWorldMap_Common.CameraExtents cameraExtents; cameraExtents.centerToX_Top = (float) (point2.x - point3.x); cameraExtents.centerToY_Top = (float) (point2.y - point3.y); cameraExtents.centerToX_Bot = (float) (point1.x - point3.x); cameraExtents.centerToY_Bot = (float) (point1.y - point3.y); return cameraExtents; } [DebuggerHidden] private IEnumerator WaitAndSetTexture(WBLoader.BundleRequest request, UIWorldMap_Common.MapSubsection region, Action onTextureLoaded = null) { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CWaitAndSetTexture\u003Ec__Iterator167() { request = request, region = region, onTextureLoaded = onTextureLoaded, \u003C\u0024\u003Erequest = request, \u003C\u0024\u003Eregion = region, \u003C\u0024\u003EonTextureLoaded = onTextureLoaded, \u003C\u003Ef__this = this }; } private void UnloadAllSubsectionResources() { if (this._regionSections == null) return; for (int index1 = 0; index1 < 14; ++index1) { for (int index2 = 0; index2 < 14; ++index2) { UIWorldMap_Common.MapSubsection mapSubsection = this._regionSections[index1, index2]; if (Object.op_Inequality((Object) mapSubsection.regionObject, (Object) null)) { MeshRenderer meshRenderer = (MeshRenderer) mapSubsection.regionObject.GetComponent<MeshRenderer>(); if (Object.op_Inequality((Object) meshRenderer, (Object) null) && Object.op_Inequality((Object) ((Renderer) meshRenderer).get_material(), (Object) null)) Resources.UnloadAsset((Object) ((Renderer) meshRenderer).get_material().get_mainTexture()); Object.Destroy((Object) mapSubsection.regionObject); mapSubsection.regionObject = (GameObject) null; } } } this._regionSections = (UIWorldMap_Common.MapSubsection[,]) null; } protected void ClearRegionMap() { UIWorldMap_Common.DisplayingRegionMap = false; this.OnClearRegionMap(); this.UnloadAllSubsectionResources(); if (!Object.op_Inequality((Object) this._currentRegionMapObject, (Object) null)) return; Object.Destroy((Object) this._currentRegionMapObject); this._currentRegionMapObject = (GameObject) null; } protected abstract void AlignUIElements(); protected virtual void LateUpdate() { if (!Object.op_Inequality((Object) UIManager.Instance, (Object) null) || UIManager.Instance.uiCameras == null || (!Object.op_Inequality((Object) FordGameRoom.Instance, (Object) null) || !Object.op_Inequality((Object) FordGameRoom.Instance._PlayerGoalProgression, (Object) null))) return; this.AlignUIElements(); FordGameRoom.Instance._PlayerGoalProgression.GetCurrentWorldMapInfo(ref this._goalInfo); bool flag1 = (this._goalInfo.FieldsUsed & 1) == 1; bool flag2 = (this._goalInfo.FieldsUsed & 2) == 2; WildernessRegion wildernessRegion = WildernessRegion.Zoo; if (flag1) { wildernessRegion = GraphMgr.Instance.FindRegionContainingRoom(this._goalInfo.TileName); } else { this._2dGoalArrow.SetVisible(false); if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) this._vfxGoalPointer.SetActive(false); this._3dGoalArrow.SetVisible(false); } if (Object.op_Inequality((Object) this._topLevelWorldMap, (Object) null) && this._topLevelWorldMap.IsEnabled()) { if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) this._vfxGoalPointer.SetActive(false); this._3dGoalArrow.SetVisible(false); if (!FordPanelManager.Instance.IsPanelOpened("UIPanelLoading") && flag1) { Transform regionTransform = this.GetRegionTransform(wildernessRegion); if (Object.op_Inequality((Object) regionTransform, (Object) null)) { this._2dGoalArrow.SetPosition(regionTransform.get_position(), -45f); this._2dGoalArrow.SetVisible(true); } else this._2dGoalArrow.SetVisible(false); } else this._2dGoalArrow.SetVisible(false); } else if (Object.op_Inequality((Object) this._currentRegionMapObject, (Object) null)) { this._2dGoalArrow.SetVisible(false); bool flag3 = false; if (this._currentRegionMap == wildernessRegion) { if (Object.op_Inequality((Object) this._currentRegionMapObject, (Object) null) && flag1 && flag2) { Vector3 targetPosition = (Vector3) null; Transform child = this._currentRegionMapObject.get_transform().FindChild(this._goalInfo.TileName); if (Object.op_Inequality((Object) child, (Object) null)) { string str = this._goalInfo.TileName.ToLower(); targetPosition = str.Contains("dungeon") || str.Contains("cave") ? child.get_position() : child.TransformPoint(VectorExtensions.FlattenY(this._goalInfo.Position)); flag3 = true; } else { GameObject childRecursively = FordUtility.FindChildRecursively(this._currentRegionMapObject.get_transform(), this._goalInfo.TileName); if (Object.op_Inequality((Object) childRecursively, (Object) null)) { targetPosition = childRecursively.get_transform().get_position(); flag3 = true; } } if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) { if (flag3) { this._vfxGoalPointer.get_transform().set_position(targetPosition); if (Vector3.op_Inequality(targetPosition, this._newGoalPosition)) { this.StartCoroutine(this.FocusOnLerp(targetPosition)); this._newGoalPosition = targetPosition; } this._vfxGoalPointer.SetActive(true); bool flag4 = false; Vector3 vPosition = Vector3.op_Multiply(9999f, Vector3.get_one()); foreach (WMPortal wmPortal in this.RegionMapHook.GetComponentsInChildren(typeof (WMPortal), true)) { if (!wmPortal.HideOnMap) { Vector3 vector3_1 = Vector3.op_Subtraction(((Component) wmPortal).get_transform().get_position(), this._vfxGoalPointer.get_transform().get_position()); // ISSUE: explicit reference operation double num1 = (double) ((Vector3) @vector3_1).get_magnitude(); Vector3 vector3_2 = Vector3.op_Subtraction(vPosition, this._vfxGoalPointer.get_transform().get_position()); // ISSUE: explicit reference operation double num2 = (double) ((Vector3) @vector3_2).get_magnitude(); if (num1 < num2) { flag4 = true; vPosition = ((Component) wmPortal).get_transform().get_position(); } } } bool flag5 = true; if (Object.op_Inequality((Object) this._playerArrow, (Object) null)) { Vector3 vector3_1 = Vector3.op_Subtraction(vPosition, this._vfxGoalPointer.get_transform().get_position()); // ISSUE: explicit reference operation double num1 = (double) ((Vector3) @vector3_1).get_magnitude() + (double) FordGameRoom.Instance.Roger.DistanceThresholdForPortalGoalArrowOnMap; Vector3 vector3_2 = Vector3.op_Subtraction(((Component) this._playerArrow).get_transform().get_position(), this._vfxGoalPointer.get_transform().get_position()); // ISSUE: explicit reference operation double num2 = (double) ((Vector3) @vector3_2).get_magnitude(); flag5 = num1 < num2; } if (flag4 && flag5) { this._3dGoalArrow.SetPosition(vPosition, this._goalArrowLookAt, this._goalArrowUp, false); this._3dGoalArrow.SetVisible(true); } } else { CommonLog.Error("Failed to find region map tile. _goalInfo.TileName = " + this._goalInfo.TileName); this._vfxGoalPointer.SetActive(false); this._3dGoalArrow.SetVisible(false); } } } else { if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) this._vfxGoalPointer.SetActive(false); this._3dGoalArrow.SetVisible(false); } } else { if (flag2 && flag1) { Transform transform = (Transform) null; switch (this._currentRegionMap) { case WildernessRegion.Jungle: transform = MonoBehaviourExtensions.FindChildRecursively(this.RegionMapHook.get_transform(), "LD_Tile20_L"); break; case WildernessRegion.Mountain: transform = MonoBehaviourExtensions.FindChildRecursively(this.RegionMapHook.get_transform(), "LD_Tile09_L"); break; } if (Object.op_Inequality((Object) transform, (Object) null)) { this._3dGoalArrow.SetPosition(transform.get_position(), this._goalArrowLookAt, this._goalArrowUp, false); if (Vector3.op_Inequality(this._newGoalPosition, transform.get_position())) { this.StartCoroutine(this.FocusOnLerp(transform.get_position())); this._newGoalPosition = transform.get_position(); } this._3dGoalArrow.SetVisible(true); } } if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) { if (!FordUtility.IsPositionVisibleOnScreen(this.RegionMapCamera, this._vfxGoalPointer.get_transform().get_position())) this._vfxGoalPointer.SetActive(false); else if (flag3) this._vfxGoalPointer.SetActive(true); } } this.Loots.get_transform().set_position(this._LootInspectorForcePosition); } else { this._2dGoalArrow.SetVisible(false); if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) this._vfxGoalPointer.SetActive(false); this._3dGoalArrow.SetVisible(false); } } public override void CloseMenu(Action done) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type UIWorldMap_Common.\u003CCloseMenu\u003Ec__AnonStorey30D menuCAnonStorey30D = new UIWorldMap_Common.\u003CCloseMenu\u003Ec__AnonStorey30D(); // ISSUE: reference to a compiler-generated field menuCAnonStorey30D.done = done; // ISSUE: reference to a compiler-generated field menuCAnonStorey30D.\u003C\u003Ef__this = this; GameLog.drej.InfoFormat("[Map] CloseMenu()"); this.StopAllCoroutines(); using (List<WBLoader.BundleRequest>.Enumerator enumerator = this._pendingRequests.GetEnumerator()) { while (enumerator.MoveNext()) enumerator.Current.Dispose(); } this.mainCamera = !Object.op_Inequality((Object) IsoCamera.Instance, (Object) null) ? (Camera) null : ((Component) IsoCamera.Instance).get_camera(); if (Object.op_Inequality((Object) this.mainCamera, (Object) null)) ((Behaviour) this.mainCamera).set_enabled(true); ((Behaviour) this.RegionMapCamera).set_enabled(false); if (Object.op_Inequality((Object) this._topLevelWorldMap, (Object) null)) this._topLevelWorldMap.SetEnabled(false); // ISSUE: reference to a compiler-generated method FlashAnimationX.PlayAllChildAnimations(((Component) this).get_gameObject(), "GL_Outro", new Action(menuCAnonStorey30D.\u003C\u003Em__50A), 0.0f, 1f, false); this.ClearRegionMap(); WBAudioManager.Instance.Play(this.WMCloseSound, (Object) this, AudioResourceUsage.Clear, (Transform) null, 0.0f, (AudioCompletionCallback) null); this.ClearFriendTags(); if (Object.op_Inequality((Object) this._playerArrow, (Object) null)) { UIGenericOverhead overHead = this._playerArrow.GetOverHead(); if (Object.op_Inequality((Object) overHead, (Object) null)) FordPanelManager.Instance.OverheadPanelManager.Unregister((Component) overHead); Object.DestroyImmediate((Object) ((Component) this._playerArrow).get_gameObject()); } FordInputMgr.Instance.FireInputUnlockCondition("UserClosedWM"); this._regionMapsIds.Clear(); this._2dGoalArrow.SetVisible(false); this._topLevelWorldMap = (UIWorldMapTopLevel) null; if (Object.op_Inequality((Object) this._vfxGoalPointer, (Object) null)) Object.Destroy((Object) this._vfxGoalPointer); this.ClearCollections(); FordPanelManager.Instance.Destroy("UIWorldMapTopLevel"); if (Object.op_Inequality((Object) ResourceMgr.Instance, (Object) null)) ResourceMgr.Instance.RemoveAllReferences((object) this); if (!Object.op_Inequality((Object) UIDefaultCursor.Instance, (Object) null)) return; UIDefaultCursor.Instance.SetupCursor(UIDefaultCursor.CursorMode.Arrow); } private void ClearCollections() { this._regionMapsIds.Clear(); this._regionMapBundlePrefixes.Clear(); this._pendingRequests.Clear(); this._FriendTags.Clear(); this._regionSections = (UIWorldMap_Common.MapSubsection[,]) null; } protected virtual void Update() { if (!UIWorldMap_Common.DisplayingRegionMap) return; this.ProcessDragNDrop(); this.ProcessInspector(); int[] numArray = this.CalculateRegionsToLoad(); int num1 = numArray[0]; int num2 = numArray[1]; int num3 = numArray[2]; int num4 = numArray[3]; for (int row = 0; row < 14; ++row) { for (int col = 0; col < 14; ++col) { if (row > num3 && row < num4 && (col > num1 && col < num2) || (row == num3 || row == num4 || (col == num1 || col == num2)) && this.IsRegionVisible(row, col)) { UIWorldMap_Common.MapSubsection region = this._regionSections[row, col]; if (this._regionSections[row, col].isUnloaded) { this._regionSections[row, col].isUnloaded = false; WBLoader.BundleRequest request = WBLoader.Instance.LoadAssetBundle(AssetPath.BuildPlatformAssetBundleName("RegionMaps", this._regionSections[row, col].bundleName), WBLoader.Priority.Normal); this._pendingRequests.Add(request); this.StartCoroutine(this.WaitAndSetTexture(request, region, (Action) null)); } } else if (this._regionSections.Length > row && Object.op_Inequality((Object) this._regionSections[row, col].regionObject, (Object) null)) { MeshRenderer meshRenderer = (MeshRenderer) this._regionSections[row, col].regionObject.GetComponent<MeshRenderer>(); if (Object.op_Inequality((Object) meshRenderer, (Object) null)) { this._regionSections[row, col].isUnloaded = true; Resources.UnloadAsset((Object) ((Renderer) meshRenderer).get_material().get_mainTexture()); ((Renderer) meshRenderer).set_enabled(false); } } } } } public void OnButtonStateChange(UIButton button) { if (button.controlState == UIButton.CONTROL_STATE.OVER && this.m_lastButtonChangedState != UIButton.CONTROL_STATE.ACTIVE) WBAudioManager.Instance.Play(this.WMRegionOver, (Object) this, AudioResourceUsage.Keep, (Transform) null, 0.0f, (AudioCompletionCallback) null); else if (button.controlState == UIButton.CONTROL_STATE.ACTIVE) WBAudioManager.Instance.Play(this.WMRegionSelectSound, (Object) this, AudioResourceUsage.Clear, (Transform) null, 0.0f, (AudioCompletionCallback) null); this.m_lastButtonChangedState = button.controlState; } private void ProcessInspector() { if (!this._OpenInspector) return; if (this._inspectorShouldClose) { this.Loots.SetActive(false); this._OpenInspector = false; this._inspectorOpened = false; this._materialTracker.ReleaseAll(); } else if (!this._inspectorOpened) { Vector3 vector3 = UIManager.Instance.rayCamera.ScreenToWorldPoint(Input.get_mousePosition()); // ISSUE: explicit reference operation ((Vector3) @vector3).\u002Ector((float) vector3.x, (float) vector3.y, -400f); vector3 = Vector3.op_Addition(vector3, new Vector3(109f, -117f, 0.0f)); this._LootInspectorForcePosition = vector3; this.Loots.SetActive(true); FlashAnimationX.ForceAllChildAnimationsToEnd(this.Loots, "Popup_Loot3", true); FlashAnimationX.PlayAllChildAnimations(this.Loots, "Popup_Loot1", 0.0f, 1f); Texture2D texture2D = this._inspectorTexture; ((Component) this._weaponInfos.WeaponIconContainer1).get_gameObject().SetActive(true); if (Object.op_Inequality((Object) texture2D, (Object) null)) { if (this._inspectorWeaponLevel > 0) { this._weaponInfos.LevelStar.SetActive(true); ((Component) this._weaponInfos.MessageField).get_transform().set_localPosition(new Vector3(-70f, 20f, -25f)); FlashAnimationX.ForceAllChildAnimationsToEnd(this.Loots, "Frame1", true); FlashAnimationX.PlayAllChildAnimations(this.Loots, "Frame" + (object) this._inspectorWeaponFootprint, 0.0f, 1f); Material defaultUiMaterial = this._materialTracker.CreateDefaultUIMaterial(texture2D); FordUtility.SetupAlreadyLoadedIcon(this._inspectorWeaponFootprint, this._inspectorIconAspect, texture2D, defaultUiMaterial, false, 40f, this._weaponInfos.WeaponIconContainer1, true); ((Component) this._weaponInfos.WeaponIconContainer1).get_transform().set_localPosition(new Vector3((float) (20 * (this._inspectorWeaponFootprint - 1) - 53), (float) ((Component) this._weaponInfos.WeaponIconContainer1).get_transform().get_localPosition().y, 0.0f)); } else { this._weaponInfos.LevelStar.SetActive(false); FlashAnimationX.PlayAllChildAnimations(this.Loots, "Popup_Loot0", 0.0f, 1f); ((Component) this._weaponInfos.MessageField).get_transform().set_localPosition(new Vector3(-70f, 20f, -25f)); Material defaultUiMaterial = this._materialTracker.CreateDefaultUIMaterial(texture2D); FordUtility.SetupAlreadyLoadedIcon(this._inspectorWeaponFootprint, this._inspectorIconAspect, texture2D, defaultUiMaterial, false, 40f, this._weaponInfos.WeaponIconContainer1, true); ((Component) this._weaponInfos.WeaponIconContainer1).get_transform().set_localPosition(new Vector3(0.0f, (float) ((Component) this._weaponInfos.WeaponIconContainer1).get_transform().get_localPosition().y, 0.0f)); } } else { FlashAnimationX.PlayAllChildAnimations(this.Loots, "Popup_Loot0", 0.0f, 1f); ((Component) this._weaponInfos.MessageField).get_transform().set_localPosition(new Vector3(-70f, 20f, -25f)); ((Component) this._weaponInfos.WeaponIconContainer1).get_gameObject().SetActive(false); } this._weaponInfos.MessageField.Text = this._inspectorMessage; this._weaponInfos.Title.Text = this._inspectorTitle; this._weaponInfos.LevelText.Text = this._inspectorWeaponLevel <= 0 ? string.Empty : this._inspectorWeaponLevel.ToString(); this._inspectorOpened = true; foreach (GameObject gameObject in this._weaponInfos.GreenChecks) { if (Object.op_Inequality((Object) gameObject, (Object) null)) gameObject.SetActive(false); } } this._inspectorShouldClose = true; } private void OpenInspector(string message, string title, int weaponLevel, int footprint, Texture2D tex, float iconAspect) { if (!this._OpenInspector) { this._inspectorIconAspect = iconAspect; this._inspectorMessage = message; this._inspectorWeaponFootprint = footprint; this._inspectorTitle = title; this._inspectorTexture = tex; this._inspectorWeaponLevel = weaponLevel; this._OpenInspector = true; } if (!this._OpenInspector || !(message == this._inspectorMessage) || footprint != this._inspectorWeaponFootprint) return; this._inspectorShouldClose = false; } private void DisplayRegionMap(string regionNumber) { GameLog.drej.InfoFormat("[Map] DisplayRegionMap: " + (object) (WildernessRegion) int.Parse(regionNumber)); this.SetMapButtonEnabled(false); this.TitleText.Text = FordLocalizationMgr.Menu.GetStringFromId("WORLD_MAP_CHOOSE_PORTAL", string.Empty, string.Empty); WildernessRegion toDisplay = (WildernessRegion) int.Parse(regionNumber); this.ClearFriendTags(); this.RegionMapHook.SetActive(true); if (this._currentRegionMap != toDisplay) { Object.Destroy((Object) this._currentRegionMapObject); this._currentRegionMapObject = (GameObject) null; } this._currentRegionMap = toDisplay; this.StartCoroutine(this.PlaceFriends(true)); this.StartCoroutine(this.InstantiateRegionMap(toDisplay)); this.RegionMapCamera.set_orthographicSize(437f); this.unitTestReady = true; } private void ClearFriendTags() { using (Dictionary<string, List<WMFriend>>.Enumerator enumerator1 = this._FriendTags.GetEnumerator()) { while (enumerator1.MoveNext()) { using (List<WMFriend>.Enumerator enumerator2 = enumerator1.Current.Value.GetEnumerator()) { while (enumerator2.MoveNext()) { WMFriend current = enumerator2.Current; UIGenericOverhead overHead = current.GetOverHead(); if (Object.op_Inequality((Object) overHead, (Object) null)) FordPanelManager.Instance.OverheadPanelManager.Unregister((Component) overHead); Object.DestroyImmediate((Object) ((Component) current).get_gameObject()); } } } } this._FriendTags.Clear(); } private void FocusOn(Vector3 targetPosition) { ((Component) this.RegionMapCamera).get_transform().set_position(new Vector3((float) targetPosition.x, (float) (targetPosition.y - 480.0), (float) ((Component) this.RegionMapCamera).get_transform().get_position().z)); this.ClampViewportToRegionMap(); } [DebuggerHidden] private IEnumerator FocusOnLerp(Vector3 targetPosition) { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CFocusOnLerp\u003Ec__Iterator168() { targetPosition = targetPosition, \u003C\u0024\u003EtargetPosition = targetPosition, \u003C\u003Ef__this = this }; } [DebuggerHidden] private IEnumerator PlaceFriends(bool displayingRegionMap = false) { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CPlaceFriends\u003Ec__Iterator169() { displayingRegionMap = displayingRegionMap, \u003C\u0024\u003EdisplayingRegionMap = displayingRegionMap, \u003C\u003Ef__this = this }; } private void PlaceFriend(bool displayingRegionMap, long playerId, Action onDone) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type UIWorldMap_Common.\u003CPlaceFriend\u003Ec__AnonStorey30E friendCAnonStorey30E = new UIWorldMap_Common.\u003CPlaceFriend\u003Ec__AnonStorey30E(); // ISSUE: reference to a compiler-generated field friendCAnonStorey30E.onDone = onDone; // ISSUE: reference to a compiler-generated field friendCAnonStorey30E.playerId = playerId; // ISSUE: reference to a compiler-generated field friendCAnonStorey30E.displayingRegionMap = displayingRegionMap; // ISSUE: reference to a compiler-generated field friendCAnonStorey30E.\u003C\u003Ef__this = this; // ISSUE: reference to a compiler-generated field // ISSUE: reference to a compiler-generated method NetworkMgr.Instance.GetPersistentRoomByName(friendCAnonStorey30E.playerId, "Art_Domain", new Action<ClientOperationResult<AvailablePersistentRoomInfo[]>>(friendCAnonStorey30E.\u003C\u003Em__50B)); } private Transform GetRegionTransform(WildernessRegion wildernessRegion) { return this._topLevelWorldMap.GetRegionTransform(wildernessRegion); } private bool PlacePlayer() { if (UIWorldMap_Common.DisplayingRegionMap) { PlayerLegoMiniFigure playerLegoMiniFigure = FordGameRoom.Instance.GetLocalAvatar() as PlayerLegoMiniFigure; if (!AssertionGameModule.Verify(Object.op_Inequality((Object) playerLegoMiniFigure, (Object) null), false, "[WorldMap] Player is null. Cannot set player location")) return false; GameObject gameObject = FordUtility.FindChildRecursively(this.RegionMapHook.get_transform(), NetworkMgr.Instance.CharacterName); if (Object.op_Equality((Object) gameObject, (Object) null)) { gameObject = new GameObject(NetworkMgr.Instance.CharacterName); this._playerArrow = (WMLocalPlayer) gameObject.AddComponent<WMLocalPlayer>(); this._playerArrow.RegisterOverhead(this.RegionMapCamera); } else { this._playerArrow = (WMLocalPlayer) gameObject.GetComponent<WMLocalPlayer>(); if (!AssertionGameModule.Verify(Object.op_Inequality((Object) this._playerArrow, (Object) null), false, "[WorldMap] Player Tag has been removed. Cannot set player location")) return false; } if (Object.op_Inequality((Object) this._playerArrow, (Object) null)) { UIWMPlayerOverhead uiwmPlayerOverhead = (UIWMPlayerOverhead) this._playerArrow.GetOverHead(); if (Object.op_Inequality((Object) uiwmPlayerOverhead, (Object) null)) { Vector3 vector3_1 = VectorExtensions.FlattenY(playerLegoMiniFigure.GetAt()); // ISSUE: explicit reference operation Vector3 normalized = ((Vector3) @vector3_1).get_normalized(); this.mainCamera = !Object.op_Inequality((Object) IsoCamera.Instance, (Object) null) ? (Camera) null : ((Component) IsoCamera.Instance).get_camera(); if (Object.op_Inequality((Object) this.mainCamera, (Object) null)) { Vector3 vector3_2 = ((Component) this.mainCamera).get_transform().InverseTransformDirection(normalized); Vector3 vector3_3; // ISSUE: explicit reference operation ((Vector3) @vector3_3).\u002Ector((float) vector3_2.x, (float) vector3_2.z, 0.0f); Quaternion playerLookAt = Quaternion.FromToRotation(new Vector3(0.0f, 1f, 0.0f), vector3_3); uiwmPlayerOverhead.SetArrowDirection(playerLookAt); } uiwmPlayerOverhead.Show(); } } Transform transform = (Transform) null; Vector3 zero = Vector3.get_zero(); if (FordGameRoom.Instance.WildernessCat == WildernessCategory.Tile) { transform = this._currentRegionMapObject.get_transform().FindChild(FordGameRoom.Instance.m_RoomName); // ISSUE: explicit reference operation ((Vector3) @zero).\u002Ector(playerLegoMiniFigure.Position.x, 0.0f, playerLegoMiniFigure.Position.z); } else { GameObject childRecursively = FordUtility.FindChildRecursively(this._currentRegionMapObject.get_transform(), FordGameRoom.Instance.m_RoomName); if (Object.op_Inequality((Object) childRecursively, (Object) null)) transform = childRecursively.get_transform(); } if (Object.op_Inequality((Object) transform, (Object) null)) { gameObject.get_transform().set_parent(((Component) transform).get_transform()); gameObject.get_transform().set_localPosition(zero); return true; } CommonLog.Interface.Error((object) "[WorldMap] Could not find Player's room location. Cannot set player location."); return false; } if (Object.op_Inequality((Object) this._topLevelWorldMap, (Object) null) && Object.op_Inequality((Object) FordGameRoom.Instance, (Object) null)) this._topLevelWorldMap.PlacePlayer(FordGameRoom.Instance.WildernessCat, FordGameRoom.Instance.WildernessReg); return true; } private void CreateFriendTag(long playerId, GameModuleProtocol.FriendActivity activity, Transform friendRoom, bool byRegion) { GameObject gameObject = FordUtility.FindChildRecursively(this.RegionMapHook.get_transform(), playerId.ToString()); WMFriend wmFriend; if (Object.op_Equality((Object) gameObject, (Object) null)) { gameObject = new GameObject(playerId.ToString()); wmFriend = (WMFriend) gameObject.AddComponent<WMFriend>(); wmFriend.RegisterOverhead(!byRegion ? this.RegionMapCamera : UIManager.Instance.uiCameras[0].camera); } else wmFriend = (WMFriend) gameObject.GetComponent<WMFriend>(); UIWMFriendOverhead_Common friendOverheadCommon = (UIWMFriendOverhead_Common) wmFriend.GetOverHead(); if (Object.op_Inequality((Object) friendOverheadCommon, (Object) null)) { friendOverheadCommon.FriendsAtThisPos.Add(playerId); friendOverheadCommon.World = byRegion; } if (byRegion) { gameObject.get_transform().set_parent(friendRoom); gameObject.get_transform().set_localPosition(new Vector3(0.0f, 0.0f, -10f)); if (!this._FriendTags.ContainsKey(((Enum) activity.CurrentRegion).ToString())) this._FriendTags.Add(((Enum) activity.CurrentRegion).ToString(), new List<WMFriend>()); this._FriendTags[((Enum) activity.CurrentRegion).ToString()].Add(wmFriend); } else { gameObject.get_transform().set_parent(friendRoom); gameObject.get_transform().set_localPosition(new Vector3(activity.TileLocalPosition.x, activity.TileLocalPosition.y, activity.TileLocalPosition.z)); if (!this._FriendTags.ContainsKey(((Object) friendRoom).get_name())) this._FriendTags.Add(((Object) friendRoom).get_name(), new List<WMFriend>()); this._FriendTags[((Object) friendRoom).get_name()].Add(wmFriend); } } private bool AddToExistingTagsByPosition(long playerIdToAdd, GameModuleProtocol.FriendActivity activity, Transform friendRoom) { Vector3 vector3_1; // ISSUE: explicit reference operation ((Vector3) @vector3_1).\u002Ector(activity.TileLocalPosition.x, activity.TileLocalPosition.y, activity.TileLocalPosition.z); bool flag = false; if (this._FriendTags.ContainsKey(((Object) friendRoom).get_name())) { using (List<WMFriend>.Enumerator enumerator1 = this._FriendTags[((Object) friendRoom).get_name()].GetEnumerator()) { while (enumerator1.MoveNext()) { WMFriend current = enumerator1.Current; Vector3 vector3_2 = VectorExtensions.FlattenY(Vector3.op_Subtraction(((Component) current).get_transform().get_localPosition(), vector3_1)); // ISSUE: explicit reference operation if ((double) ((Vector3) @vector3_2).get_magnitude() < 20.0) { UIWMFriendOverhead_Common friendOverheadCommon = (UIWMFriendOverhead_Common) current.GetOverHead(); if (Object.op_Inequality((Object) friendOverheadCommon, (Object) null)) { using (List<long>.Enumerator enumerator2 = friendOverheadCommon.FriendsAtThisPos.GetEnumerator()) { while (enumerator2.MoveNext()) { if (enumerator2.Current == playerIdToAdd) flag = true; } } if (!flag) friendOverheadCommon.FriendsAtThisPos.Add(playerIdToAdd); } flag = true; } } } } return flag; } private bool AddToExistingTagsByRegion(long playerIdToAdd, GameModuleProtocol.FriendActivity activity) { bool flag = false; if (this._FriendTags.ContainsKey(((Enum) activity.CurrentRegion).ToString())) { UIWMFriendOverhead_Common friendOverheadCommon = (UIWMFriendOverhead_Common) this._FriendTags[((Enum) activity.CurrentRegion).ToString()][0].GetOverHead(); if (Object.op_Inequality((Object) friendOverheadCommon, (Object) null)) { using (List<long>.Enumerator enumerator = friendOverheadCommon.FriendsAtThisPos.GetEnumerator()) { while (enumerator.MoveNext()) { if (enumerator.Current == playerIdToAdd) flag = true; } } if (!flag) friendOverheadCommon.FriendsAtThisPos.Add(playerIdToAdd); } flag = true; } return flag; } public void CloseFriendJoinPanels() { using (Dictionary<string, List<WMFriend>>.Enumerator enumerator1 = this._FriendTags.GetEnumerator()) { while (enumerator1.MoveNext()) { using (List<WMFriend>.Enumerator enumerator2 = enumerator1.Current.Value.GetEnumerator()) { while (enumerator2.MoveNext()) { UIWMFriendOverhead_Common friendOverheadCommon = (UIWMFriendOverhead_Common) enumerator2.Current.GetOverHead(); if (Object.op_Inequality((Object) friendOverheadCommon, (Object) null)) friendOverheadCommon.OnCloseJoinClick(); } } } } } private bool FindCurrentGoalPosition(ref Vector3 vPosition) { FordGameRoom.Instance._PlayerGoalProgression.GetCurrentWorldMapInfo(ref this._goalInfo); bool flag1 = (this._goalInfo.FieldsUsed & 1) == 1; bool flag2 = (this._goalInfo.FieldsUsed & 2) == 2; WildernessRegion wildernessRegion = WildernessRegion.Zoo; if (flag1) wildernessRegion = GraphMgr.Instance.FindRegionContainingRoom(this._goalInfo.TileName); if (flag1 && flag2 && this._currentRegionMap == wildernessRegion) { Transform child = this._currentRegionMapObject.get_transform().FindChild(this._goalInfo.TileName); if (Object.op_Inequality((Object) child, (Object) null)) { vPosition = child.TransformPoint(this._goalInfo.Position); return true; } GameObject childRecursively = FordUtility.FindChildRecursively(this._currentRegionMapObject.get_transform(), this._goalInfo.TileName); if (Object.op_Inequality((Object) childRecursively, (Object) null)) { vPosition = childRecursively.get_transform().get_position(); return true; } } return false; } [DebuggerHidden] private IEnumerator InstantiateRegionMap(WildernessRegion toDisplay) { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new UIWorldMap_Common.\u003CInstantiateRegionMap\u003Ec__Iterator16A() { toDisplay = toDisplay, \u003C\u0024\u003EtoDisplay = toDisplay, \u003C\u003Ef__this = this }; } private void LoadWorldMapItemOfType<T>(Action<T> actionToRun) where T : WMItem { foreach (T obj in this.RegionMapHook.GetComponentsInChildren(typeof (T), true)) { if (actionToRun != null) actionToRun(obj); obj.ManualInitAndLoadItem(); } } private void SetMapButtonEnabled(bool enabled) { if (!Object.op_Inequality((Object) this._topLevelWorldMap, (Object) null)) return; if (this._topLevelWorldMap.JungleButtons != null) { foreach (UIButton uiButton in this._topLevelWorldMap.JungleButtons) uiButton.controlIsEnabled = enabled; } if (this._topLevelWorldMap.MountainButtons == null) return; foreach (UIButton uiButton in this._topLevelWorldMap.MountainButtons) uiButton.controlIsEnabled = enabled; } protected void ZoomRegionMap(float zoomValue, Vector3 zoomMoveVector) { // ISSUE: explicit reference operation // ISSUE: explicit reference operation ((Component) this.RegionMapCamera).get_transform().set_position(Vector3.op_Addition(((Component) this.RegionMapCamera).get_transform().get_position(), Vector3.op_Multiply((float) (((double) zoomValue <= 0.0 ? -1.0 : 1.0) * ((double) ((Vector3) @zoomMoveVector).get_magnitude() / 10.0)), ((Vector3) @zoomMoveVector).get_normalized()))); this.ClampViewportToRegionMap(); Transform transform1 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_1 = Vector3.op_Addition(transform1.get_localPosition(), Vector3.op_Multiply(zoomValue, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform1.set_localPosition(vector3_1); if (((Component) this.RegionMapCamera).get_transform().get_localPosition().z > (double) this.MaxZoomValue) { Transform transform2 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_2 = Vector3.op_Subtraction(transform2.get_localPosition(), Vector3.op_Multiply(zoomValue, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform2.set_localPosition(vector3_2); Transform transform3 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_3 = Vector3.op_Addition(transform3.get_localPosition(), Vector3.op_Multiply(zoomValue / 2f, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform3.set_localPosition(vector3_3); if (((Component) this.RegionMapCamera).get_transform().get_localPosition().z > (double) this.MaxZoomValue) { Transform transform4 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_4 = Vector3.op_Subtraction(transform4.get_localPosition(), Vector3.op_Multiply(zoomValue / 2f, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform4.set_localPosition(vector3_4); } } else if (((Component) this.RegionMapCamera).get_transform().get_localPosition().z < (double) this.MinZoomValue) { Transform transform2 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_2 = Vector3.op_Subtraction(transform2.get_localPosition(), Vector3.op_Multiply(zoomValue, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform2.set_localPosition(vector3_2); Transform transform3 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_3 = Vector3.op_Addition(transform3.get_localPosition(), Vector3.op_Multiply(zoomValue / 2f, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform3.set_localPosition(vector3_3); if (((Component) this.RegionMapCamera).get_transform().get_localPosition().z < (double) this.MinZoomValue) { Transform transform4 = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_4 = Vector3.op_Subtraction(transform4.get_localPosition(), Vector3.op_Multiply(zoomValue / 2f, ((Component) this.RegionMapCamera).get_transform().get_forward())); transform4.set_localPosition(vector3_4); } } if (!this.ClampViewportToRegionMap() || !this.IsOpenedViaDomain) return; this.DisplayWorldMap(); } private float GetZoomFactor() { return (float) (this.CurrZoomValue - this.MinZoomValue) / (float) (this.MaxZoomValue - this.MinZoomValue); } private void ProcessDragNDrop() { if (!this._startDragged && Input.GetMouseButtonDown(0)) { this._startDragged = true; if (Object.op_Inequality((Object) UIDefaultCursor.Instance, (Object) null)) UIDefaultCursor.Instance.SetupCursor(UIDefaultCursor.CursorMode.ClosedPaw); } else if (Input.GetMouseButtonUp(0)) { this._startDragged = false; if (Object.op_Inequality((Object) UIDefaultCursor.Instance, (Object) null)) UIDefaultCursor.Instance.SetupCursor(UIDefaultCursor.CursorMode.OpenedPaw); } else if (this._startDragged) { if (Object.op_Inequality((Object) UIDefaultCursor.Instance, (Object) null)) UIDefaultCursor.Instance.SetupCursor(UIDefaultCursor.CursorMode.ClosedPaw); Vector3 vector3_1 = Vector3.op_Subtraction(Input.get_mousePosition(), this._position); Transform transform = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_2 = Vector3.op_Subtraction(transform.get_position(), new Vector3((float) vector3_1.x, (float) vector3_1.y, 0.0f)); transform.set_position(vector3_2); this.ClampViewportToRegionMap(); } this._position = Input.get_mousePosition(); } private void CloseAllJoinPanels() { using (Dictionary<string, List<WMFriend>>.Enumerator enumerator1 = this._FriendTags.GetEnumerator()) { while (enumerator1.MoveNext()) { using (List<WMFriend>.Enumerator enumerator2 = enumerator1.Current.Value.GetEnumerator()) { while (enumerator2.MoveNext()) { UIWMFriendOverhead_Common friendOverheadCommon = (UIWMFriendOverhead_Common) enumerator2.Current.GetOverHead(); if (Object.op_Inequality((Object) friendOverheadCommon, (Object) null)) friendOverheadCommon.OnCloseJoinClick(); } } } } } protected bool ClampViewportToRegionMap() { Vector3 vector3_1 = this.RegionMapCamera.ViewportToWorldPoint(new Vector3(0.0f, 0.0f)); Vector3 vector3_2 = this.RegionMapCamera.ViewportToWorldPoint(new Vector3(1f, 1f)); int num1 = 1; int num2 = 1; if (this._regionMapDesc != null) { num1 = this._regionMapDesc.MapXGraphicTileSize; num2 = this._regionMapDesc.MapYGraphicTileSize; } Vector3 vector3_3; // ISSUE: explicit reference operation ((Vector3) @vector3_3).\u002Ector((float) (num1 * 180), (float) (num2 * 300 - 800), 0.0f); Vector3 vector3_4; // ISSUE: explicit reference operation ((Vector3) @vector3_4).\u002Ector((float) (-num1 * 180), (float) (-num2 * 300), 0.0f); Vector3 vector3_5 = Vector3.op_Addition(this.RegionMapHook.get_transform().get_position(), vector3_4); Vector3 vector3_6 = Vector3.op_Addition(this.RegionMapHook.get_transform().get_position(), vector3_3); float num3 = 0.0f; float num4 = 0.0f; bool flag1 = vector3_1.x < vector3_5.x; bool flag2 = vector3_2.x > vector3_6.x; bool flag3 = vector3_1.y < vector3_5.y; bool flag4 = vector3_2.y > vector3_6.y; int num5 = (!flag1 ? 0 : 1) + (!flag2 ? 0 : 1) + (!flag3 ? 0 : 1) + (!flag4 ? 0 : 1); if (flag1) num3 = (float) (vector3_5.x - vector3_1.x); else if (flag2) num3 = (float) (vector3_6.x - vector3_2.x); if (flag3) num4 = (float) (vector3_5.y - vector3_1.y); else if (flag4) num4 = (float) (vector3_6.y - vector3_2.y); if (num5 > 2 || flag1 && flag2 || flag4 && flag3) return true; Vector3 vector3_7; // ISSUE: explicit reference operation ((Vector3) @vector3_7).\u002Ector(num3, num4, 0.0f); Transform transform = ((Component) this.RegionMapCamera).get_transform(); Vector3 vector3_8 = Vector3.op_Addition(transform.get_position(), vector3_7); transform.set_position(vector3_8); return false; } public virtual void OnClickClose(UIButton btn) { this.StopAllCoroutines(); FordPanelManager.Instance.SafeDismissUIPanelLoading(); FordPanelManager.Instance.SwitchLayout(FordGameRoom.Instance.IsDomain() ? FordPanelBase.FordHUDGroup.Domain : FordPanelBase.FordHUDGroup.Wilderness, (Action<string, UIPanelBase>) null, (object) null, (Action<string>) null, (string[]) null); FordPanelManager.Instance.OverheadPanelManager.RestoreAll(); } private void OnZoomInClick() { this.ZoomRegionMap(30f, Vector3.get_zero()); } private void OnZoomOutClick() { this.ZoomRegionMap(-30f, Vector3.get_zero()); } private int ConvertPositionFromLetterToNumber(char letter) { return (int) letter - 65; } private char ConvertPositionFromNumberToLetter(int number) { return (char) (number + 65); } private Vector3 TranslateWorldPositionToMapPosition(Vector3 worldPosition) { Vector3 position = this.RegionMapHook.get_transform().get_position(); return Vector3.op_Subtraction(worldPosition, position); } private bool IsRegionVisible(int row, int col) { if (!FordUtility.IsPositionVisibleOnScreen(this.RegionMapCamera, this._regionSections[row, col].topLeft) && !FordUtility.IsPositionVisibleOnScreen(this.RegionMapCamera, this._regionSections[row, col].topRight) && !FordUtility.IsPositionVisibleOnScreen(this.RegionMapCamera, this._regionSections[row, col].bottomLeft)) return FordUtility.IsPositionVisibleOnScreen(this.RegionMapCamera, this._regionSections[row, col].bottomRight); return true; } private int[] CalculateRegionsToLoad() { RaycastHit raycastHit; Physics.Raycast(this.RegionMapCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0.0f)), ref raycastHit); // ISSUE: explicit reference operation Vector3 vector3 = this.TranslateWorldPositionToMapPosition(((RaycastHit) @raycastHit).get_point()); float zoomFactor = this.GetZoomFactor(); float num1 = Mathf.Lerp(this._minCamExtents.centerToX_Top, this._maxCamExtents.centerToX_Top, zoomFactor); float num2 = Mathf.Lerp(this._minCamExtents.centerToX_Bot, this._maxCamExtents.centerToX_Bot, zoomFactor); float num3 = Mathf.Lerp(this._minCamExtents.centerToY_Top, this._maxCamExtents.centerToY_Top, zoomFactor); float num4 = Mathf.Lerp(this._minCamExtents.centerToY_Bot, this._maxCamExtents.centerToY_Bot, zoomFactor); int[] regionIndex1 = this.GetRegionIndex(new Vector3((float) vector3.x - num1, (float) vector3.y + num3)); int[] regionIndex2 = this.GetRegionIndex(new Vector3((float) vector3.x + num1, (float) vector3.y + num3)); int[] regionIndex3 = this.GetRegionIndex(new Vector3((float) vector3.x + num2, (float) vector3.y + num4)); int[] numArray = new int[4]; int index1 = 0; int num5 = regionIndex1[0]; numArray[index1] = num5; int index2 = 1; int num6 = regionIndex2[0]; numArray[index2] = num6; int index3 = 2; int num7 = regionIndex1[1]; numArray[index3] = num7; int index4 = 3; int num8 = regionIndex3[1]; numArray[index4] = num8; return numArray; } private int[] GetRegionIndex(Vector3 regionMapPosition) { int num1 = (int) ((regionMapPosition.x - (double) this._regionMapSpecs.topX) / (double) this._regionMapSpecs.subsectionWidth); int num2 = 13 - (int) ((regionMapPosition.y + (double) this._regionMapSpecs.topY) / (double) this._regionMapSpecs.subsectionHeight); int[] numArray = new int[2]; int index1 = 0; int num3 = num1; numArray[index1] = num3; int index2 = 1; int num4 = num2; numArray[index2] = num4; return numArray; } protected Mesh CreateQuad(float width, float height) { if (Object.op_Equality((Object) this._quad, (Object) null)) this._quad = FordUtility.MakeMesh(width, height, 1f, true); return this._quad; } public class WeaponInfos { public GameObject MainObject; public WBSpriteText Title; public WBSpriteText LevelText; public GameObject LevelStar; public WBSpriteText MessageField; public GameObject[] GreenChecks; public SimpleSprite WeaponIconContainer1; } private struct MapSubsection { public GameObject regionObject; public string bundleName; public Vector3 topLeft; public Vector3 topRight; public Vector3 bottomLeft; public Vector3 bottomRight; public bool isUnloaded; } private struct RegionMapSpecs { public float topX; public float topY; public float subsectionWidth; public float subsectionHeight; } private struct CameraExtents { public float centerToX_Top; public float centerToX_Bot; public float centerToY_Top; public float centerToY_Bot; public override string ToString() { string format = "X:({0},{1}), Y:({2},{3})"; object[] objArray = new object[4]; int index1 = 0; // ISSUE: variable of a boxed type __Boxed<float> local1 = (ValueType) this.centerToX_Bot; objArray[index1] = (object) local1; int index2 = 1; // ISSUE: variable of a boxed type __Boxed<float> local2 = (ValueType) this.centerToX_Top; objArray[index2] = (object) local2; int index3 = 2; // ISSUE: variable of a boxed type __Boxed<float> local3 = (ValueType) this.centerToY_Bot; objArray[index3] = (object) local3; int index4 = 3; // ISSUE: variable of a boxed type __Boxed<float> local4 = (ValueType) this.centerToY_Top; objArray[index4] = (object) local4; return string.Format(format, objArray); } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/Assembly-CSharp/UIWorldMap_Common.cs
C#
gpl-3.0
66,286
/* * This file is part of tmdb-service. * * media-scanner is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * tmdb-service 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 tmdb-service. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2014 Caprica Software Limited. */ package uk.co.caprica.tmdb.domain; import com.google.common.base.Objects; /** * */ public final class Name { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { return Objects.hashCode( id, name ); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Name)) { return false; } Name other = (Name)obj; return Objects.equal(id , other.id ) && Objects.equal(name, other.name); } @Override public String toString() { return Objects.toStringHelper(this) .add("id" , id ) .add("name", name) .toString(); } }
caprica/tmdb-service
src/main/java/uk/co/caprica/tmdb/domain/Name.java
Java
gpl-3.0
1,804
package im.tox.antox.callbacks import android.app.{Notification, PendingIntent} import android.content.{Context, Intent} import android.preference.PreferenceManager import android.support.v4.app.NotificationCompat import android.util.Log import im.tox.antox.activities.MainActivity import im.tox.antox.data.AntoxDB import im.tox.antox.tox.ToxSingleton import im.tox.antox.utils.Hex import im.tox.antox.wrapper.ToxKey import im.tox.antoxnightly.R import im.tox.tox4j.core.callbacks.FriendRequestCallback object AntoxOnFriendRequestCallback { private val TAG = "im.tox.antox.TAG" val FRIEND_KEY = "im.tox.antox.FRIEND_KEY" val FRIEND_MESSAGE = "im.tox.antox.FRIEND_MESSAGE" } class AntoxOnFriendRequestCallback(private var ctx: Context) extends FriendRequestCallback { override def friendRequest(keyBytes: Array[Byte], timeDelta: Int, message: Array[Byte]): Unit = { val db = new AntoxDB(this.ctx) val key = new ToxKey(keyBytes) if (!db.isContactBlocked(key)){ db.addFriendRequest(key, new String(message, "UTF-8")) } db.close() ToxSingleton.updateFriendRequests(ctx) Log.d("FriendRequestCallback", "") val preferences = PreferenceManager.getDefaultSharedPreferences(this.ctx) if (preferences.getBoolean("notifications_enable_notifications", true) && preferences.getBoolean("notifications_friend_request", true)) { val vibratePattern = Array[Long](0, 500) if (!preferences.getBoolean("notifications_new_message_vibrate", true)) { vibratePattern(1) = 0 } val mBuilder = new NotificationCompat.Builder(this.ctx) .setSmallIcon(R.drawable.ic_actionbar) .setContentTitle(this.ctx.getString(R.string.friend_request)) .setContentText(new String(message, "UTF-8")) .setVibrate(vibratePattern) .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) val targetIntent = new Intent(this.ctx, classOf[MainActivity]) val contentIntent = PendingIntent.getActivity(this.ctx, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT) mBuilder.setContentIntent(contentIntent) ToxSingleton.mNotificationManager.notify(0, mBuilder.build()) } } }
mGhassen/Antox
app/src/main/scala/im/tox/antox/callbacks/AntoxOnFriendRequestCallback.scala
Scala
gpl-3.0
2,197
/* * include/ioasync.h * * 2016-01-01 written by Hoyleeson <hoyleeson@gmail.com> * Copyright (C) 2015-2016 by Hoyleeson. * * 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; version 2. * */ #ifndef _ANZZC_IOASYNC_H #define _ANZZC_IOASYNC_H #include <sys/socket.h> #include "types.h" #include "packet.h" #include "poller.h" #ifdef __cplusplus extern "C" { #endif typedef struct iohandler iohandler_t; typedef struct ioasync ioasync_t; #if 0 typedef void (*handle_func) (void *priv, uint8_t *data, int len); typedef void (*handlefrom_func) (void *priv, uint8_t *data, int len, void *from); typedef void (*accept_func) (void *priv, int acceptfd); typedef void (*close_func) (void *priv); #endif pack_buf_t *iohandler_pack_buf_alloc(iohandler_t *ioh); void iohandler_pack_buf_free(pack_buf_t *pkb); void iohandler_send(iohandler_t *ioh, const uint8_t *data, int len); void iohandler_sendto(iohandler_t *ioh, const uint8_t *data, int len, struct sockaddr *to); void iohandler_pkt_send(iohandler_t *ioh, pack_buf_t *pkb); void iohandler_pkt_sendto(iohandler_t *ioh, pack_buf_t *pkb, struct sockaddr *to); iohandler_t *iohandler_create(ioasync_t *aio, int fd, void (*handle)(void *, uint8_t *, int), void (*close)(void *), void *priv); iohandler_t *iohandler_accept_create(ioasync_t *aio, int fd, void (*accept)(void *, int), void (*close)(void *), void *priv); iohandler_t *iohandler_udp_create(ioasync_t *aio, int fd, void (*handlefrom)(void *, uint8_t *, int, void *), void (*close)(void *), void *priv); void iohandler_shutdown(iohandler_t *ioh); ioasync_t *ioasync_init(void); //void ioasync_loop(ioasync_t *aio); void ioasync_release(ioasync_t *aio); void global_ioasync_init(void); void global_ioasync_release(void); ioasync_t *get_global_ioasync(void); #ifdef __cplusplus } #endif #endif
hoyleeson/anzzc
include/ioasync.h
C
gpl-3.0
2,161
// OptionsPropertySheet.cpp : implementation file // #include "stdafx.h" #include "dmrg.h" #include "OptionsPropertySheet.h" // COptionsPropertySheet IMPLEMENT_DYNAMIC(COptionsPropertySheet, CMFCPropertySheet) COptionsPropertySheet::COptionsPropertySheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) :CMFCPropertySheet(nIDCaption, pParentWnd, iSelectPage), hIcon(0) { } COptionsPropertySheet::COptionsPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) :CMFCPropertySheet(pszCaption, pParentWnd, iSelectPage), hIcon(0) { } COptionsPropertySheet::~COptionsPropertySheet() { if (hIcon) DestroyIcon(hIcon); } BEGIN_MESSAGE_MAP(COptionsPropertySheet, CMFCPropertySheet) END_MESSAGE_MAP() // COptionsPropertySheet message handlers BOOL COptionsPropertySheet::OnInitDialog() { BOOL bResult = CMFCPropertySheet::OnInitDialog(); hIcon = static_cast<HICON>(::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0)); SetIcon(hIcon, FALSE); return bResult; }
aromanro/dmrg
dmrg/OptionsPropertySheet.cpp
C++
gpl-3.0
1,094
package de.unikiel.inf.comsys.neo4j.inference; /* * #%L * neo4j-sparql-extension * %% * Copyright (C) 2014 Niclas Hoyer * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import de.unikiel.inf.comsys.neo4j.inference.rules.Rules; import de.unikiel.inf.comsys.neo4j.inference.rules.Rule; import com.google.common.collect.Multiset; import com.google.common.collect.Multisets; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.rules.ErrorCollector; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.openrdf.model.ValueFactory; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.QueryResultHandlerException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.TupleQueryResultHandlerException; import org.openrdf.query.resultio.QueryResultParseException; import org.openrdf.query.resultio.TupleQueryResultParser; import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLParserFactory; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.repository.sail.SailRepositoryConnection; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.sail.memory.MemoryStore; @RunWith(Parameterized.class) public class SPARQLInferenceTest { private SailRepository repo; private SailRepositoryConnection conn; private ValueFactory vf; private final String name; private final String comment; private final String data; private final String expected; private final String queryString; private TupleQuery query; private TupleQuery nonInfQuery; private TupleQueryResultParser parser; private static InputStream getResource(String name) { if (name == null) { return null; } String pref = "file://"; if (name.startsWith(pref)) { name = name.substring(pref.length()); } return SPARQLInferenceTest.class.getResourceAsStream(name); } private static String getResourceAsString(String name) throws IOException { InputStream in = getResource(name); if (in == null) { return null; } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); return writer.toString(); } @Parameters(name = "{0} - {1}") public static Iterable<Object[]> data() throws RepositoryException, IOException, RDFParseException, MalformedQueryException, QueryEvaluationException { SailRepository repository = new SailRepository(new MemoryStore()); repository.initialize(); SailRepositoryConnection conn = repository.getConnection(); conn.add( getResource("/inference/kiel/manifest.ttl"), "file:///inference/kiel/", RDFFormat.TURTLE); TupleQuery q = conn.prepareTupleQuery( QueryLanguage.SPARQL, getResourceAsString("/inference/queryeval.sparql")); TupleQueryResult r = q.evaluate(); BindingSet b; String name; InputStream data; String query; InputStream result; String comment; ArrayList<Object[]> tests = new ArrayList<>(); while(r.hasNext()) { b = r.next(); String datastr = b.getValue("data").stringValue(); String resultstr = b.getValue("result").stringValue(); name = b.getValue("name").stringValue(); data = getResource(datastr); query = getResourceAsString(b.getValue("query").stringValue()); result = getResource(resultstr); if (b.hasBinding("comment")) { comment = b.getValue("comment").stringValue(); } else { comment = ""; } if (data != null && query != null && result != null) { Object[] test = {name, comment, datastr, query, resultstr}; tests.add(test); } } return tests; } public SPARQLInferenceTest( String name, String comment, String data, String query, String expected) throws RepositoryException { this.name = name; this.comment = comment; this.data = data; this.queryString = query; this.expected = expected; this.query = null; this.parser = null; } @Before public void before() throws RepositoryException, IOException, RDFParseException, MalformedQueryException, QueryResultParseException, QueryResultHandlerException { repo = new SailRepository(new MemoryStore()); repo.initialize(); conn = repo.getConnection(); vf = conn.getValueFactory(); conn.add(getResource(data), "file://", RDFFormat.TURTLE); SPARQLResultsXMLParserFactory factory = new SPARQLResultsXMLParserFactory(); parser = factory.getParser(); parser.setValueFactory(vf); List<Rule> rules; rules = Rules.fromOntology(getResource(data)); QueryRewriter rewriter = new QueryRewriter(conn, rules); query = (TupleQuery) rewriter.rewrite(QueryLanguage.SPARQL, queryString); nonInfQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); System.out.println("== QUERY (" + this.name + ") =="); System.out.println(nonInfQuery); System.out.println("== REWRITTEN QUERY (" + this.name + ") =="); System.out.println(query); } @After public void after() throws RepositoryException { conn.close(); repo.shutDown(); } private class QueryResult { private final Multiset<BindingSet> expect; private final Multiset<BindingSet> actual; private final Multiset<BindingSet> noninf; public QueryResult( Multiset<BindingSet> expected, Multiset<BindingSet> actual, Multiset<BindingSet> noninf) { this.expect = expected; this.actual = actual; this.noninf = noninf; } public Multiset<BindingSet> getExpected() { return expect; } public Multiset<BindingSet> getActual() { return actual; } public Multiset<BindingSet> getNonInferred() { return noninf; } public Multiset<BindingSet> getDiff() { return Multisets.difference(expect, actual); } @Override public String toString() { return getActual() + "\n" + getExpected(); } } private QueryResult runQuery() throws IOException, QueryEvaluationException, QueryResultParseException, TupleQueryResultHandlerException, QueryResultHandlerException { TestResultHandler noninf = new TestResultHandler(); TestResultHandler actual = new TestResultHandler(); TestResultHandler expect = new TestResultHandler(); parser.setQueryResultHandler(expect); parser.parseQueryResult(getResource(expected)); nonInfQuery.evaluate(noninf); query.evaluate(actual); Multiset<BindingSet> noninfset = noninf.getSolutions(); Multiset<BindingSet> expectset = expect.getSolutions(); Multiset<BindingSet> actualset = actual.getSolutions(); return new QueryResult(expectset, actualset, noninfset); } @org.junit.Rule public ErrorCollector collector = new ErrorCollector(); @Test public void subset() throws QueryEvaluationException, TupleQueryResultHandlerException, IOException, QueryResultParseException, QueryResultHandlerException { QueryResult q = this.runQuery(); assertTrue( q.getNonInferred() + " should be a subset of " + q.getActual(), Multisets.containsOccurrences( q.getActual(), q.getNonInferred() )); } @Test public void missing() throws QueryEvaluationException, TupleQueryResultHandlerException, IOException, QueryResultParseException, QueryResultHandlerException { QueryResult q = this.runQuery(); Multiset<BindingSet> missing = q.getExpected(); missing.removeAll(q.getActual()); for (BindingSet b : missing) { collector.addError(new Throwable("Missing " + b + " in result set")); } } @Test public void additional() throws QueryEvaluationException, TupleQueryResultHandlerException, IOException, QueryResultParseException, QueryResultHandlerException { QueryResult q = this.runQuery(); Multiset<BindingSet> additional = q.getActual(); additional.removeAll(q.getExpected()); for (BindingSet b : additional) { collector.addError(new Throwable(b + " shouldn't be in result set")); } } }
niclashoyer/neo4j-sparql-extension
src/test/java/de/unikiel/inf/comsys/neo4j/inference/SPARQLInferenceTest.java
Java
gpl-3.0
8,963
/* * Copyright 2013 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Dave Airlie * Alon Levy */ #include "qxl_drv.h" #include "qxl_object.h" /* * TODO: allocating a new gem(in qxl_bo) for each request. * This is wasteful since bo's are page aligned. */ static int qxl_alloc_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_alloc *qxl_alloc = data; int ret; struct qxl_bo *qobj; uint32_t handle; u32 domain = QXL_GEM_DOMAIN_VRAM; if (qxl_alloc->size == 0) { DRM_ERROR("invalid size %d\n", qxl_alloc->size); return -EINVAL; } ret = qxl_gem_object_create_with_handle(qdev, file_priv, domain, qxl_alloc->size, NULL, &qobj, &handle); if (ret) { DRM_ERROR("%s: failed to create gem ret=%d\n", __func__, ret); return -ENOMEM; } qxl_alloc->handle = handle; return 0; } static int qxl_map_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_map *qxl_map = data; return qxl_mode_dumb_mmap(file_priv, qdev->ddev, qxl_map->handle, &qxl_map->offset); } struct qxl_reloc_info { int type; struct qxl_bo *dst_bo; uint32_t dst_offset; struct qxl_bo *src_bo; int src_offset; }; /* * dst must be validated, i.e. whole bo on vram/surfacesram (right now all bo's * are on vram). * *(dst + dst_off) = qxl_bo_physical_address(src, src_off) */ static void apply_reloc(struct qxl_device *qdev, struct qxl_reloc_info *info) { void *reloc_page; reloc_page = qxl_bo_kmap_atomic_page(qdev, info->dst_bo, info->dst_offset & PAGE_MASK); *(uint64_t *)(reloc_page + (info->dst_offset & ~PAGE_MASK)) = qxl_bo_physical_address(qdev, info->src_bo, info->src_offset); qxl_bo_kunmap_atomic_page(qdev, info->dst_bo, reloc_page); } static void apply_surf_reloc(struct qxl_device *qdev, struct qxl_reloc_info *info) { uint32_t id = 0; void *reloc_page; if (info->src_bo && !info->src_bo->is_primary) { id = info->src_bo->surface_id; } reloc_page = qxl_bo_kmap_atomic_page(qdev, info->dst_bo, info->dst_offset & PAGE_MASK); *(uint32_t *)(reloc_page + (info->dst_offset & ~PAGE_MASK)) = id; qxl_bo_kunmap_atomic_page(qdev, info->dst_bo, reloc_page); } /* return holding the reference to this object */ static int qxlhw_handle_to_bo(struct drm_file *file_priv, uint64_t handle, struct qxl_release *release, struct qxl_bo **qbo_p) { struct drm_gem_object *gobj; struct qxl_bo *qobj; int ret; gobj = drm_gem_object_lookup(file_priv, handle); if (!gobj) { return -EINVAL; } qobj = gem_to_qxl_bo(gobj); ret = qxl_release_list_add(release, qobj); drm_gem_object_unreference_unlocked(gobj); if (ret) { return ret; } *qbo_p = qobj; return 0; } /* * Usage of execbuffer: * Relocations need to take into account the full QXLDrawable size. * However, the command as passed from user space must *not* contain the initial * QXLReleaseInfo struct (first XXX bytes) */ static int qxl_process_single_command(struct qxl_device *qdev, struct drm_qxl_command *cmd, struct drm_file *file_priv) { struct qxl_reloc_info *reloc_info; int release_type; struct qxl_release *release; struct qxl_bo *cmd_bo; void *fb_cmd; int i, ret, num_relocs; int unwritten; switch (cmd->type) { case QXL_CMD_DRAW: release_type = QXL_RELEASE_DRAWABLE; break; case QXL_CMD_SURFACE: case QXL_CMD_CURSOR: default: DRM_DEBUG("Only draw commands in execbuffers\n"); return -EINVAL; break; } if (cmd->command_size > PAGE_SIZE - sizeof(union qxl_release_info)) { return -EINVAL; } if (!access_ok(VERIFY_READ, (void *)(unsigned long)cmd->command, cmd->command_size)) { return -EFAULT; } reloc_info = kmalloc_array(cmd->relocs_num, sizeof(struct qxl_reloc_info), GFP_KERNEL); if (!reloc_info) { return -ENOMEM; } ret = qxl_alloc_release_reserved(qdev, sizeof(union qxl_release_info) + cmd->command_size, release_type, &release, &cmd_bo); if (ret) { goto out_free_reloc; } /* TODO copy slow path code from i915 */ fb_cmd = qxl_bo_kmap_atomic_page(qdev, cmd_bo, (release->release_offset & PAGE_SIZE)); unwritten = __copy_from_user_inatomic_nocache(fb_cmd + sizeof(union qxl_release_info) + (release->release_offset & ~PAGE_SIZE), (void *)(unsigned long)cmd->command, cmd->command_size); { struct qxl_drawable *draw = fb_cmd; draw->mm_time = qdev->rom->mm_clock; } qxl_bo_kunmap_atomic_page(qdev, cmd_bo, fb_cmd); if (unwritten) { DRM_ERROR("got unwritten %d\n", unwritten); ret = -EFAULT; goto out_free_release; } /* fill out reloc info structs */ num_relocs = 0; for (i = 0; i < cmd->relocs_num; ++i) { struct drm_qxl_reloc reloc; if (copy_from_user(&reloc, &((struct drm_qxl_reloc *)(uintptr_t)cmd->relocs)[i], sizeof(reloc))) { ret = -EFAULT; goto out_free_bos; } /* add the bos to the list of bos to validate - need to validate first then process relocs? */ if (reloc.reloc_type != QXL_RELOC_TYPE_BO && reloc.reloc_type != QXL_RELOC_TYPE_SURF) { DRM_DEBUG("unknown reloc type %d\n", reloc.reloc_type); ret = -EINVAL; goto out_free_bos; } reloc_info[i].type = reloc.reloc_type; if (reloc.dst_handle) { ret = qxlhw_handle_to_bo(file_priv, reloc.dst_handle, release, &reloc_info[i].dst_bo); if (ret) { goto out_free_bos; } reloc_info[i].dst_offset = reloc.dst_offset; } else { reloc_info[i].dst_bo = cmd_bo; reloc_info[i].dst_offset = reloc.dst_offset + release->release_offset; } num_relocs++; /* reserve and validate the reloc dst bo */ if (reloc.reloc_type == QXL_RELOC_TYPE_BO || reloc.src_handle) { ret = qxlhw_handle_to_bo(file_priv, reloc.src_handle, release, &reloc_info[i].src_bo); if (ret) { goto out_free_bos; } reloc_info[i].src_offset = reloc.src_offset; } else { reloc_info[i].src_bo = NULL; reloc_info[i].src_offset = 0; } } /* validate all buffers */ ret = qxl_release_reserve_list(release, false); if (ret) { goto out_free_bos; } for (i = 0; i < cmd->relocs_num; ++i) { if (reloc_info[i].type == QXL_RELOC_TYPE_BO) { apply_reloc(qdev, &reloc_info[i]); } else if (reloc_info[i].type == QXL_RELOC_TYPE_SURF) { apply_surf_reloc(qdev, &reloc_info[i]); } } ret = qxl_push_command_ring_release(qdev, release, cmd->type, true); if (ret) { qxl_release_backoff_reserve_list(release); } else { qxl_release_fence_buffer_objects(release); } out_free_bos: out_free_release: if (ret) { qxl_release_free(qdev, release); } out_free_reloc: kfree(reloc_info); return ret; } static int qxl_execbuffer_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_execbuffer *execbuffer = data; struct drm_qxl_command user_cmd; int cmd_num; int ret; for (cmd_num = 0; cmd_num < execbuffer->commands_num; ++cmd_num) { struct drm_qxl_command *commands = (struct drm_qxl_command *)(uintptr_t)execbuffer->commands; if (copy_from_user(&user_cmd, &commands[cmd_num], sizeof(user_cmd))) { return -EFAULT; } ret = qxl_process_single_command(qdev, &user_cmd, file_priv); if (ret) { return ret; } } return 0; } static int qxl_update_area_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_update_area *update_area = data; struct qxl_rect area = {.left = update_area->left, .top = update_area->top, .right = update_area->right, .bottom = update_area->bottom }; int ret; struct drm_gem_object *gobj = NULL; struct qxl_bo *qobj = NULL; if (update_area->left >= update_area->right || update_area->top >= update_area->bottom) { return -EINVAL; } gobj = drm_gem_object_lookup(file, update_area->handle); if (gobj == NULL) { return -ENOENT; } qobj = gem_to_qxl_bo(gobj); ret = qxl_bo_reserve(qobj, false); if (ret) { goto out; } if (!qobj->pin_count) { qxl_ttm_placement_from_domain(qobj, qobj->type, false); ret = ttm_bo_validate(&qobj->tbo, &qobj->placement, true, false); if (unlikely(ret)) { goto out; } } ret = qxl_bo_check_id(qdev, qobj); if (ret) { goto out2; } if (!qobj->surface_id) { DRM_ERROR("got update area for surface with no id %d\n", update_area->handle); } ret = qxl_io_update_area(qdev, qobj, &area); out2: qxl_bo_unreserve(qobj); out: drm_gem_object_unreference_unlocked(gobj); return ret; } static int qxl_getparam_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_getparam *param = data; switch (param->param) { case QXL_PARAM_NUM_SURFACES: param->value = qdev->rom->n_surfaces; break; case QXL_PARAM_MAX_RELOCS: param->value = QXL_MAX_RES; break; default: return -EINVAL; } return 0; } static int qxl_clientcap_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_clientcap *param = data; int byte, idx; byte = param->index / 8; idx = param->index % 8; if (qdev->pdev->revision < 4) { return -ENOSYS; } if (byte >= 58) { return -ENOSYS; } if (qdev->rom->client_capabilities[byte] & (1 << idx)) { return 0; } return -ENOSYS; } static int qxl_alloc_surf_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct qxl_device *qdev = dev->dev_private; struct drm_qxl_alloc_surf *param = data; struct qxl_bo *qobj; int handle; int ret; int size, actual_stride; struct qxl_surface surf; /* work out size allocate bo with handle */ actual_stride = param->stride < 0 ? -param->stride : param->stride; size = actual_stride * param->height + actual_stride; surf.format = param->format; surf.width = param->width; surf.height = param->height; surf.stride = param->stride; surf.data = 0; ret = qxl_gem_object_create_with_handle(qdev, file, QXL_GEM_DOMAIN_SURFACE, size, &surf, &qobj, &handle); if (ret) { DRM_ERROR("%s: failed to create gem ret=%d\n", __func__, ret); return -ENOMEM; } else { param->handle = handle; } return ret; } const struct drm_ioctl_desc qxl_ioctls[] = { DRM_IOCTL_DEF_DRV(QXL_ALLOC, qxl_alloc_ioctl, DRM_AUTH), DRM_IOCTL_DEF_DRV(QXL_MAP, qxl_map_ioctl, DRM_AUTH), DRM_IOCTL_DEF_DRV(QXL_EXECBUFFER, qxl_execbuffer_ioctl, DRM_AUTH), DRM_IOCTL_DEF_DRV(QXL_UPDATE_AREA, qxl_update_area_ioctl, DRM_AUTH), DRM_IOCTL_DEF_DRV(QXL_GETPARAM, qxl_getparam_ioctl, DRM_AUTH), DRM_IOCTL_DEF_DRV(QXL_CLIENTCAP, qxl_clientcap_ioctl, DRM_AUTH), DRM_IOCTL_DEF_DRV(QXL_ALLOC_SURF, qxl_alloc_surf_ioctl, DRM_AUTH), }; int qxl_max_ioctls = ARRAY_SIZE(qxl_ioctls);
williamfdevine/PrettyLinux
drivers/gpu/drm/qxl/qxl_ioctl.c
C
gpl-3.0
12,165
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CMaterialBlockOutputColorDeferred : CMaterialRootBlock { [Ordinal(1)] [RED("isTwoSided")] public CBool IsTwoSided { get; set;} [Ordinal(2)] [RED("rawOutput")] public CBool RawOutput { get; set;} [Ordinal(3)] [RED("maskThreshold")] public CFloat MaskThreshold { get; set;} [Ordinal(4)] [RED("terrain")] public CBool Terrain { get; set;} public CMaterialBlockOutputColorDeferred(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CMaterialBlockOutputColorDeferred(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/CMaterialBlockOutputColorDeferred.cs
C#
gpl-3.0
1,019
// Decompiled with JetBrains decompiler // Type: System.Web.UI.WebControls.ParsingCulture // Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll namespace System.Web.UI.WebControls { /// <summary> /// Specifies the culture information to use when string values are converted to types. /// </summary> public enum ParsingCulture { Invariant, Current, } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/WebControls/ParsingCulture.cs
C#
gpl-3.0
542
Version 3 of the EvePriceInfo twitch.tv chat bot. This IRC bot is written in Perl using the POE framework and MySQL database. Eve Online market data is gathered from the eve-central.com website. The user kill data is gathered from zkillboard.com website.
RJReed67/Evepriceinfo
README.md
Markdown
gpl-3.0
256
import { LOCATION_SUCCESS } from '../actions/location' // login reducer export default function location(state = null, action) { if (action.type == LOCATION_SUCCESS) { return action.response; } return state; }
caTUstrophy/frontend
reducers/location.js
JavaScript
gpl-3.0
221
#include "loadinfo.hpp" #include "esmreader.hpp" #include "esmwriter.hpp" #include "defs.hpp" namespace ESM { unsigned int DialInfo::sRecordId = REC_INFO; void DialInfo::load(ESMReader &esm) { mPrev = esm.getHNString("PNAM"); mNext = esm.getHNString("NNAM"); // Not present if deleted if (esm.isNextSub("DATA")) { esm.getHT(mData, 12); } if (!esm.hasMoreSubs()) return; // What follows is somewhat spaghetti-ish, but it's worth if for // an extra speedup. INFO is by far the most common record type. // subName is a reference to the original, so it changes whenever // a new sub name is read. esm.isEmptyOrGetName() will get the // next name for us, or return true if there are no more records. esm.getSubName(); const NAME &subName = esm.retSubName(); if (subName.val == REC_ONAM) { mActor = esm.getHString(); if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_RNAM) { mRace = esm.getHString(); if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_CNAM) { mClass = esm.getHString(); if (esm.isEmptyOrGetName()) return; } mFactionLess = false; if (subName.val == REC_FNAM) { mFaction = esm.getHString(); if (mFaction == "FFFF") mFactionLess = true; if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_ANAM) { mCell = esm.getHString(); if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_DNAM) { mPcFaction = esm.getHString(); if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_SNAM) { mSound = esm.getHString(); if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_NAME) { mResponse = esm.getHString(); if (esm.isEmptyOrGetName()) return; } while (subName.val == REC_SCVR) { SelectStruct ss; ss.mSelectRule = esm.getHString(); ss.mValue.read (esm, Variant::Format_Info); mSelects.push_back(ss); if (esm.isEmptyOrGetName()) return; } if (subName.val == REC_BNAM) { mResultScript = esm.getHString(); if (esm.isEmptyOrGetName()) return; } mQuestStatus = QS_None; if (subName.val == REC_QSTN) mQuestStatus = QS_Name; else if (subName.val == REC_QSTF) mQuestStatus = QS_Finished; else if (subName.val == REC_QSTR) mQuestStatus = QS_Restart; else if (subName.val == REC_DELE) mQuestStatus = QS_Deleted; else esm.fail( "Don't know what to do with " + subName.toString() + " in INFO " + mId); if (mQuestStatus != QS_None) // Skip rest of record esm.skipRecord(); } void DialInfo::save(ESMWriter &esm) const { esm.writeHNCString("PNAM", mPrev); esm.writeHNCString("NNAM", mNext); esm.writeHNT("DATA", mData, 12); esm.writeHNOCString("ONAM", mActor); esm.writeHNOCString("RNAM", mRace); esm.writeHNOCString("CNAM", mClass); esm.writeHNOCString("FNAM", mFaction); esm.writeHNOCString("ANAM", mCell); esm.writeHNOCString("DNAM", mPcFaction); esm.writeHNOCString("SNAM", mSound); esm.writeHNOString("NAME", mResponse); for (std::vector<SelectStruct>::const_iterator it = mSelects.begin(); it != mSelects.end(); ++it) { esm.writeHNString("SCVR", it->mSelectRule); it->mValue.write (esm, Variant::Format_Info); } esm.writeHNOString("BNAM", mResultScript); switch(mQuestStatus) { case QS_Name: esm.writeHNT("QSTN",'\1'); break; case QS_Finished: esm.writeHNT("QSTF", '\1'); break; case QS_Restart: esm.writeHNT("QSTR", '\1'); break; case QS_Deleted: esm.writeHNT("DELE", '\1'); break; default: break; } } void DialInfo::blank() { mData.mUnknown1 = 0; mData.mDisposition = 0; mData.mRank = 0; mData.mGender = 0; mData.mPCrank = 0; mData.mUnknown2 = 0; mSelects.clear(); mPrev.clear(); mNext.clear(); mActor.clear(); mRace.clear(); mClass.clear(); mFaction.clear(); mPcFaction.clear(); mCell.clear(); mSound.clear(); mResponse.clear(); mResultScript.clear(); mFactionLess = false; mQuestStatus = QS_None; } }
Demorde/openmw-android
components/esm/loadinfo.cpp
C++
gpl-3.0
4,593
/* This file is part of Clementine. Copyright 2010-2014, David Sansome <me@davidsansome.com> Copyright 2010-2012, 2014, John Maguire <john.maguire@gmail.com> Copyright 2011, 2014, Arnaud Bienner <arnaud.bienner@gmail.com> Copyright 2012, Alan Briolat <alan.briolat@gmail.com> Copyright 2012, Veniamin Gvozdikov <G.Veniamin@gmail.com> Copyright 2013-2014, Andreas <asfa194@gmail.com> Copyright 2013, Glad Olus <gladolus@gmx.com> Copyright 2013, graehl <graehl@gmail.com> Copyright 2014, vkrishtal <krishtalhost@gmail.com> Copyright 2014, Krzysztof Sobiecki <sobkas@gmail.com> Clementine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clementine 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 Clementine. If not, see <http://www.gnu.org/licenses/>. */ #include "utilities.h" #include <stdlib.h> #include <QApplication> #include <QDateTime> #include <QDesktopServices> #include <QDir> #include <QFile> #include <QIODevice> #include <QMetaEnum> #include <QMouseEvent> #include <QStringList> #include <QTcpServer> #include <QTemporaryFile> #include <QUrl> #include <QUrlQuery> #include <QWidget> #include <QXmlStreamReader> #include <QtDebug> #include <QtGlobal> #include <memory> #include "config.h" #include "core/application.h" #include "core/logging.h" #include "core/timeconstants.h" #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) #include <QRandomGenerator> #endif #if defined(Q_OS_UNIX) #include <sys/statvfs.h> #elif defined(Q_OS_WIN32) #include <windows.h> #include <QProcess> #endif #ifdef Q_OS_LINUX #include <sys/syscall.h> #include <unistd.h> #endif #ifdef Q_OS_DARWIN #include <sys/resource.h> #endif #ifdef Q_OS_DARWIN #include <QProcess> #include "CoreServices/CoreServices.h" #include "IOKit/ps/IOPSKeys.h" #include "IOKit/ps/IOPowerSources.h" #include "core/mac_startup.h" #include "core/mac_utilities.h" #include "core/scoped_cftyperef.h" #endif namespace Utilities { static QString tr(const char* str) { return QCoreApplication::translate("", str); } QString PrettyTimeDelta(int seconds) { return (seconds >= 0 ? "+" : "-") + PrettyTime(seconds); } QString PrettyTime(int seconds, bool always_show_hours) { // last.fm sometimes gets the track length wrong, so you end up with // negative times. seconds = qAbs(seconds); int hours = seconds / (60 * 60); int minutes = (seconds / 60) % 60; seconds %= 60; QString ret; if (hours || always_show_hours) ret = QString::asprintf("%d:%02d:%02d", hours, minutes, seconds); // NOLINT(runtime/printf) else ret = QString::asprintf("%d:%02d", minutes, seconds); // NOLINT(runtime/printf) return ret; } QString PrettyTimeNanosec(qint64 nanoseconds, bool always_show_hours) { return PrettyTime(nanoseconds / kNsecPerSec, always_show_hours); } QString WordyTime(quint64 seconds) { quint64 days = seconds / (kSecsPerDay); quint64 remaining_hours = (seconds - days * kSecsPerDay) / (60 * 60); // TODO(David Sansome): Make the plural rules translatable QStringList parts; if (days) parts << (days == 1 ? tr("1 day") : tr("%1 days").arg(days)); // Since PrettyTime does not return the hour if it is 0, we need to add it // explicitly for durations longer than 1 day. parts << (days && !remaining_hours ? QString("0:") : QString()) + PrettyTime(seconds - days * kSecsPerDay); return parts.join(" "); } QString WordyTimeNanosec(qint64 nanoseconds) { return WordyTime(nanoseconds / kNsecPerSec); } QString Ago(int seconds_since_epoch, const QLocale& locale) { const QDateTime now = QDateTime::currentDateTime(); const QDateTime then = QDateTime::fromTime_t(seconds_since_epoch); const int days_ago = then.date().daysTo(now.date()); const QString time = then.time().toString(locale.timeFormat(QLocale::ShortFormat)); if (days_ago == 0) return tr("Today") + " " + time; if (days_ago == 1) return tr("Yesterday") + " " + time; if (days_ago <= 7) return tr("%1 days ago").arg(days_ago); return then.date().toString(locale.dateFormat(QLocale::ShortFormat)); } QString PrettyFutureDate(const QDate& date) { const QDate now = QDate::currentDate(); const int delta_days = now.daysTo(date); if (delta_days < 0) return QString(); if (delta_days == 0) return tr("Today"); if (delta_days == 1) return tr("Tomorrow"); if (delta_days <= 7) return tr("In %1 days").arg(delta_days); if (delta_days <= 14) return tr("Next week"); return tr("In %1 weeks").arg(delta_days / 7); } QString PrettySize(quint64 bytes) { QString ret; if (bytes > 0) { if (bytes <= 1000) ret = QString::number(bytes) + " bytes"; else if (bytes <= 1000 * 1000) ret = QString::asprintf( "%.1f KB", static_cast<float>(bytes) / 1000); // NOLINT(runtime/printf) else if (bytes <= 1000 * 1000 * 1000) ret = QString::asprintf( "%.1f MB", static_cast<float>(bytes) / (1000 * 1000)); // NOLINT(runtime/printf) else ret = QString::asprintf( "%.1f GB", static_cast<float>(bytes) / (1000 * 1000 * 1000)); // NOLINT(runtime/printf) } return ret; } quint64 FileSystemCapacity(const QString& path) { #if defined(Q_OS_UNIX) struct statvfs fs_info; if (statvfs(path.toLocal8Bit().constData(), &fs_info) == 0) return quint64(fs_info.f_blocks) * quint64(fs_info.f_bsize); #elif defined(Q_OS_WIN32) _ULARGE_INTEGER ret; if (GetDiskFreeSpaceEx( QDir::toNativeSeparators(path).toLocal8Bit().constData(), nullptr, &ret, nullptr) != 0) return ret.QuadPart; #endif return 0; } quint64 FileSystemFreeSpace(const QString& path) { #if defined(Q_OS_UNIX) struct statvfs fs_info; if (statvfs(path.toLocal8Bit().constData(), &fs_info) == 0) return quint64(fs_info.f_bavail) * quint64(fs_info.f_bsize); #elif defined(Q_OS_WIN32) _ULARGE_INTEGER ret; if (GetDiskFreeSpaceEx( QDir::toNativeSeparators(path).toLocal8Bit().constData(), &ret, nullptr, nullptr) != 0) return ret.QuadPart; #endif return 0; } QString MakeTempDir(const QString template_name) { QString path; { QTemporaryFile tempfile; if (!template_name.isEmpty()) tempfile.setFileTemplate(template_name); tempfile.open(); path = tempfile.fileName(); } QDir d; d.mkdir(path); return path; } QString GetTemporaryFileName() { QString file; { QTemporaryFile tempfile; // Do not delete the file, we want to do something with it tempfile.setAutoRemove(false); tempfile.open(); file = tempfile.fileName(); } return file; } QString SaveToTemporaryFile(const QByteArray& data) { QTemporaryFile tempfile; tempfile.setAutoRemove(false); if (!tempfile.open()) { return QString(); } if (tempfile.write(data) != data.size()) { tempfile.remove(); return QString(); } tempfile.close(); return tempfile.fileName(); } bool RemoveRecursive(const QString& path) { QDir dir(path); for (const QString& child : dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden)) { if (!RemoveRecursive(path + "/" + child)) return false; } for (const QString& child : dir.entryList(QDir::NoDotAndDotDot | QDir::Files | QDir::Hidden)) { if (!QFile::remove(path + "/" + child)) return false; } return dir.rmdir(path); } bool CopyRecursive(const QString& source, const QString& destination) { // Make the destination directory QString dir_name = source.section('/', -1, -1); QString dest_path = destination + "/" + dir_name; QDir().mkpath(dest_path); QDir dir(source); for (const QString& child : dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs)) { if (!CopyRecursive(source + "/" + child, dest_path)) { qLog(Warning) << "Failed to copy dir" << source + "/" + child << "to" << dest_path; return false; } } for (const QString& child : dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) { if (!QFile::copy(source + "/" + child, dest_path + "/" + child)) { qLog(Warning) << "Failed to copy file" << source + "/" + child << "to" << dest_path; return false; } } return true; } bool Copy(QIODevice* source, QIODevice* destination) { if (!source->open(QIODevice::ReadOnly)) return false; if (!destination->open(QIODevice::WriteOnly)) return false; const qint64 bytes = source->size(); std::unique_ptr<char[]> data(new char[bytes]); qint64 pos = 0; qint64 bytes_read; do { bytes_read = source->read(data.get() + pos, bytes - pos); if (bytes_read == -1) return false; pos += bytes_read; } while (bytes_read > 0 && pos != bytes); pos = 0; qint64 bytes_written; do { bytes_written = destination->write(data.get() + pos, bytes - pos); if (bytes_written == -1) return false; pos += bytes_written; } while (bytes_written > 0 && pos != bytes); return true; } QString ColorToRgba(const QColor& c) { return QString("rgba(%1, %2, %3, %4)") .arg(c.red()) .arg(c.green()) .arg(c.blue()) .arg(c.alpha()); } QString GetConfigPath(ConfigPath config) { switch (config) { case Path_Root: { if (Application::IsPortable()) { QDir d(QCoreApplication::applicationDirPath()); return d.filePath(Application::kPortableDataDir); } #ifdef Q_OS_DARWIN return mac::GetApplicationSupportPath() + "/" + QCoreApplication::organizationName(); #else return QString("%1/%2").arg( QStandardPaths::writableLocation(QStandardPaths::ConfigLocation), QCoreApplication::organizationName()); #endif } break; case Path_CacheRoot: { if (Application::kIsPortable) { return GetConfigPath(Path_Root) + "/cache"; } #if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN) return QString("%1/%2").arg(QStandardPaths::writableLocation( QStandardPaths::GenericCacheLocation), QCoreApplication::organizationName()); #else return GetConfigPath(Path_Root); #endif } break; case Path_Icons: return GetConfigPath(Path_Root) + "/customiconset"; case Path_AlbumCovers: return GetConfigPath(Path_Root) + "/albumcovers"; case Path_NetworkCache: return GetConfigPath(Path_CacheRoot) + "/networkcache"; case Path_MoodbarCache: return GetConfigPath(Path_CacheRoot) + "/moodbarcache"; case Path_PixmapCache: return GetConfigPath(Path_CacheRoot) + "/pixmapcache"; case Path_GstreamerRegistry: return GetConfigPath(Path_Root) + QString("/gst-registry-%1-bin") .arg(QCoreApplication::applicationVersion()); case Path_DefaultMusicLibrary: #ifdef Q_OS_DARWIN return mac::GetMusicDirectory(); #else return QDir::homePath(); #endif case Path_LocalSpotifyBlob: return GetConfigPath(Path_Root) + "/spotifyblob"; default: qFatal("%s", Q_FUNC_INFO); return QString(); } } #ifdef Q_OS_DARWIN // Better than openUrl(dirname(path)) - also highlights file at path void RevealFileInFinder(QString const& path) { QProcess::execute("/usr/bin/open", QStringList() << "-R" << path); } #endif // Q_OS_DARWIN #ifdef Q_OS_WIN void ShowFileInExplorer(QString const& path) { QProcess::execute("explorer.exe", QStringList() << "/select," << QDir::toNativeSeparators(path)); } #endif void OpenInFileBrowser(const QList<QUrl>& urls) { QSet<QString> dirs; for (const QUrl& url : urls) { if (url.scheme() != "file") { continue; } QString path = url.toLocalFile(); if (!QFile::exists(path)) continue; const QString directory = QFileInfo(path).dir().path(); if (dirs.contains(directory)) continue; dirs.insert(directory); qLog(Debug) << path; #ifdef Q_OS_DARWIN // revealing multiple files in the finder only opens one window, // so it also makes sense to reveal at most one per directory RevealFileInFinder(path); #elif defined(Q_OS_WIN32) ShowFileInExplorer(path); #else QDesktopServices::openUrl(QUrl::fromLocalFile(directory)); #endif } } QByteArray Hmac(const QByteArray& key, const QByteArray& data, HashFunction method) { const int kBlockSize = 64; // bytes Q_ASSERT(key.length() <= kBlockSize); QByteArray inner_padding(kBlockSize, static_cast<char>(0x36)); QByteArray outer_padding(kBlockSize, static_cast<char>(0x5c)); for (int i = 0; i < key.length(); ++i) { inner_padding[i] = inner_padding[i] ^ key[i]; outer_padding[i] = outer_padding[i] ^ key[i]; } if (Md5_Algo == method) { return QCryptographicHash::hash( outer_padding + QCryptographicHash::hash(inner_padding + data, QCryptographicHash::Md5), QCryptographicHash::Md5); } else if (Sha1_Algo == method) { return QCryptographicHash::hash( outer_padding + QCryptographicHash::hash(inner_padding + data, QCryptographicHash::Sha1), QCryptographicHash::Sha1); } else { // Sha256_Algo, currently default return QCryptographicHash::hash( outer_padding + QCryptographicHash::hash(inner_padding + data, QCryptographicHash::Sha256), QCryptographicHash::Sha256); } } QByteArray HmacSha256(const QByteArray& key, const QByteArray& data) { return Hmac(key, data, Sha256_Algo); } QByteArray HmacMd5(const QByteArray& key, const QByteArray& data) { return Hmac(key, data, Md5_Algo); } QByteArray HmacSha1(const QByteArray& key, const QByteArray& data) { return Hmac(key, data, Sha1_Algo); } // File must not be open and will be closed afterwards! QByteArray Sha1File(QFile& file) { file.open(QIODevice::ReadOnly); QCryptographicHash hash(QCryptographicHash::Sha1); QByteArray data; while (!file.atEnd()) { data = file.read(1000000); // 1 mib hash.addData(data.data(), data.length()); data.clear(); } file.close(); return hash.result(); } QByteArray Sha1CoverHash(const QString& artist, const QString& album) { QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(artist.toLower().toUtf8().constData()); hash.addData(album.toLower().toUtf8().constData()); return hash.result(); } QString PrettySize(const QSize& size) { return QString::number(size.width()) + "x" + QString::number(size.height()); } void ForwardMouseEvent(const QMouseEvent* e, QWidget* target) { QMouseEvent c(e->type(), target->mapFromGlobal(e->globalPos()), e->globalPos(), e->button(), e->buttons(), e->modifiers()); QApplication::sendEvent(target, &c); } bool IsMouseEventInWidget(const QMouseEvent* e, const QWidget* widget) { return widget->rect().contains(widget->mapFromGlobal(e->globalPos())); } quint16 PickUnusedPort() { forever { #if (QT_VERSION < QT_VERSION_CHECK(5, 10, 0)) const quint16 port = 49152 + qrand() % 16384; #else const quint16 port = QRandomGenerator::global()->bounded(49152, 65536); #endif QTcpServer server; if (server.listen(QHostAddress::Any, port)) { return port; } } } void ConsumeCurrentElement(QXmlStreamReader* reader) { int level = 1; while (level != 0 && !reader->atEnd()) { switch (reader->readNext()) { case QXmlStreamReader::StartElement: ++level; break; case QXmlStreamReader::EndElement: --level; break; default: break; } } } bool ParseUntilElement(QXmlStreamReader* reader, const QString& name) { while (!reader->atEnd()) { QXmlStreamReader::TokenType type = reader->readNext(); switch (type) { case QXmlStreamReader::StartElement: if (reader->name() == name) { return true; } break; default: break; } } return false; } QDateTime ParseRFC822DateTime(const QString& text) { QRegExp regexp( "(\\d{1,2}) (\\w{3,12}) (\\d+) (\\d{1,2}):(\\d{1,2}):(\\d{1,2})"); if (regexp.indexIn(text) == -1) { return QDateTime(); } enum class MatchNames { DAYS = 1, MONTHS, YEARS, HOURS, MINUTES, SECONDS }; QMap<QString, int> monthmap; monthmap["Jan"] = 1; monthmap["Feb"] = 2; monthmap["Mar"] = 3; monthmap["Apr"] = 4; monthmap["May"] = 5; monthmap["Jun"] = 6; monthmap["Jul"] = 7; monthmap["Aug"] = 8; monthmap["Sep"] = 9; monthmap["Oct"] = 10; monthmap["Nov"] = 11; monthmap["Dec"] = 12; monthmap["January"] = 1; monthmap["February"] = 2; monthmap["March"] = 3; monthmap["April"] = 4; monthmap["May"] = 5; monthmap["June"] = 6; monthmap["July"] = 7; monthmap["August"] = 8; monthmap["September"] = 9; monthmap["October"] = 10; monthmap["November"] = 11; monthmap["December"] = 12; const QDate date(regexp.cap(static_cast<int>(MatchNames::YEARS)).toInt(), monthmap[regexp.cap(static_cast<int>(MatchNames::MONTHS))], regexp.cap(static_cast<int>(MatchNames::DAYS)).toInt()); const QTime time(regexp.cap(static_cast<int>(MatchNames::HOURS)).toInt(), regexp.cap(static_cast<int>(MatchNames::MINUTES)).toInt(), regexp.cap(static_cast<int>(MatchNames::SECONDS)).toInt()); return QDateTime(date, time); } const char* EnumToString(const QMetaObject& meta, const char* name, int value) { int index = meta.indexOfEnumerator(name); if (index == -1) return "[UnknownEnum]"; QMetaEnum metaenum = meta.enumerator(index); const char* result = metaenum.valueToKey(value); if (result == 0) return "[UnknownEnumValue]"; return result; } QStringList Prepend(const QString& text, const QStringList& list) { QStringList ret(list); for (int i = 0; i < ret.count(); ++i) ret[i].prepend(text); return ret; } QStringList Updateify(const QStringList& list) { QStringList ret(list); for (int i = 0; i < ret.count(); ++i) ret[i].prepend(ret[i] + " = :"); return ret; } QString DecodeHtmlEntities(const QString& text) { QString copy(text); copy.replace("&amp;", "&"); copy.replace("&quot;", "\""); copy.replace("&apos;", "'"); copy.replace("&lt;", "<"); copy.replace("&gt;", ">"); return copy; } int SetThreadIOPriority(IoPriority priority) { #ifdef Q_OS_LINUX return syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, GetThreadId(), 4 | priority << IOPRIO_CLASS_SHIFT); #elif defined(Q_OS_DARWIN) return setpriority(PRIO_DARWIN_THREAD, 0, priority == IOPRIO_CLASS_IDLE ? PRIO_DARWIN_BG : 0); #else return 0; #endif } int GetThreadId() { #ifdef Q_OS_LINUX return syscall(SYS_gettid); #else return 0; #endif } bool IsLaptop() { #ifdef Q_OS_WIN SYSTEM_POWER_STATUS status; if (!GetSystemPowerStatus(&status)) { return false; } return !(status.BatteryFlag & 128); // 128 = no system battery #elif defined(Q_OS_LINUX) return !QDir("/proc/acpi/battery") .entryList(QDir::Dirs | QDir::NoDotAndDotDot) .isEmpty(); #elif defined(Q_OS_MAC) ScopedCFTypeRef<CFTypeRef> power_sources(IOPSCopyPowerSourcesInfo()); ScopedCFTypeRef<CFArrayRef> power_source_list( IOPSCopyPowerSourcesList(power_sources.get())); for (CFIndex i = 0; i < CFArrayGetCount(power_source_list.get()); ++i) { CFTypeRef ps = CFArrayGetValueAtIndex(power_source_list.get(), i); CFDictionaryRef description = IOPSGetPowerSourceDescription(power_sources.get(), ps); if (CFDictionaryContainsKey(description, CFSTR(kIOPSBatteryHealthKey))) { return true; } } return false; #else return false; #endif } QString SystemLanguageName() { QString system_language = QLocale::system().uiLanguages().empty() ? QLocale::system().name() : QLocale::system().uiLanguages().first(); // uiLanguages returns strings with "-" as separators for language/region; // however QTranslator needs "_" separators system_language.replace("-", "_"); return system_language; } bool UrlOnSameDriveAsClementine(const QUrl& url) { if (url.scheme() != "file") return false; #ifdef Q_OS_WIN QUrl appUrl = QUrl::fromLocalFile(QCoreApplication::applicationDirPath()); if (url.toLocalFile().left(1) == appUrl.toLocalFile().left(1)) return true; else return false; #else // Non windows systems have always a / in the path return true; #endif } QUrl GetRelativePathToClementineBin(const QUrl& url) { QString relPath = GetRelativePathToClementineBin(url.toLocalFile()); QUrl rel_url = QUrl::fromLocalFile(relPath); // QUrl considers a URL relative if the schema is omitted. rel_url.setScheme(QString()); return rel_url; } QString GetRelativePathToClementineBin(const QString& abspath) { QDir appPath(QCoreApplication::applicationDirPath()); return appPath.relativeFilePath(abspath); } QString PathWithoutFilenameExtension(const QString& filename) { if (filename.section('/', -1, -1).contains('.')) return filename.section('.', 0, -2); return filename; } QString FiddleFileExtension(const QString& filename, const QString& new_extension) { return PathWithoutFilenameExtension(filename) + "." + new_extension; } QByteArray GetUriForGstreamer(const QUrl& url) { if (url.scheme() == "file") { QString local_file = url.toLocalFile(); if (local_file.indexOf("//") == 0) { // Exclude / from encoding. return QByteArray("file://") + QUrl::toPercentEncoding(local_file, "/"); } } return url.toEncoded(); } QString ScrubUrlQueries(const QString& str) { // If the URL isn't followed by whitespace, this will eat extra characters. QRegExp rx("((?:http|https)://\\S*\\?)\\S*"); // QString::replace is non const, so operate on a copy. return QString(str).replace(rx, "\\1 (query removed)"); } QString MakeBugReportUrl(const QString& title) { // Example: // https://github.com/clementine-player/Clementine/issues/new?title=New%20bug QUrl url("https://github.com/clementine-player/Clementine/issues/new"); QUrlQuery query; query.addQueryItem("title", title); url.setQuery(query); return url.toString(QUrl::FullyEncoded); } } // namespace Utilities ScopedWCharArray::ScopedWCharArray(const QString& str) : chars_(str.length()), data_(new wchar_t[chars_ + 1]) { str.toWCharArray(data_.get()); data_[chars_] = '\0'; }
clementine-player/Clementine
src/core/utilities.cpp
C++
gpl-3.0
23,020
/* * Copyright (C) 2012 Tim Vaughan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package multitypetree.operators; import beast.core.Description; import beast.core.Input; import beast.core.Input.Validate; import beast.core.Operator; import beast.evolution.tree.MigrationModel; import beast.evolution.tree.MultiTypeNode; import beast.evolution.tree.MultiTypeTree; import beast.evolution.tree.Node; import beast.evolution.tree.Tree; /** * Abstract base class for all operators on ColouredTree objects. * * @author Tim Vaughan */ @Description("This operator generates proposals for a coloured beast tree.") public abstract class MultiTypeTreeOperator extends Operator { public Input<MultiTypeTree> multiTypeTreeInput = new Input<>( "multiTypeTree", "Multi-type tree on which to operate.", Validate.REQUIRED); public Input<MigrationModel> migrationModelInput = new Input<>( "migrationModel", "Migration model for proposal distribution", Input.Validate.REQUIRED); protected MultiTypeTree mtTree; protected MigrationModel migModel; @Override public void initAndValidate() throws Exception { mtTree = multiTypeTreeInput.get(); migModel = migrationModelInput.get(); } /* *********************************************************************** * The following two methods are copied verbatim from TreeOperator. */ /** * Obtain the sister of node "child" having parent "parent". * * @param parent the parent * @param child the child that you want the sister of * @return the other child of the given parent. */ protected Node getOtherChild(Node parent, Node child) { if (parent.getLeft().getNr() == child.getNr()) { return parent.getRight(); } else { return parent.getLeft(); } } /** * Replace node "child" with another node. * * @param node * @param child * @param replacement */ public void replace(Node node, Node child, Node replacement) { node.removeChild(child); node.addChild(replacement); node.makeDirty(Tree.IS_FILTHY); replacement.makeDirty(Tree.IS_FILTHY); } /* **********************************************************************/ /** * Disconnect edge <node,node.getParent()> by joining node's sister directly * to node's grandmother and adding all colour changes previously on * <node.getParent(),node.getParent().getParent()> to the new branch. * * @param node */ public void disconnectBranch(Node node) { // Check argument validity: Node parent = node.getParent(); if (node.isRoot() || parent.isRoot()) throw new IllegalArgumentException("Illegal argument to " + "disconnectBranch()."); Node sister = getOtherChild(parent, node); // Add colour changes originally attached to parent to those attached // to node's sister: for (int idx = 0; idx < ((MultiTypeNode)parent).getChangeCount(); idx++) { int colour = ((MultiTypeNode)parent).getChangeType(idx); double time = ((MultiTypeNode)parent).getChangeTime(idx); ((MultiTypeNode)sister).addChange(colour, time); } // Implement topology change. replace(parent.getParent(), parent, sister); // Clear colour changes from parent: ((MultiTypeNode)parent).clearChanges(); // Ensure BEAST knows to update affected likelihoods: parent.makeDirty(Tree.IS_FILTHY); sister.makeDirty(Tree.IS_FILTHY); node.makeDirty(Tree.IS_FILTHY); } /** * Disconnect node from root, discarding all colouring on <node,root> and * <node's sister,root>. * * @param node */ public void disconnectBranchFromRoot(Node node) { // Check argument validity: if (node.isRoot() || !node.getParent().isRoot()) throw new IllegalArgumentException("Illegal argument to" + " disconnectBranchFromRoot()."); // Implement topology change: Node parent = node.getParent(); Node sister = getOtherChild(parent, node); sister.setParent(null); parent.removeChild(sister); // Clear colour changes on new root: ((MultiTypeNode)sister).clearChanges(); // Ensure BEAST knows to update affected likelihoods: parent.makeDirty(Tree.IS_FILTHY); sister.makeDirty(Tree.IS_FILTHY); node.makeDirty(Tree.IS_FILTHY); } /** * Creates a new branch between node and a new node at time destTime between * destBranchBase and its parent. Colour changes are divided between the two * new branches created by the split. * * @param node * @param destBranchBase * @param destTime */ public void connectBranch(Node node, Node destBranchBase, double destTime) { // Check argument validity: if (node.isRoot() || destBranchBase.isRoot()) throw new IllegalArgumentException("Illegal argument to " + "connectBranch()."); // Obtain existing parent of node and set new time: Node parent = node.getParent(); parent.setHeight(destTime); MultiTypeNode mtParent = (MultiTypeNode)parent; MultiTypeNode mtDestBranchBase = (MultiTypeNode)destBranchBase; // Determine where the split comes in the list of colour changes // attached to destBranchBase: int split; for (split = 0; split < mtDestBranchBase.getChangeCount(); split++) if (mtDestBranchBase.getChangeTime(split) > destTime) break; // Divide colour changes between new branches: mtParent.clearChanges(); for (int idx = split; idx < mtDestBranchBase.getChangeCount(); idx++) mtParent.addChange(mtDestBranchBase.getChangeType(idx), mtDestBranchBase.getChangeTime(idx)); mtDestBranchBase.truncateChanges(split); // Set colour at split: mtParent.setNodeType(mtDestBranchBase.getFinalType()); // Implement topology changes: replace(destBranchBase.getParent(), destBranchBase, parent); destBranchBase.setParent(parent); if (parent.getLeft() == node) parent.setRight(destBranchBase); else if (parent.getRight() == node) parent.setLeft(destBranchBase); // Ensure BEAST knows to update affected likelihoods: node.makeDirty(Tree.IS_FILTHY); parent.makeDirty(Tree.IS_FILTHY); destBranchBase.makeDirty(Tree.IS_FILTHY); } /** * Set up node's parent as the new root with a height of destTime, with * oldRoot as node's new sister. * * @param node * @param oldRoot * @param destTime */ public void connectBranchToRoot(Node node, Node oldRoot, double destTime) { // Check argument validity: if (node.isRoot() || !oldRoot.isRoot()) throw new IllegalArgumentException("Illegal argument " + "to connectBranchToRoot()."); // Obtain existing parent of node and set new time: Node newRoot = node.getParent(); newRoot.setHeight(destTime); // Implement topology changes: newRoot.setParent(null); if (newRoot.getLeft() == node) newRoot.setRight(oldRoot); else if (newRoot.getRight() == node) newRoot.setLeft(oldRoot); oldRoot.setParent(newRoot); // Ensure BEAST knows to recalculate affected likelihood: newRoot.makeDirty(Tree.IS_FILTHY); oldRoot.makeDirty(Tree.IS_FILTHY); node.makeDirty(Tree.IS_FILTHY); } }
aand065/MultiTypeTree
src/multitypetree/operators/MultiTypeTreeOperator.java
Java
gpl-3.0
8,471
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the qmake application of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef OPTION_H #define OPTION_H #include <qmakeglobals.h> #include <qmakevfs.h> #include <qmakeparser.h> #include <qmakeevaluator.h> #include <qstring.h> #include <qstringlist.h> #include <qfile.h> QT_BEGIN_NAMESPACE #define QMAKE_VERSION_STR "3.1" QString qmake_getpwd(); bool qmake_setpwd(const QString &p); #define debug_msg if(Option::debug_level) debug_msg_internal void debug_msg_internal(int level, const char *fmt, ...); //don't call directly, use debug_msg enum QMakeWarn { WarnNone = 0x00, WarnParser = 0x01, WarnLogic = 0x02, WarnDeprecated = 0x04, WarnAll = 0xFF }; void warn_msg(QMakeWarn t, const char *fmt, ...); class QMakeProject; class EvalHandler : public QMakeHandler { public: void message(int type, const QString &msg, const QString &fileName, int lineNo); void fileMessage(int type, const QString &msg); void aboutToEval(ProFile *, ProFile *, EvalFileType); void doneWithEval(ProFile *); }; struct Option { static EvalHandler evalHandler; static QMakeGlobals *globals; static ProFileCache *proFileCache; static QMakeVfs *vfs; static QMakeParser *parser; //simply global convenience static QString libtool_ext; static QString pkgcfg_ext; static QString prf_ext; static QString prl_ext; static QString ui_ext; static QStringList h_ext; static QStringList cpp_ext; static QStringList c_ext; static QString objc_ext; static QString objcpp_ext; static QString cpp_moc_ext; static QString obj_ext; static QString lex_ext; static QString yacc_ext; static QString h_moc_mod; static QString lex_mod; static QString yacc_mod; static QString dir_sep; static QString pro_ext; static QString res_ext; static char field_sep; enum CmdLineFlags { QMAKE_CMDLINE_SUCCESS = 0x00, QMAKE_CMDLINE_SHOW_USAGE = 0x01, QMAKE_CMDLINE_BAIL = 0x02, QMAKE_CMDLINE_ERROR = 0x04 }; //both of these must be called.. static int init(int argc=0, char **argv=0); //parse cmdline static void prepareProject(const QString &pfile); static bool postProcessProject(QMakeProject *); enum StringFixFlags { FixNone = 0x00, FixEnvVars = 0x01, FixPathCanonicalize = 0x02, FixPathToLocalSeparators = 0x04, FixPathToTargetSeparators = 0x08, FixPathToNormalSeparators = 0x10 }; static QString fixString(QString string, uchar flags); //and convenience functions inline static QString fixPathToLocalOS(const QString &in, bool fix_env=true, bool canonical=true) { uchar flags = FixPathToLocalSeparators; if(fix_env) flags |= FixEnvVars; if(canonical) flags |= FixPathCanonicalize; return fixString(in, flags); } inline static QString fixPathToTargetOS(const QString &in, bool fix_env=true, bool canonical=true) { uchar flags = FixPathToTargetSeparators; if(fix_env) flags |= FixEnvVars; if(canonical) flags |= FixPathCanonicalize; return fixString(in, flags); } inline static QString normalizePath(const QString &in, bool fix_env=true, bool canonical=true) { uchar flags = FixPathToNormalSeparators; if (fix_env) flags |= FixEnvVars; if (canonical) flags |= FixPathCanonicalize; return fixString(in, flags); } inline static bool hasFileExtension(const QString &str, const QStringList &extensions) { for (const QString &ext : extensions) if (str.endsWith(ext)) return true; return false; } //global qmake mode, can only be in one mode per invocation! enum QMAKE_MODE { QMAKE_GENERATE_NOTHING, QMAKE_GENERATE_PROJECT, QMAKE_GENERATE_MAKEFILE, QMAKE_GENERATE_PRL, QMAKE_SET_PROPERTY, QMAKE_UNSET_PROPERTY, QMAKE_QUERY_PROPERTY }; static QMAKE_MODE qmake_mode; //all modes static QFile output; static QString output_dir; static int debug_level; static int warn_level; static bool recursive; //QMAKE_*_PROPERTY options struct prop { static QStringList properties; }; //QMAKE_GENERATE_PROJECT options struct projfile { static bool do_pwd; static QStringList project_dirs; }; //QMAKE_GENERATE_MAKEFILE options struct mkfile { static bool do_deps; static bool do_mocs; static bool do_dep_heuristics; static bool do_preprocess; static bool do_stub_makefile; static int cachefile_depth; static QStringList project_files; }; private: static int parseCommandLine(QStringList &args, QMakeCmdLineParserState &state); }; inline QString fixEnvVariables(const QString &x) { return Option::fixString(x, Option::FixEnvVars); } inline QStringList splitPathList(const QString &paths) { return paths.isEmpty() ? QStringList() : paths.split(Option::globals->dirlist_sep); } QT_END_NAMESPACE #endif // OPTION_H
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtbase/qmake/option.h
C
gpl-3.0
6,461
// ****************************************************************************** // Filename: SoundEffectsEnum.h // Project: Vox // Author: Steven Ball // // Purpose: // An enum list of all of the sound effects in the game. // // Revision History: // Initial Revision - 13/06/16 // // Copyright (c) 2005-2016, Steven Ball // ****************************************************************************** #pragma once enum eSoundEffect { eSoundEffect_None = 0, eSoundEffect_FootStep01, eSoundEffect_FootStep02, eSoundEffect_FootStep03, eSoundEffect_FootStep04, eSoundEffect_JumpLand, eSoundEffect_EquipCloth, eSoundEffect_EquipSword, eSoundEffect_EquipMove, eSoundEffect_ChestOpen, eSoundEffect_BowDraw, eSoundEffect_ArrowRelease, eSoundEffect_FireballCast, eSoundEffect_MimicJump, eSoundEffect_MimicDie, eSoundEffect_NUM, }; extern string g_soundEffectFilenames[eSoundEffect_NUM];
AlwaysGeeky/Vox
source/AudioManager/SoundEffectsEnum.h
C
gpl-3.0
923
-- mods/default/nodes.lua --[[ Node name convention: Although many node names are in combined-word form, the required form for new node names is words separated by underscores. If both forms are used in written language (for example pinewood and pine wood) the underscore form should be used. --]] --[[ Index: Stone ----- (1. Material 2. Cobble variant 3. Brick variant 4. Modified forms) default:stone default:cobble default:stonebrick default:stone_block default:mossycobble default:desert_stone default:desert_cobble default:desert_stonebrick default:desert_stone_block default:sandstone default:sandstonebrick default:sandstone_block default:desert_sandstone default:desert_sandstone_brick default:desert_sandstone_block default:silver_sandstone default:silver_sandstone_brick default:silver_sandstone_block default:obsidian default:obsidianbrick default:obsidian_block Soft / Non-Stone ---------------- (1. Material 2. Modified forms) default:dirt default:dirt_with_grass default:dirt_with_grass_footsteps default:dirt_with_dry_grass default:dirt_with_snow default:dirt_with_rainforest_litter default:sand default:desert_sand default:silver_sand default:gravel default:clay default:snow default:snowblock default:ice Trees ----- (1. Trunk 2. Fabricated trunk 3. Leaves 4. Sapling 5. Fruits) default:tree default:wood default:leaves default:sapling default:apple default:jungletree default:junglewood default:jungleleaves default:junglesapling default:pine_tree default:pine_wood default:pine_needles default:pine_sapling default:acacia_tree default:acacia_wood default:acacia_leaves default:acacia_sapling default:aspen_tree default:aspen_wood default:aspen_leaves default:aspen_sapling Ores ---- (1. In stone 2. Blocks) default:stone_with_coal default:coalblock default:stone_with_iron default:steelblock default:stone_with_copper default:copperblock default:stone_with_tin default:tinblock default:bronzeblock default:stone_with_gold default:goldblock default:stone_with_mese default:mese default:stone_with_diamond default:diamondblock Plantlife --------- default:cactus default:papyrus default:dry_shrub default:junglegrass default:grass_1 default:grass_2 default:grass_3 default:grass_4 default:grass_5 default:dry_grass_1 default:dry_grass_2 default:dry_grass_3 default:dry_grass_4 default:dry_grass_5 default:bush_stem default:bush_leaves default:bush_sapling default:acacia_bush_stem default:acacia_bush_leaves default:acacia_bush_sapling Corals ------ default:coral_brown default:coral_orange default:coral_skeleton Liquids ------- (1. Source 2. Flowing) default:water_source default:water_flowing default:river_water_source default:river_water_flowing default:lava_source default:lava_flowing Tools / "Advanced" crafting / Non-"natural" ------------------------------------------- default:chest default:chest_locked default:bookshelf default:sign_wall_wood default:sign_wall_steel default:ladder_wood default:ladder_steel default:fence_wood default:fence_acacia_wood default:fence_junglewood default:fence_pine_wood default:fence_aspen_wood default:glass default:obsidian_glass default:brick default:meselamp default:mese_post_light Misc ---- default:cloud --]] -- -- Stone -- minetest.register_node("default:stone", { description = "Stone", tiles = {"default_stone.png"}, groups = {cracky = 3, stone = 1}, drop = 'default:cobble', legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:cobble", { description = "Cobblestone", tiles = {"default_cobble.png"}, is_ground_content = false, groups = {cracky = 3, stone = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stonebrick", { description = "Stone Brick", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_stone_brick.png"}, is_ground_content = false, groups = {cracky = 2, stone = 1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_block", { description = "Stone Block", tiles = {"default_stone_block.png"}, is_ground_content = false, groups = {cracky = 2, stone = 1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:mossycobble", { description = "Mossy Cobblestone", tiles = {"default_mossycobble.png"}, is_ground_content = false, groups = {cracky = 3, stone = 1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stone", { description = "Desert Stone", tiles = {"default_desert_stone.png"}, groups = {cracky = 3, stone = 1}, drop = 'default:desert_cobble', legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_cobble", { description = "Desert Cobblestone", tiles = {"default_desert_cobble.png"}, is_ground_content = false, groups = {cracky = 3, stone = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stonebrick", { description = "Desert Stone Brick", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_desert_stone_brick.png"}, is_ground_content = false, groups = {cracky = 2, stone = 1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stone_block", { description = "Desert Stone Block", tiles = {"default_desert_stone_block.png"}, is_ground_content = false, groups = {cracky = 2, stone = 1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:sandstone", { description = "Sandstone", tiles = {"default_sandstone.png"}, groups = {crumbly = 1, cracky = 3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:sandstonebrick", { description = "Sandstone Brick", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_sandstone_brick.png"}, is_ground_content = false, groups = {cracky = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:sandstone_block", { description = "Sandstone Block", tiles = {"default_sandstone_block.png"}, is_ground_content = false, groups = {cracky = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_sandstone", { description = "Desert Sandstone", tiles = {"default_desert_sandstone.png"}, groups = {crumbly = 1, cracky = 3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_sandstone_brick", { description = "Desert Sandstone Brick", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_desert_sandstone_brick.png"}, is_ground_content = false, groups = {cracky = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_sandstone_block", { description = "Desert Sandstone Block", tiles = {"default_desert_sandstone_block.png"}, is_ground_content = false, groups = {cracky = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:silver_sandstone", { description = "Silver Sandstone", tiles = {"default_silver_sandstone.png"}, groups = {crumbly = 1, cracky = 3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:silver_sandstone_brick", { description = "Silver Sandstone Brick", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_silver_sandstone_brick.png"}, is_ground_content = false, groups = {cracky = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:silver_sandstone_block", { description = "Silver Sandstone Block", tiles = {"default_silver_sandstone_block.png"}, is_ground_content = false, groups = {cracky = 2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:obsidian", { description = "Obsidian", tiles = {"default_obsidian.png"}, sounds = default.node_sound_stone_defaults(), groups = {cracky = 1, level = 2}, }) minetest.register_node("default:obsidianbrick", { description = "Obsidian Brick", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_obsidian_brick.png"}, is_ground_content = false, sounds = default.node_sound_stone_defaults(), groups = {cracky = 1, level = 2}, }) minetest.register_node("default:obsidian_block", { description = "Obsidian Block", tiles = {"default_obsidian_block.png"}, is_ground_content = false, sounds = default.node_sound_stone_defaults(), groups = {cracky = 1, level = 2}, }) -- -- Soft / Non-Stone -- minetest.register_node("default:dirt", { description = "Dirt", tiles = {"default_dirt.png"}, groups = {crumbly = 3, soil = 1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("default:dirt_with_grass", { description = "Dirt with Grass", tiles = {"default_grass.png", "default_dirt.png", {name = "default_dirt.png^default_grass_side.png", tileable_vertical = false}}, groups = {crumbly = 3, soil = 1, spreading_dirt_type = 1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_grass_footstep", gain = 0.25}, }), }) minetest.register_node("default:dirt_with_grass_footsteps", { description = "Dirt with Grass and Footsteps", tiles = {"default_grass.png^default_footprint.png", "default_dirt.png", {name = "default_dirt.png^default_grass_side.png", tileable_vertical = false}}, groups = {crumbly = 3, soil = 1, not_in_creative_inventory = 1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_grass_footstep", gain = 0.25}, }), }) minetest.register_node("default:dirt_with_dry_grass", { description = "Dirt with Dry Grass", tiles = {"default_dry_grass.png", "default_dirt.png", {name = "default_dirt.png^default_dry_grass_side.png", tileable_vertical = false}}, groups = {crumbly = 3, soil = 1, spreading_dirt_type = 1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_grass_footstep", gain = 0.4}, }), }) minetest.register_node("default:dirt_with_snow", { description = "Dirt with Snow", tiles = {"default_snow.png", "default_dirt.png", {name = "default_dirt.png^default_snow_side.png", tileable_vertical = false}}, groups = {crumbly = 3, spreading_dirt_type = 1, snowy = 1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_snow_footstep", gain = 0.15}, }), }) minetest.register_node("default:dirt_with_rainforest_litter", { description = "Dirt with Rainforest Litter", tiles = { "default_rainforest_litter.png", "default_dirt.png", {name = "default_dirt.png^default_rainforest_litter_side.png", tileable_vertical = false} }, groups = {crumbly = 3, soil = 1, spreading_dirt_type = 1}, drop = "default:dirt", sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_grass_footstep", gain = 0.4}, }), }) minetest.register_node("default:sand", { description = "Sand", tiles = {"default_sand.png"}, groups = {crumbly = 3, falling_node = 1, sand = 1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:desert_sand", { description = "Desert Sand", tiles = {"default_desert_sand.png"}, groups = {crumbly = 3, falling_node = 1, sand = 1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:silver_sand", { description = "Silver Sand", tiles = {"default_silver_sand.png"}, groups = {crumbly = 3, falling_node = 1, sand = 1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:gravel", { description = "Gravel", tiles = {"default_gravel.png"}, groups = {crumbly = 2, falling_node = 1}, sounds = default.node_sound_gravel_defaults(), drop = { max_items = 1, items = { {items = {'default:flint'}, rarity = 16}, {items = {'default:gravel'}} } } }) minetest.register_node("default:clay", { description = "Clay", tiles = {"default_clay.png"}, groups = {crumbly = 3}, drop = 'default:clay_lump 4', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("default:snow", { description = "Snow", tiles = {"default_snow.png"}, inventory_image = "default_snowball.png", wield_image = "default_snowball.png", paramtype = "light", buildable_to = true, floodable = true, drawtype = "nodebox", node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}, }, }, groups = {crumbly = 3, falling_node = 1, puts_out_fire = 1, snowy = 1}, sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_snow_footstep", gain = 0.15}, dug = {name = "default_snow_footstep", gain = 0.2}, dig = {name = "default_snow_footstep", gain = 0.2} }), on_construct = function(pos) pos.y = pos.y - 1 if minetest.get_node(pos).name == "default:dirt_with_grass" then minetest.set_node(pos, {name = "default:dirt_with_snow"}) end end, }) minetest.register_node("default:snowblock", { description = "Snow Block", tiles = {"default_snow.png"}, groups = {crumbly = 3, puts_out_fire = 1, cools_lava = 1, snowy = 1}, sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_snow_footstep", gain = 0.15}, dug = {name = "default_snow_footstep", gain = 0.2}, dig = {name = "default_snow_footstep", gain = 0.2} }), on_construct = function(pos) pos.y = pos.y - 1 if minetest.get_node(pos).name == "default:dirt_with_grass" then minetest.set_node(pos, {name = "default:dirt_with_snow"}) end end, }) minetest.register_node("default:ice", { description = "Ice", tiles = {"default_ice.png"}, is_ground_content = false, paramtype = "light", groups = {cracky = 3, puts_out_fire = 1, cools_lava = 1}, sounds = default.node_sound_glass_defaults(), }) -- -- Trees -- minetest.register_node("default:tree", { description = "Tree", tiles = {"default_tree_top.png", "default_tree_top.png", "default_tree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree = 1, choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:wood", { description = "Wooden Planks", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_wood.png"}, is_ground_content = false, groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2, wood = 1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:sapling", { description = "Sapling", drawtype = "plantlike", tiles = {"default_sapling.png"}, inventory_image = "default_sapling.png", wield_image = "default_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-4 / 16, -0.5, -4 / 16, 4 / 16, 7 / 16, 4 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(2400,4800)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:sapling", -- minp, maxp to be checked, relative to sapling pos -- minp_relative.y = 1 because sapling pos has been checked {x = -2, y = 1, z = -2}, {x = 2, y = 6, z = 2}, -- maximum interval of interior volume check 4) return itemstack end, }) minetest.register_node("default:leaves", { description = "Leaves", drawtype = "allfaces_optional", waving = 1, tiles = {"default_leaves.png"}, special_tiles = {"default_leaves_simple.png"}, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { { -- player will get sapling with 1/20 chance items = {'default:sapling'}, rarity = 20, }, { -- player will get leaves only if he get no saplings, -- this is because max_items is 1 items = {'default:leaves'}, } } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:apple", { description = "Apple", drawtype = "plantlike", tiles = {"default_apple.png"}, inventory_image = "default_apple.png", paramtype = "light", sunlight_propagates = true, walkable = false, is_ground_content = false, selection_box = { type = "fixed", fixed = {-3 / 16, -7 / 16, -3 / 16, 3 / 16, 4 / 16, 3 / 16} }, groups = {fleshy = 3, dig_immediate = 3, flammable = 2, leafdecay = 3, leafdecay_drop = 1}, on_use = minetest.item_eat(2), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer, itemstack) if placer:is_player() then minetest.set_node(pos, {name = "default:apple", param2 = 1}) end end, }) minetest.register_node("default:jungletree", { description = "Jungle Tree", tiles = {"default_jungletree_top.png", "default_jungletree_top.png", "default_jungletree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree = 1, choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:junglewood", { description = "Junglewood Planks", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_junglewood.png"}, is_ground_content = false, groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2, wood = 1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:jungleleaves", { description = "Jungle Leaves", drawtype = "allfaces_optional", waving = 1, tiles = {"default_jungleleaves.png"}, special_tiles = {"default_jungleleaves_simple.png"}, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {'default:junglesapling'}, rarity = 20}, {items = {'default:jungleleaves'}} } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:junglesapling", { description = "Jungle Sapling", drawtype = "plantlike", tiles = {"default_junglesapling.png"}, inventory_image = "default_junglesapling.png", wield_image = "default_junglesapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-4 / 16, -0.5, -4 / 16, 4 / 16, 7 / 16, 4 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(2400,4800)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:junglesapling", -- minp, maxp to be checked, relative to sapling pos -- minp_relative.y = 1 because sapling pos has been checked {x = -2, y = 1, z = -2}, {x = 2, y = 15, z = 2}, -- maximum interval of interior volume check 4) return itemstack end, }) minetest.register_node("default:pine_tree", { description = "Pine Tree", tiles = {"default_pine_tree_top.png", "default_pine_tree_top.png", "default_pine_tree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree = 1, choppy = 3, oddly_breakable_by_hand = 1, flammable = 3}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:pine_wood", { description = "Pine Wood Planks", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_pine_wood.png"}, is_ground_content = false, groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3, wood = 1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:pine_needles",{ description = "Pine Needles", drawtype = "allfaces_optional", tiles = {"default_pine_needles.png"}, waving = 1, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:pine_sapling"}, rarity = 20}, {items = {"default:pine_needles"}} } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:pine_sapling", { description = "Pine Sapling", drawtype = "plantlike", tiles = {"default_pine_sapling.png"}, inventory_image = "default_pine_sapling.png", wield_image = "default_pine_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-4 / 16, -0.5, -4 / 16, 4 / 16, 7 / 16, 4 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 3, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(2400,4800)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:pine_sapling", -- minp, maxp to be checked, relative to sapling pos -- minp_relative.y = 1 because sapling pos has been checked {x = -2, y = 1, z = -2}, {x = 2, y = 12, z = 2}, -- maximum interval of interior volume check 4) return itemstack end, }) minetest.register_node("default:acacia_tree", { description = "Acacia Tree", tiles = {"default_acacia_tree_top.png", "default_acacia_tree_top.png", "default_acacia_tree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree = 1, choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:acacia_wood", { description = "Acacia Wood Planks", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_acacia_wood.png"}, is_ground_content = false, groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2, wood = 1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:acacia_leaves", { description = "Acacia Leaves", drawtype = "allfaces_optional", tiles = {"default_acacia_leaves.png"}, special_tiles = {"default_acacia_leaves_simple.png"}, waving = 1, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:acacia_sapling"}, rarity = 20}, {items = {"default:acacia_leaves"}} } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:acacia_sapling", { description = "Acacia Tree Sapling", drawtype = "plantlike", tiles = {"default_acacia_sapling.png"}, inventory_image = "default_acacia_sapling.png", wield_image = "default_acacia_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-4 / 16, -0.5, -4 / 16, 4 / 16, 7 / 16, 4 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(2400,4800)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:acacia_sapling", -- minp, maxp to be checked, relative to sapling pos -- minp_relative.y = 1 because sapling pos has been checked {x = -4, y = 1, z = -4}, {x = 4, y = 6, z = 4}, -- maximum interval of interior volume check 4) return itemstack end, }) minetest.register_node("default:aspen_tree", { description = "Aspen Tree", tiles = {"default_aspen_tree_top.png", "default_aspen_tree_top.png", "default_aspen_tree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree = 1, choppy = 3, oddly_breakable_by_hand = 1, flammable = 3}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:aspen_wood", { description = "Aspen Wood Planks", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_aspen_wood.png"}, is_ground_content = false, groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3, wood = 1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:aspen_leaves", { description = "Aspen Leaves", drawtype = "allfaces_optional", tiles = {"default_aspen_leaves.png"}, waving = 1, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:aspen_sapling"}, rarity = 20}, {items = {"default:aspen_leaves"}} } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:aspen_sapling", { description = "Aspen Tree Sapling", drawtype = "plantlike", tiles = {"default_aspen_sapling.png"}, inventory_image = "default_aspen_sapling.png", wield_image = "default_aspen_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-3 / 16, -0.5, -3 / 16, 3 / 16, 0.5, 3 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 3, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(2400,4800)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:aspen_sapling", -- minp, maxp to be checked, relative to sapling pos -- minp_relative.y = 1 because sapling pos has been checked {x = -2, y = 1, z = -2}, {x = 2, y = 12, z = 2}, -- maximum interval of interior volume check 4) return itemstack end, }) -- -- Ores -- minetest.register_node("default:stone_with_coal", { description = "Coal Ore", tiles = {"default_stone.png^default_mineral_coal.png"}, groups = {cracky = 3}, drop = 'default:coal_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:coalblock", { description = "Coal Block", tiles = {"default_coal_block.png"}, is_ground_content = false, groups = {cracky = 3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_iron", { description = "Iron Ore", tiles = {"default_stone.png^default_mineral_iron.png"}, groups = {cracky = 2}, drop = 'default:iron_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:steelblock", { description = "Steel Block", tiles = {"default_steel_block.png"}, is_ground_content = false, groups = {cracky = 1, level = 2}, sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:stone_with_copper", { description = "Copper Ore", tiles = {"default_stone.png^default_mineral_copper.png"}, groups = {cracky = 2}, drop = 'default:copper_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:copperblock", { description = "Copper Block", tiles = {"default_copper_block.png"}, is_ground_content = false, groups = {cracky = 1, level = 2}, sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:stone_with_tin", { description = "Tin Ore", tiles = {"default_stone.png^default_mineral_tin.png"}, groups = {cracky = 2}, drop = "default:tin_lump", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:tinblock", { description = "Tin Block", tiles = {"default_tin_block.png"}, is_ground_content = false, groups = {cracky = 1, level = 2}, sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:bronzeblock", { description = "Bronze Block", tiles = {"default_bronze_block.png"}, is_ground_content = false, groups = {cracky = 1, level = 2}, sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:stone_with_mese", { description = "Mese Ore", tiles = {"default_stone.png^default_mineral_mese.png"}, groups = {cracky = 1}, drop = "default:mese_crystal", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:mese", { description = "Mese Block", tiles = {"default_mese_block.png"}, paramtype = "light", groups = {cracky = 1, level = 2}, sounds = default.node_sound_stone_defaults(), light_source = 3, }) minetest.register_node("default:stone_with_gold", { description = "Gold Ore", tiles = {"default_stone.png^default_mineral_gold.png"}, groups = {cracky = 2}, drop = "default:gold_lump", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:goldblock", { description = "Gold Block", tiles = {"default_gold_block.png"}, is_ground_content = false, groups = {cracky = 1}, sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:stone_with_diamond", { description = "Diamond Ore", tiles = {"default_stone.png^default_mineral_diamond.png"}, groups = {cracky = 1}, drop = "default:diamond", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:diamondblock", { description = "Diamond Block", tiles = {"default_diamond_block.png"}, is_ground_content = false, groups = {cracky = 1, level = 3}, sounds = default.node_sound_stone_defaults(), }) -- -- Plantlife (non-cubic) -- minetest.register_node("default:cactus", { description = "Cactus", tiles = {"default_cactus_top.png", "default_cactus_top.png", "default_cactus_side.png"}, paramtype2 = "facedir", groups = {choppy = 3}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node, }) minetest.register_node("default:papyrus", { description = "Papyrus", drawtype = "plantlike", tiles = {"default_papyrus.png"}, inventory_image = "default_papyrus.png", wield_image = "default_papyrus.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 0.5, 6 / 16}, }, groups = {snappy = 3, flammable = 2}, sounds = default.node_sound_leaves_defaults(), after_dig_node = function(pos, node, metadata, digger) default.dig_up(pos, node, digger) end, }) minetest.register_node("default:dry_shrub", { description = "Dry Shrub", drawtype = "plantlike", waving = 1, tiles = {"default_dry_shrub.png"}, inventory_image = "default_dry_shrub.png", wield_image = "default_dry_shrub.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, flammable = 3, attached_node = 1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-5 / 16, -0.5, -5 / 16, 5 / 16, 4 / 16, 5 / 16}, }, }) minetest.register_node("default:junglegrass", { description = "Jungle Grass", drawtype = "plantlike", waving = 1, visual_scale = 1.69, tiles = {"default_junglegrass.png"}, inventory_image = "default_junglegrass.png", wield_image = "default_junglegrass.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, flora = 1, attached_node = 1, flammable = 1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-7 / 16, -0.5, -7 / 16, 7 / 16, 1.19, 7 / 16}, }, }) minetest.register_node("default:grass_1", { description = "Grass", drawtype = "plantlike", waving = 1, tiles = {"default_grass_1.png"}, -- Use texture of a taller grass stage in inventory inventory_image = "default_grass_3.png", wield_image = "default_grass_3.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, flora = 1, attached_node = 1, grass = 1, flammable = 1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, -5 / 16, 6 / 16}, }, on_place = function(itemstack, placer, pointed_thing) -- place a random grass node local stack = ItemStack("default:grass_" .. math.random(1,5)) local ret = minetest.item_place(stack, placer, pointed_thing) return ItemStack("default:grass_1 " .. itemstack:get_count() - (1 - ret:get_count())) end, }) for i = 2, 5 do minetest.register_node("default:grass_" .. i, { description = "Grass", drawtype = "plantlike", waving = 1, tiles = {"default_grass_" .. i .. ".png"}, inventory_image = "default_grass_" .. i .. ".png", wield_image = "default_grass_" .. i .. ".png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, drop = "default:grass_1", groups = {snappy = 3, flora = 1, attached_node = 1, not_in_creative_inventory = 1, grass = 1, flammable = 1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, -3 / 16, 6 / 16}, }, }) end minetest.register_node("default:dry_grass_1", { description = "Dry Grass", drawtype = "plantlike", waving = 1, tiles = {"default_dry_grass_1.png"}, inventory_image = "default_dry_grass_3.png", wield_image = "default_dry_grass_3.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, flammable = 3, flora = 1, attached_node = 1, dry_grass = 1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, -3 / 16, 6 / 16}, }, on_place = function(itemstack, placer, pointed_thing) -- place a random dry grass node local stack = ItemStack("default:dry_grass_" .. math.random(1, 5)) local ret = minetest.item_place(stack, placer, pointed_thing) return ItemStack("default:dry_grass_1 " .. itemstack:get_count() - (1 - ret:get_count())) end, }) for i = 2, 5 do minetest.register_node("default:dry_grass_" .. i, { description = "Dry Grass", drawtype = "plantlike", waving = 1, tiles = {"default_dry_grass_" .. i .. ".png"}, inventory_image = "default_dry_grass_" .. i .. ".png", wield_image = "default_dry_grass_" .. i .. ".png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy = 3, flammable = 3, flora = 1, attached_node = 1, not_in_creative_inventory=1, dry_grass = 1}, drop = "default:dry_grass_1", sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, -1 / 16, 6 / 16}, }, }) end minetest.register_node("default:bush_stem", { description = "Bush Stem", drawtype = "plantlike", visual_scale = 1.41, tiles = {"default_bush_stem.png"}, inventory_image = "default_bush_stem.png", wield_image = "default_bush_stem.png", paramtype = "light", sunlight_propagates = true, groups = {choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = default.node_sound_wood_defaults(), selection_box = { type = "fixed", fixed = {-7 / 16, -0.5, -7 / 16, 7 / 16, 0.5, 7 / 16}, }, }) minetest.register_node("default:bush_leaves", { description = "Bush Leaves", drawtype = "allfaces_optional", waving = 1, tiles = {"default_leaves_simple.png"}, paramtype = "light", groups = {snappy = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:bush_sapling"}, rarity = 5}, {items = {"default:bush_leaves"}} } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:bush_sapling", { description = "Bush Sapling", drawtype = "plantlike", tiles = {"default_bush_sapling.png"}, inventory_image = "default_bush_sapling.png", wield_image = "default_bush_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-4 / 16, -0.5, -4 / 16, 4 / 16, 2 / 16, 4 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(1200, 2400)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:bush_sapling", -- minp, maxp to be checked, relative to sapling pos {x = -1, y = 0, z = -1}, {x = 1, y = 1, z = 1}, -- maximum interval of interior volume check 2) return itemstack end, }) minetest.register_node("default:acacia_bush_stem", { description = "Acacia Bush Stem", drawtype = "plantlike", visual_scale = 1.41, tiles = {"default_acacia_bush_stem.png"}, inventory_image = "default_acacia_bush_stem.png", wield_image = "default_acacia_bush_stem.png", paramtype = "light", sunlight_propagates = true, groups = {choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = default.node_sound_wood_defaults(), selection_box = { type = "fixed", fixed = {-7 / 16, -0.5, -7 / 16, 7 / 16, 0.5, 7 / 16}, }, }) minetest.register_node("default:acacia_bush_leaves", { description = "Acacia Bush Leaves", drawtype = "allfaces_optional", waving = 1, tiles = {"default_acacia_leaves_simple.png"}, paramtype = "light", groups = {snappy = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:acacia_bush_sapling"}, rarity = 5}, {items = {"default:acacia_bush_leaves"}} } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:acacia_bush_sapling", { description = "Acacia Bush Sapling", drawtype = "plantlike", tiles = {"default_acacia_bush_sapling.png"}, inventory_image = "default_acacia_bush_sapling.png", wield_image = "default_acacia_bush_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, on_timer = default.grow_sapling, selection_box = { type = "fixed", fixed = {-3 / 16, -0.5, -3 / 16, 3 / 16, 2 / 16, 3 / 16} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), on_construct = function(pos) minetest.get_node_timer(pos):start(math.random(1200, 2400)) end, on_place = function(itemstack, placer, pointed_thing) itemstack = default.sapling_on_place(itemstack, placer, pointed_thing, "default:acacia_bush_sapling", -- minp, maxp to be checked, relative to sapling pos {x = -1, y = 0, z = -1}, {x = 1, y = 1, z = 1}, -- maximum interval of interior volume check 2) return itemstack end, }) -- -- Corals -- minetest.register_node("default:coral_brown", { description = "Brown Coral", tiles = {"default_coral_brown.png"}, groups = {cracky = 3}, drop = "default:coral_skeleton", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:coral_orange", { description = "Orange Coral", tiles = {"default_coral_orange.png"}, groups = {cracky = 3}, drop = "default:coral_skeleton", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:coral_skeleton", { description = "Coral Skeleton", tiles = {"default_coral_skeleton.png"}, groups = {cracky = 3}, sounds = default.node_sound_stone_defaults(), }) -- -- Liquids -- minetest.register_node("default:water_source", { description = "Water Source", drawtype = "liquid", tiles = { { name = "default_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, }, }, special_tiles = { -- New-style water source material (mostly unused) { name = "default_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, backface_culling = false, }, }, alpha = 160, paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = 1, post_effect_color = {a = 103, r = 30, g = 60, b = 90}, groups = {water = 3, liquid = 3, puts_out_fire = 1, cools_lava = 1}, sounds = default.node_sound_water_defaults(), }) minetest.register_node("default:water_flowing", { description = "Flowing Water", drawtype = "flowingliquid", tiles = {"default_water.png"}, special_tiles = { { name = "default_water_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, { name = "default_water_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, }, alpha = 160, paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = 1, post_effect_color = {a = 103, r = 30, g = 60, b = 90}, groups = {water = 3, liquid = 3, puts_out_fire = 1, not_in_creative_inventory = 1, cools_lava = 1}, sounds = default.node_sound_water_defaults(), }) minetest.register_node("default:river_water_source", { description = "River Water Source", drawtype = "liquid", tiles = { { name = "default_river_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, }, }, special_tiles = { { name = "default_river_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, backface_culling = false, }, }, alpha = 160, paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:river_water_flowing", liquid_alternative_source = "default:river_water_source", liquid_viscosity = 1, liquid_renewable = false, liquid_range = 2, post_effect_color = {a = 103, r = 30, g = 76, b = 90}, groups = {water = 3, liquid = 3, puts_out_fire = 1, cools_lava = 1}, sounds = default.node_sound_water_defaults(), }) minetest.register_node("default:river_water_flowing", { description = "Flowing River Water", drawtype = "flowingliquid", tiles = {"default_river_water.png"}, special_tiles = { { name = "default_river_water_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, { name = "default_river_water_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, }, alpha = 160, paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:river_water_flowing", liquid_alternative_source = "default:river_water_source", liquid_viscosity = 1, liquid_renewable = false, liquid_range = 2, post_effect_color = {a = 103, r = 30, g = 76, b = 90}, groups = {water = 3, liquid = 3, puts_out_fire = 1, not_in_creative_inventory = 1, cools_lava = 1}, sounds = default.node_sound_water_defaults(), }) minetest.register_node("default:lava_source", { description = "Lava Source", drawtype = "liquid", tiles = { { name = "default_lava_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, special_tiles = { -- New-style lava source material (mostly unused) { name = "default_lava_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, backface_culling = false, }, }, paramtype = "light", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a = 191, r = 255, g = 64, b = 0}, groups = {lava = 3, liquid = 2, igniter = 1}, }) minetest.register_node("default:lava_flowing", { description = "Flowing Lava", drawtype = "flowingliquid", tiles = {"default_lava.png"}, special_tiles = { { name = "default_lava_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, { name = "default_lava_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, }, paramtype = "light", paramtype2 = "flowingliquid", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a = 191, r = 255, g = 64, b = 0}, groups = {lava = 3, liquid = 2, igniter = 1, not_in_creative_inventory = 1}, }) -- -- Tools / "Advanced" crafting / Non-"natural" -- local function get_chest_formspec(pos) local spos = pos.x .. "," .. pos.y .. "," .. pos.z local formspec = "size[8,9]" .. default.gui_bg .. default.gui_bg_img .. default.gui_slots .. "list[nodemeta:" .. spos .. ";main;0,0.3;8,4;]" .. "list[current_player;main;0,4.85;8,1;]" .. "list[current_player;main;0,6.08;8,3;8]" .. "listring[nodemeta:" .. spos .. ";main]" .. "listring[current_player;main]" .. default.get_hotbar_bg(0,4.85) return formspec end local function chest_lid_obstructed(pos) local above = { x = pos.x, y = pos.y + 1, z = pos.z } local def = minetest.registered_nodes[minetest.get_node(above).name] -- allow ladders, signs, wallmounted things and torches to not obstruct if def.drawtype == "airlike" or def.drawtype == "signlike" or def.drawtype == "torchlike" or (def.drawtype == "nodebox" and def.paramtype2 == "wallmounted") then return false end return true end local open_chests = {} minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "default:chest" then return end if not player or not fields.quit then return end local pn = player:get_player_name() if not open_chests[pn] then return end local pos = open_chests[pn].pos local sound = open_chests[pn].sound local swap = open_chests[pn].swap local node = minetest.get_node(pos) open_chests[pn] = nil for k, v in pairs(open_chests) do if v.pos.x == pos.x and v.pos.y == pos.y and v.pos.z == pos.z then return true end end minetest.after(0.2, minetest.swap_node, pos, { name = "default:" .. swap, param2 = node.param2 }) minetest.sound_play(sound, {gain = 0.3, pos = pos, max_hear_distance = 10}) return true end) function default.register_chest(name, d) local def = table.copy(d) def.drawtype = "mesh" def.visual = "mesh" def.paramtype = "light" def.paramtype2 = "facedir" def.legacy_facedir_simple = true def.is_ground_content = false if def.protected then def.on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", "Locked Chest") meta:set_string("owner", "") local inv = meta:get_inventory() inv:set_size("main", 8*4) end def.after_place_node = function(pos, placer) local meta = minetest.get_meta(pos) meta:set_string("owner", placer:get_player_name() or "") meta:set_string("infotext", "Locked Chest (owned by " .. meta:get_string("owner") .. ")") end def.can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("main") and default.can_interact_with_node(player, pos) end def.allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if not default.can_interact_with_node(player, pos) then return 0 end return count end def.allow_metadata_inventory_put = function(pos, listname, index, stack, player) if not default.can_interact_with_node(player, pos) then return 0 end return stack:get_count() end def.allow_metadata_inventory_take = function(pos, listname, index, stack, player) if not default.can_interact_with_node(player, pos) then return 0 end return stack:get_count() end def.on_rightclick = function(pos, node, clicker, itemstack, pointed_thing) if not default.can_interact_with_node(clicker, pos) then return itemstack end minetest.sound_play(def.sound_open, {gain = 0.3, pos = pos, max_hear_distance = 10}) if not chest_lid_obstructed(pos) then minetest.swap_node(pos, { name = "default:" .. name .. "_open", param2 = node.param2 }) end minetest.after(0.2, minetest.show_formspec, clicker:get_player_name(), "default:chest", get_chest_formspec(pos)) open_chests[clicker:get_player_name()] = { pos = pos, sound = def.sound_close, swap = name } end def.on_blast = function() end def.on_key_use = function(pos, player) local secret = minetest.get_meta(pos):get_string("key_lock_secret") local itemstack = player:get_wielded_item() local key_meta = itemstack:get_meta() if key_meta:get_string("secret") == "" then key_meta:set_string("secret", minetest.parse_json(itemstack:get_metadata()).secret) itemstack:set_metadata("") end if secret ~= key_meta:get_string("secret") then return end minetest.show_formspec( player:get_player_name(), "default:chest_locked", get_chest_formspec(pos) ) end def.on_skeleton_key_use = function(pos, player, newsecret) local meta = minetest.get_meta(pos) local owner = meta:get_string("owner") local pn = player:get_player_name() -- verify placer is owner of lockable chest if owner ~= pn then minetest.record_protection_violation(pos, pn) minetest.chat_send_player(pn, "You do not own this chest.") return nil end local secret = meta:get_string("key_lock_secret") if secret == "" then secret = newsecret meta:set_string("key_lock_secret", secret) end return secret, "a locked chest", owner end else def.on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", "Chest") local inv = meta:get_inventory() inv:set_size("main", 8*4) end def.can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("main") end def.on_rightclick = function(pos, node, clicker) minetest.sound_play(def.sound_open, {gain = 0.3, pos = pos, max_hear_distance = 10}) if not chest_lid_obstructed(pos) then minetest.swap_node(pos, { name = "default:" .. name .. "_open", param2 = node.param2 }) end minetest.after(0.2, minetest.show_formspec, clicker:get_player_name(), "default:chest", get_chest_formspec(pos)) open_chests[clicker:get_player_name()] = { pos = pos, sound = def.sound_close, swap = name } end end def.on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name() .. " moves stuff in chest at " .. minetest.pos_to_string(pos)) end def.on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " moves " .. stack:get_name() .. " to chest at " .. minetest.pos_to_string(pos)) end def.on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " takes " .. stack:get_name() .. " from chest at " .. minetest.pos_to_string(pos)) end def.on_blast = function(pos) local drops = {} default.get_inventory_drops(pos, "main", drops) drops[#drops+1] = "default:chest" minetest.remove_node(pos) return drops end local def_opened = table.copy(def) local def_closed = table.copy(def) def_opened.mesh = "chest_open.obj" def_opened.drop = "default:" .. name def_opened.groups.not_in_creative_inventory = 1 def_opened.selection_box = { type = "fixed", fixed = { -1/2, -1/2, -1/2, 1/2, 3/16, 1/2 }, } def_opened.can_dig = function() return false end def_closed.mesh = "cube.obj" minetest.register_node("default:" .. name, def_closed) minetest.register_node("default:" .. name .. "_open", def_opened) -- convert old chests to this new variant minetest.register_lbm({ label = "update chests to opening chests", name = "default:upgrade_" .. name .. "_v2", nodenames = {"default:" .. name}, action = function(pos, node) local meta = minetest.get_meta(pos) meta:set_string("formspec", nil) local inv = meta:get_inventory() local list = inv:get_list("default:chest") if list then inv:set_size("main", 8*4) inv:set_list("main", list) inv:set_list("default:chest", nil) end end }) end default.register_chest("chest", { description = "Chest", tiles = { "default_chest_wood.png" }, sounds = default.node_sound_wood_defaults(), sound_open = "default_chest_open", sound_close = "default_chest_close", groups = {choppy = 2, oddly_breakable_by_hand = 2}, }) default.register_chest("chest_locked", { description = "Locked Chest", tiles = { "default_chest_wood_locked.png" }, sounds = default.node_sound_wood_defaults(), sound_open = "default_chest_open", sound_close = "default_chest_close", groups = {choppy = 2, oddly_breakable_by_hand = 2}, protected = true, }) local bookshelf_formspec = "size[8,7;]" .. default.gui_bg .. default.gui_bg_img .. default.gui_slots .. "list[context;books;0,0.3;8,2;]" .. "list[current_player;main;0,2.85;8,1;]" .. "list[current_player;main;0,4.08;8,3;8]" .. "listring[context;books]" .. "listring[current_player;main]" .. default.get_hotbar_bg(0,2.85) local function get_bookshelf_formspec(inv) local formspec = bookshelf_formspec local invlist = inv and inv:get_list("books") -- Inventory slots overlay local bx, by = 0, 0.3 for i = 1, 16 do if i == 9 then bx = 0 by = by + 1 end if not invlist or invlist[i]:is_empty() then formspec = formspec .. "image[" .. bx .. "," .. by .. ";1,1;default_bookshelf_slot.png]" end bx = bx + 1 end return formspec end minetest.register_node("default:bookshelf", { description = "Bookshelf", tiles = {"default_wood.png", "default_wood.png", "default_wood.png", "default_wood.png", "default_bookshelf.png", "default_bookshelf.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, sounds = default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_bookshelf_formspec(nil)) local inv = meta:get_inventory() inv:set_size("books", 8 * 2) end, can_dig = function(pos,player) local inv = minetest.get_meta(pos):get_inventory() return inv:is_empty("books") end, allow_metadata_inventory_put = function(pos, listname, index, stack) if minetest.get_item_group(stack:get_name(), "book") ~= 0 then return stack:get_count() end return 0 end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name() .. " moves stuff in bookshelf at " .. minetest.pos_to_string(pos)) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_bookshelf_formspec(meta:get_inventory())) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " moves stuff to bookshelf at " .. minetest.pos_to_string(pos)) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_bookshelf_formspec(meta:get_inventory())) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " takes stuff from bookshelf at " .. minetest.pos_to_string(pos)) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_bookshelf_formspec(meta:get_inventory())) end, on_blast = function(pos) local drops = {} default.get_inventory_drops(pos, "books", drops) drops[#drops+1] = "default:bookshelf" minetest.remove_node(pos) return drops end, }) local function register_sign(material, desc, def) minetest.register_node("default:sign_wall_" .. material, { description = desc .. " Sign", drawtype = "nodebox", tiles = {"default_sign_wall_" .. material .. ".png"}, inventory_image = "default_sign_" .. material .. ".png", wield_image = "default_sign_" .. material .. ".png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, is_ground_content = false, walkable = false, node_box = { type = "wallmounted", wall_top = {-0.4375, 0.4375, -0.3125, 0.4375, 0.5, 0.3125}, wall_bottom = {-0.4375, -0.5, -0.3125, 0.4375, -0.4375, 0.3125}, wall_side = {-0.5, -0.3125, -0.4375, -0.4375, 0.3125, 0.4375}, }, groups = def.groups, legacy_wallmounted = true, sounds = def.sounds, on_construct = function(pos) --local n = minetest.get_node(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", "field[text;;${text}]") end, on_receive_fields = function(pos, formname, fields, sender) --print("Sign at "..minetest.pos_to_string(pos).." got "..dump(fields)) local player_name = sender:get_player_name() if minetest.is_protected(pos, player_name) then minetest.record_protection_violation(pos, player_name) return end local meta = minetest.get_meta(pos) if not fields.text then return end minetest.log("action", (player_name or "") .. " wrote \"" .. fields.text .. "\" to sign at " .. minetest.pos_to_string(pos)) meta:set_string("text", fields.text) meta:set_string("infotext", '"' .. fields.text .. '"') end, }) end register_sign("wood", "Wooden", { sounds = default.node_sound_wood_defaults(), groups = {choppy = 2, attached_node = 1, flammable = 2, oddly_breakable_by_hand = 3} }) register_sign("steel", "Steel", { sounds = default.node_sound_metal_defaults(), groups = {cracky = 2, attached_node = 1} }) minetest.register_node("default:ladder_wood", { description = "Wooden Ladder", drawtype = "signlike", tiles = {"default_ladder_wood.png"}, inventory_image = "default_ladder_wood.png", wield_image = "default_ladder_wood.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, climbable = true, is_ground_content = false, selection_box = { type = "wallmounted", --wall_top = = <default> --wall_bottom = = <default> --wall_side = = <default> }, groups = {choppy = 2, oddly_breakable_by_hand = 3, flammable = 2}, legacy_wallmounted = true, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:ladder_steel", { description = "Steel Ladder", drawtype = "signlike", tiles = {"default_ladder_steel.png"}, inventory_image = "default_ladder_steel.png", wield_image = "default_ladder_steel.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, climbable = true, is_ground_content = false, selection_box = { type = "wallmounted", --wall_top = = <default> --wall_bottom = = <default> --wall_side = = <default> }, groups = {cracky = 2}, sounds = default.node_sound_metal_defaults(), }) default.register_fence("default:fence_wood", { description = "Wooden Fence", texture = "default_fence_wood.png", inventory_image = "default_fence_overlay.png^default_wood.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_wood.png^default_fence_overlay.png^[makealpha:255,126,126", material = "default:wood", groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, sounds = default.node_sound_wood_defaults() }) default.register_fence("default:fence_acacia_wood", { description = "Acacia Fence", texture = "default_fence_acacia_wood.png", inventory_image = "default_fence_overlay.png^default_acacia_wood.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_acacia_wood.png^default_fence_overlay.png^[makealpha:255,126,126", material = "default:acacia_wood", groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, sounds = default.node_sound_wood_defaults() }) default.register_fence("default:fence_junglewood", { description = "Junglewood Fence", texture = "default_fence_junglewood.png", inventory_image = "default_fence_overlay.png^default_junglewood.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_junglewood.png^default_fence_overlay.png^[makealpha:255,126,126", material = "default:junglewood", groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, sounds = default.node_sound_wood_defaults() }) default.register_fence("default:fence_pine_wood", { description = "Pine Fence", texture = "default_fence_pine_wood.png", inventory_image = "default_fence_overlay.png^default_pine_wood.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_pine_wood.png^default_fence_overlay.png^[makealpha:255,126,126", material = "default:pine_wood", groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, sounds = default.node_sound_wood_defaults() }) default.register_fence("default:fence_aspen_wood", { description = "Aspen Fence", texture = "default_fence_aspen_wood.png", inventory_image = "default_fence_overlay.png^default_aspen_wood.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_aspen_wood.png^default_fence_overlay.png^[makealpha:255,126,126", material = "default:aspen_wood", groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, sounds = default.node_sound_wood_defaults() }) minetest.register_node("default:glass", { description = "Glass", drawtype = "glasslike_framed_optional", tiles = {"default_glass.png", "default_glass_detail.png"}, paramtype = "light", paramtype2 = "glasslikeliquidlevel", sunlight_propagates = true, is_ground_content = false, groups = {cracky = 3, oddly_breakable_by_hand = 3}, sounds = default.node_sound_glass_defaults(), }) minetest.register_node("default:obsidian_glass", { description = "Obsidian Glass", drawtype = "glasslike_framed_optional", tiles = {"default_obsidian_glass.png", "default_obsidian_glass_detail.png"}, paramtype = "light", paramtype2 = "glasslikeliquidlevel", is_ground_content = false, sunlight_propagates = true, sounds = default.node_sound_glass_defaults(), groups = {cracky = 3}, }) minetest.register_node("default:brick", { description = "Brick Block", paramtype2 = "facedir", place_param2 = 0, tiles = {"default_brick.png"}, is_ground_content = false, groups = {cracky = 3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:meselamp", { description = "Mese Lamp", drawtype = "glasslike", tiles = {"default_meselamp.png"}, paramtype = "light", sunlight_propagates = true, is_ground_content = false, groups = {cracky = 3, oddly_breakable_by_hand = 3}, sounds = default.node_sound_glass_defaults(), light_source = default.LIGHT_MAX, }) minetest.register_node("default:mese_post_light", { description = "Mese Post Light", tiles = {"default_mese_post_light_top.png", "default_mese_post_light_top.png", "default_mese_post_light_side_dark.png", "default_mese_post_light_side_dark.png", "default_mese_post_light_side.png", "default_mese_post_light_side.png"}, wield_image = "default_mese_post_light_side.png", drawtype = "nodebox", node_box = { type = "fixed", fixed = { {-2 / 16, -8 / 16, -2 / 16, 2 / 16, 8 / 16, 2 / 16}, }, }, paramtype = "light", light_source = default.LIGHT_MAX, sunlight_propagates = true, is_ground_content = false, groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, sounds = default.node_sound_wood_defaults(), }) -- -- Misc -- minetest.register_node("default:cloud", { description = "Cloud", tiles = {"default_cloud.png"}, is_ground_content = false, sounds = default.node_sound_defaults(), groups = {not_in_creative_inventory = 1}, }) -- -- register trees for leafdecay -- if minetest.get_mapgen_setting("mg_name") == "v6" then default.register_leafdecay({ trunks = {"default:tree"}, leaves = {"default:apple", "default:leaves"}, radius = 2, }) default.register_leafdecay({ trunks = {"default:jungletree"}, leaves = {"default:jungleleaves"}, radius = 3, }) default.register_leafdecay({ trunks = {"default:pine_tree"}, leaves = {"default:pine_needles"}, radius = 3, }) else default.register_leafdecay({ trunks = {"default:tree"}, leaves = {"default:apple", "default:leaves"}, radius = 3, }) default.register_leafdecay({ trunks = {"default:jungletree"}, leaves = {"default:jungleleaves"}, radius = 2, }) default.register_leafdecay({ trunks = {"default:pine_tree"}, leaves = {"default:pine_needles"}, radius = 2, }) end default.register_leafdecay({ trunks = {"default:acacia_tree"}, leaves = {"default:acacia_leaves"}, radius = 2, }) default.register_leafdecay({ trunks = {"default:aspen_tree"}, leaves = {"default:aspen_leaves"}, radius = 3, }) default.register_leafdecay({ trunks = {"default:bush_stem"}, leaves = {"default:bush_leaves"}, radius = 1, }) default.register_leafdecay({ trunks = {"default:acacia_bush_stem"}, leaves = {"default:acacia_bush_leaves"}, radius = 1, })
linushsao/marsu_game-linus-v0.2
mods/minetest_game/default/nodes.lua
Lua
gpl-3.0
67,149
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /*!----------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.32.1(29a273516805a852aa8edc5e05059f119b13eff0) * Released under the MIT license * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt *-----------------------------------------------------------------------------*/ define("vs/basic-languages/html/html", ["require", "require"], function (require) { var moduleExports = function () { var u = Object.create; var o = Object.defineProperty; var b = Object.getOwnPropertyDescriptor; var x = Object.getOwnPropertyNames; var g = Object.getPrototypeOf, y = Object.prototype.hasOwnProperty; var d = function d(e) { return o(e, "__esModule", { value: !0 }); }; var k = function (e) { return typeof require != "undefined" ? require : typeof Proxy != "undefined" ? new Proxy(e, { get: function get(t, n) { return (typeof require != "undefined" ? require : t)[n]; } }) : e; }(function (e) { if (typeof require != "undefined") return require.apply(this, arguments); throw new Error('Dynamic require of "' + e + '" is not supported'); }); var E = function E(e, t) { return function () { return t || e((t = { exports: {} }).exports, t), t.exports; }; }, w = function w(e, t) { for (var n in t) { o(e, n, { get: t[n], enumerable: !0 }); } }, a = function a(e, t, n, s) { if (t && babelHelpers.typeof(t) == "object" || typeof t == "function") { var _iterator = _createForOfIteratorHelper(x(t)), _step; try { var _loop = function _loop() { var r = _step.value; !y.call(e, r) && (n || r !== "default") && o(e, r, { get: function get() { return t[r]; }, enumerable: !(s = b(t, r)) || s.enumerable }); }; for (_iterator.s(); !(_step = _iterator.n()).done;) { _loop(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return e; }, m = function m(e, t) { return a(d(o(e != null ? u(g(e)) : {}, "default", !t && e && e.__esModule ? { get: function get() { return e.default; }, enumerable: !0 } : { value: e, enumerable: !0 })), e); }, T = function (e) { return function (t, n) { return e && e.get(t) || (n = a(d({}), t, 1), e && e.set(t, n), n); }; }(typeof WeakMap != "undefined" ? new WeakMap() : 0); var l = E(function (C, p) { var h = m(k("vs/editor/editor.api")); p.exports = h; }); var $ = {}; w($, { conf: function conf() { return f; }, language: function language() { return v; } }); var i = {}; a(i, m(l())); var c = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"], f = { wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g, comments: { blockComment: ["<!--", "-->"] }, brackets: [["<!--", "-->"], ["<", ">"], ["{", "}"], ["(", ")"]], autoClosingPairs: [{ open: "{", close: "}" }, { open: "[", close: "]" }, { open: "(", close: ")" }, { open: '"', close: '"' }, { open: "'", close: "'" }], surroundingPairs: [{ open: '"', close: '"' }, { open: "'", close: "'" }, { open: "{", close: "}" }, { open: "[", close: "]" }, { open: "(", close: ")" }, { open: "<", close: ">" }], onEnterRules: [{ beforeText: new RegExp("<(?!(?:".concat(c.join("|"), "))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$"), "i"), afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i, action: { indentAction: i.languages.IndentAction.IndentOutdent } }, { beforeText: new RegExp("<(?!(?:".concat(c.join("|"), "))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$"), "i"), action: { indentAction: i.languages.IndentAction.Indent } }], folding: { markers: { start: new RegExp("^\\s*<!--\\s*#region\\b.*-->"), end: new RegExp("^\\s*<!--\\s*#endregion\\b.*-->") } } }, v = { defaultToken: "", tokenPostfix: ".html", ignoreCase: !0, tokenizer: { root: [[/<!DOCTYPE/, "metatag", "@doctype"], [/<!--/, "comment", "@comment"], [/(<)((?:[\w\-]+:)?[\w\-]+)(\s*)(\/>)/, ["delimiter", "tag", "", "delimiter"]], [/(<)(script)/, ["delimiter", { token: "tag", next: "@script" }]], [/(<)(style)/, ["delimiter", { token: "tag", next: "@style" }]], [/(<)((?:[\w\-]+:)?[\w\-]+)/, ["delimiter", { token: "tag", next: "@otherTag" }]], [/(<\/)((?:[\w\-]+:)?[\w\-]+)/, ["delimiter", { token: "tag", next: "@otherTag" }]], [/</, "delimiter"], [/[^<]+/]], doctype: [[/[^>]+/, "metatag.content"], [/>/, "metatag", "@pop"]], comment: [[/-->/, "comment", "@pop"], [/[^-]+/, "comment.content"], [/./, "comment.content"]], otherTag: [[/\/?>/, "delimiter", "@pop"], [/"([^"]*)"/, "attribute.value"], [/'([^']*)'/, "attribute.value"], [/[\w\-]+/, "attribute.name"], [/=/, "delimiter"], [/[ \t\r\n]+/]], script: [[/type/, "attribute.name", "@scriptAfterType"], [/"([^"]*)"/, "attribute.value"], [/'([^']*)'/, "attribute.value"], [/[\w\-]+/, "attribute.name"], [/=/, "delimiter"], [/>/, { token: "delimiter", next: "@scriptEmbedded", nextEmbedded: "text/javascript" }], [/[ \t\r\n]+/], [/(<\/)(script\s*)(>)/, ["delimiter", "tag", { token: "delimiter", next: "@pop" }]]], scriptAfterType: [[/=/, "delimiter", "@scriptAfterTypeEquals"], [/>/, { token: "delimiter", next: "@scriptEmbedded", nextEmbedded: "text/javascript" }], [/[ \t\r\n]+/], [/<\/script\s*>/, { token: "@rematch", next: "@pop" }]], scriptAfterTypeEquals: [[/"([^"]*)"/, { token: "attribute.value", switchTo: "@scriptWithCustomType.$1" }], [/'([^']*)'/, { token: "attribute.value", switchTo: "@scriptWithCustomType.$1" }], [/>/, { token: "delimiter", next: "@scriptEmbedded", nextEmbedded: "text/javascript" }], [/[ \t\r\n]+/], [/<\/script\s*>/, { token: "@rematch", next: "@pop" }]], scriptWithCustomType: [[/>/, { token: "delimiter", next: "@scriptEmbedded.$S2", nextEmbedded: "$S2" }], [/"([^"]*)"/, "attribute.value"], [/'([^']*)'/, "attribute.value"], [/[\w\-]+/, "attribute.name"], [/=/, "delimiter"], [/[ \t\r\n]+/], [/<\/script\s*>/, { token: "@rematch", next: "@pop" }]], scriptEmbedded: [[/<\/script/, { token: "@rematch", next: "@pop", nextEmbedded: "@pop" }], [/[^<]+/, ""]], style: [[/type/, "attribute.name", "@styleAfterType"], [/"([^"]*)"/, "attribute.value"], [/'([^']*)'/, "attribute.value"], [/[\w\-]+/, "attribute.name"], [/=/, "delimiter"], [/>/, { token: "delimiter", next: "@styleEmbedded", nextEmbedded: "text/css" }], [/[ \t\r\n]+/], [/(<\/)(style\s*)(>)/, ["delimiter", "tag", { token: "delimiter", next: "@pop" }]]], styleAfterType: [[/=/, "delimiter", "@styleAfterTypeEquals"], [/>/, { token: "delimiter", next: "@styleEmbedded", nextEmbedded: "text/css" }], [/[ \t\r\n]+/], [/<\/style\s*>/, { token: "@rematch", next: "@pop" }]], styleAfterTypeEquals: [[/"([^"]*)"/, { token: "attribute.value", switchTo: "@styleWithCustomType.$1" }], [/'([^']*)'/, { token: "attribute.value", switchTo: "@styleWithCustomType.$1" }], [/>/, { token: "delimiter", next: "@styleEmbedded", nextEmbedded: "text/css" }], [/[ \t\r\n]+/], [/<\/style\s*>/, { token: "@rematch", next: "@pop" }]], styleWithCustomType: [[/>/, { token: "delimiter", next: "@styleEmbedded.$S2", nextEmbedded: "$S2" }], [/"([^"]*)"/, "attribute.value"], [/'([^']*)'/, "attribute.value"], [/[\w\-]+/, "attribute.name"], [/=/, "delimiter"], [/[ \t\r\n]+/], [/<\/style\s*>/, { token: "@rematch", next: "@pop" }]], styleEmbedded: [[/<\/style/, { token: "@rematch", next: "@pop", nextEmbedded: "@pop" }], [/[^<]+/, ""]] } }; return T($); }(); return moduleExports; });
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es5-amd/node_modules/monaco-editor/min/vs/basic-languages/html/html.js
JavaScript
gpl-3.0
10,977
/* * linux/arch/unicore/include/mach/pm.h * * Code specific to PKUnity SoC and UniCore ISA * * Copyright (C) 2001-2010 GUAN Xue-tao * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __PUV3_PM_H__ #define __PUV3_PM_H__ #include <linux/suspend.h> struct puv3_cpu_pm_fns { int save_count; void (*save)(unsigned long *); void (*restore)(unsigned long *); int (*valid)(suspend_state_t state); void (*enter)(suspend_state_t state); int (*prepare)(void); void (*finish)(void); }; extern struct puv3_cpu_pm_fns *puv3_cpu_pm_fns; /* sleep.S */ extern void puv3_cpu_suspend(unsigned int); extern void puv3_cpu_resume(void); extern int puv3_pm_enter(suspend_state_t state); /* Defined in hibernate_asm.S */ extern int restore_image(pgd_t *resume_pg_dir, struct pbe *restore_pblist); extern struct pbe *restore_pblist; #endif
williamfdevine/PrettyLinux
arch/unicore32/include/mach/pm.h
C
gpl-3.0
986
package services import model.CurrencyConverter import org.jsoup.Jsoup import org.jsoup.nodes.Element import play.api.libs.functional.syntax._ import play.api.libs.json.{JsPath, Json, Reads, Writes} import scala.collection.immutable.Seq case class SteamEntry(name: String, steamId: Long, price: Option[BigDecimal] = None, discounted: Option[BigDecimal]= None, genres : String = "", tags : String = "", owned : Boolean) extends ShopEntry{ val link = s"http://store.steampowered.com/app/$steamId" override def id: Long = steamId override def title: String = name } object SteamEntry { private val regExp = "var rgGames = (.+);".r implicit val steamReads: Reads[SteamEntry] = ((JsPath \ "name").read[String] and (JsPath \ "appid").read[Long]) ((n, i) => SteamEntry(n, i, owned = true)) implicit val steamWrites: Writes[SteamEntry] = ( (JsPath \ "name").write[String] and (JsPath \ "steamId").write[Long] and (JsPath \ "link").write[String] and (JsPath \ "price" \ "normal").write[Option[BigDecimal]]and (JsPath \ "price" \ "discounted").write[Option[BigDecimal]] and (JsPath \ "genres").write[String] and (JsPath \ "tags").write[String]) ((e) => (e.name, e.steamId, e.link, e.price, e.discounted, e.genres, e.tags)) def parseGenresAndTags(page: String): (Option[String], Option[String]) = { import scala.collection.JavaConversions._ val detailsBlock = Jsoup.parse(page).getElementsByClass("block responsive_apppage_details_left game_details underlined_links").first() val genres = if (detailsBlock != null) { val allDetails = detailsBlock.getElementsByClass("details_block").first().children().toList.map(e => e.text()).filter(_.length() > 0) val genreIndex = allDetails.indexOf("Genre:") val devIndex = allDetails.indexOf("Developer:") if (genreIndex != -1 && devIndex > genreIndex) Some(allDetails.slice(genreIndex + 1, devIndex).mkString(",")) else None } else None val tagsBlock = Jsoup.parse(page).getElementsByClass("glance_tags_ctn popular_tags_ctn").first() val tags = if (tagsBlock != null) { Some(tagsBlock.getElementsByTag("a").toList.map(e => e.text()).mkString(",")) } else None (genres, tags) } def parse(owned: String, wishList : String, converter : CurrencyConverter): Seq[SteamEntry] = parseOwned(owned) ++ parseWishList(wishList, converter) private def parseWishList(wishList: String, converter: CurrencyConverter): Seq[SteamEntry] = { import scala.collection.JavaConversions._ val wItems = Jsoup.parse(wishList).getElementById("wishlist_items") if (wItems != null) { val items = wItems.getElementsByClass("wishlistRow").toList items.map(e => { val id = e.attr("id").split("_")(1) val name = e.getElementsByAttributeValue("class", "ellipsis").text() val (price, discounted) = getPrices(e) SteamEntry(name, id.toLong, price.flatMap(converter.convert), discounted.flatMap(converter.convert), owned = false) }) } else Seq() } private def getPrices(e: Element): (Option[String], Option[String]) = { val normalPrice = e.getElementsByClass("price").text() if (!normalPrice.isEmpty) (Some(normalPrice), None) else (Some(e.getElementsByClass("discount_original_price").text()), Some(e.getElementsByClass("discount_final_price").text())) } private def parseOwned(owned: String) = { Json.parse(regExp.findAllMatchIn(owned).map(m => m.group(1)).next()).validate[List[SteamEntry]].get } }
kongus99/Aggregator
app/services/SteamEntry.scala
Scala
gpl-3.0
3,579
/** * \file RMF/internal/SharedData.h * \brief Handle read/write of Model data from/to files. * * Copyright 2007-2017 IMP Inventors. All rights reserved. * */ #ifndef RMF_INTERNAL_BACKWARDS_IO_BASE_H #define RMF_INTERNAL_BACKWARDS_IO_BASE_H #include "RMF/config.h" #include "RMF/ID.h" #include "RMF/constants.h" RMF_ENABLE_WARNINGS namespace RMF { namespace backends { class BackwardsIOBase { std::string path_; FrameID loaded_frame_; public: BackwardsIOBase(std::string path) : path_(path) {} std::string get_file_path() const { return path_; } void set_loaded_frame(FrameID frame) { loaded_frame_ = frame; } FrameID get_loaded_frame() const { return loaded_frame_; } }; } // namespace internal } /* namespace RMF */ RMF_DISABLE_WARNINGS #endif /* RMF_INTERNAL_BACKWARDS_IO_BASE_H */
shanot/imp
modules/rmf/dependency/RMF/src/backend/BackwardsIOBase.h
C
gpl-3.0
817
/* banfunc.h -- extension functions for the pta program ban Rutger van Haasteren 15 August 2007 haasteren@strw.leidenuniv.nl Copyright (C) 2005-2007 Rutger van Haasteren. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, 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. */ // Minimum version of the configfile that is compatible with this release #define CONFIG_VERSION_MIN 0.20 // We want to be able to use the linal classes #include "linal.h" #include "config.h" #ifndef __BANFUNC_H__ #define __BANFUNC_H__ // Check were the definition of pi really is #ifndef PI #define PI 3.14159265358979323846264338327950288419716939937510 #endif #ifndef NSPERYEAR #define NSPERYEAR 31557600000000000.0 #define SPERYEAR 31557600.0 #endif // The dispersion constant in seconds #ifndef DM_K // #define DM_K 4.15e-3 // Units of Kj's paper (check these) #define DM_K 241.0 // GHz^-2 cm^-3 pc s^-1 #endif int KbHit(); bool BANFuncInitialize(int nProcessRank=0); // Initialise some constantes, functions and random numbers void InitProgressBar(const char *strMsg=NULL); void DrawProgressBar(int nPercent=0); void FinishProgressBar(); // For status report void PrintStatus(const char *str); void PrintFailed(); void PrintSuccess(); // For (MCMC) updates void PrintUpdate(const char *str); void FinishUpdate(); int n_min(int *pnArray, int nLength); double d_min(double *pdArray, int nLength); void d_swap(double &x, double &y); void QuickSort(double *pdBufferX, double *pdBufferY, double *pdBufferZ, double *pdBufferComp, int left, int right); void QuickSort(double *pdBuffer, int left, int right); void QuickSort(double **ppdBuffer, double *pdBufferZ, int nDimensions, int left, int right); // __BANFUNC_H__ #endif
vhaasteren/bang-legacy
src/banfunc.h
C
gpl-3.0
2,358
package net.minecraft.server; import java.util.ArrayList; import java.util.List; class PlayerInstance { private final List b; private final ChunkCoordIntPair location; private short[] dirtyBlocks; private int dirtyCount; private int f; final PlayerManager playerManager; public PlayerInstance(PlayerManager playermanager, int i, int j) { this.playerManager = playermanager; this.b = new ArrayList(); this.dirtyBlocks = new short[64]; this.dirtyCount = 0; this.location = new ChunkCoordIntPair(i, j); playermanager.a().chunkProviderServer.getChunkAt(i, j); } public void a(EntityPlayer entityplayer) { if (this.b.contains(entityplayer)) { throw new IllegalStateException("Failed to add player. " + entityplayer + " already is in chunk " + this.location.x + ", " + this.location.z); } else { this.b.add(entityplayer); entityplayer.chunkCoordIntPairQueue.add(this.location); } } public void b(EntityPlayer entityplayer) { if (this.b.contains(entityplayer)) { entityplayer.netServerHandler.sendPacket(new Packet51MapChunk(PlayerManager.a(this.playerManager).getChunkAt(this.location.x, this.location.z), true, 0)); this.b.remove(entityplayer); entityplayer.chunkCoordIntPairQueue.remove(this.location); if (this.b.isEmpty()) { long i = (long) this.location.x + 2147483647L | (long) this.location.z + 2147483647L << 32; PlayerManager.b(this.playerManager).remove(i); if (this.dirtyCount > 0) { PlayerManager.c(this.playerManager).remove(this); } this.playerManager.a().chunkProviderServer.queueUnload(this.location.x, this.location.z); } } } public void a(int i, int j, int k) { if (this.dirtyCount == 0) { PlayerManager.c(this.playerManager).add(this); } this.f |= 1 << (j >> 4); if (this.dirtyCount < 64) { short short1 = (short) (i << 12 | k << 8 | j); for (int l = 0; l < this.dirtyCount; ++l) { if (this.dirtyBlocks[l] == short1) { return; } } this.dirtyBlocks[this.dirtyCount++] = short1; } } public void sendAll(Packet packet) { for (int i = 0; i < this.b.size(); ++i) { EntityPlayer entityplayer = (EntityPlayer) this.b.get(i); if (!entityplayer.chunkCoordIntPairQueue.contains(this.location)) { entityplayer.netServerHandler.sendPacket(packet); } } } public void a() { if (this.dirtyCount != 0) { int i; int j; int k; if (this.dirtyCount == 1) { i = this.location.x * 16 + (this.dirtyBlocks[0] >> 12 & 15); j = this.dirtyBlocks[0] & 255; k = this.location.z * 16 + (this.dirtyBlocks[0] >> 8 & 15); this.sendAll(new Packet53BlockChange(i, j, k, PlayerManager.a(this.playerManager))); if (PlayerManager.a(this.playerManager).isTileEntity(i, j, k)) { this.sendTileEntity(PlayerManager.a(this.playerManager).getTileEntity(i, j, k)); } } else { int l; if (this.dirtyCount == 64) { i = this.location.x * 16; j = this.location.z * 16; this.sendAll(new Packet51MapChunk(PlayerManager.a(this.playerManager).getChunkAt(this.location.x, this.location.z), (this.f == 0xFFFF), this.f)); // CraftBukkit - send everything (including biome) if all sections flagged for (k = 0; k < 16; ++k) { if ((this.f & 1 << k) != 0) { l = k << 4; List list = PlayerManager.a(this.playerManager).getTileEntities(i, l, j, i + 16, l + 16, j + 16); for (int i1 = 0; i1 < list.size(); ++i1) { this.sendTileEntity((TileEntity) list.get(i1)); } } } } else { this.sendAll(new Packet52MultiBlockChange(this.location.x, this.location.z, this.dirtyBlocks, this.dirtyCount, PlayerManager.a(this.playerManager))); for (i = 0; i < this.dirtyCount; ++i) { j = this.location.x * 16 + (this.dirtyBlocks[i] >> 12 & 15); k = this.dirtyBlocks[i] & 255; l = this.location.z * 16 + (this.dirtyBlocks[i] >> 8 & 15); if (PlayerManager.a(this.playerManager).isTileEntity(j, k, l)) { this.sendTileEntity(PlayerManager.a(this.playerManager).getTileEntity(j, k, l)); } } } } this.dirtyCount = 0; this.f = 0; } } private void sendTileEntity(TileEntity tileentity) { if (tileentity != null) { Packet packet = tileentity.getUpdatePacket(); if (packet != null) { this.sendAll(packet); } } } static ChunkCoordIntPair a(PlayerInstance playerinstance) { return playerinstance.location; } static List b(PlayerInstance playerinstance) { return playerinstance.b; } }
Betterverse/Craftbukkit
src/main/java/net/minecraft/server/PlayerInstance.java
Java
gpl-3.0
5,606
/* ** v_palette.cpp ** Automatic colormap generation for "colored lights", etc. ** **--------------------------------------------------------------------------- ** Copyright 1998-2006 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #include <stddef.h> #include <string.h> #include <math.h> #include <float.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #define O_BINARY 0 #endif #include <fcntl.h> #include "templates.h" #include "v_video.h" #include "i_system.h" #include "w_wad.h" #include "i_video.h" #include "c_dispatch.h" #include "g_level.h" #include "st_stuff.h" #include "gi.h" #include "x86.h" #include "colormatcher.h" #include "v_palette.h" #include "g_levellocals.h" #include "r_data/colormaps.h" FPalette GPalette; FColorMatcher ColorMatcher; /* Current color blending values */ int BlendR, BlendG, BlendB, BlendA; static int sortforremap (const void *a, const void *b); static int sortforremap2 (const void *a, const void *b); /**************************/ /* Gamma correction stuff */ /**************************/ BYTE newgamma[256]; CUSTOM_CVAR (Float, Gamma, 1.f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self == 0.f) { // Gamma values of 0 are illegal. self = 1.f; return; } if (screen != NULL) { screen->SetGamma (self); } } CCMD (bumpgamma) { // [RH] Gamma correction tables are now generated // on the fly for *any* gamma level. // Q: What are reasonable limits to use here? float newgamma = Gamma + 0.1f; if (newgamma > 3.0) newgamma = 1.0; Gamma = newgamma; Printf ("Gamma correction level %g\n", *Gamma); } /****************************/ /* Palette management stuff */ /****************************/ int BestColor (const uint32 *pal_in, int r, int g, int b, int first, int num) { const PalEntry *pal = (const PalEntry *)pal_in; int bestcolor = first; int bestdist = 257 * 257 + 257 * 257 + 257 * 257; for (int color = first; color < num; color++) { int x = r - pal[color].r; int y = g - pal[color].g; int z = b - pal[color].b; int dist = x*x + y*y + z*z; if (dist < bestdist) { if (dist == 0) return color; bestdist = dist; bestcolor = color; } } return bestcolor; } FPalette::FPalette () { } FPalette::FPalette (const BYTE *colors) { SetPalette (colors); } void FPalette::SetPalette (const BYTE *colors) { for (int i = 0; i < 256; i++, colors += 3) { BaseColors[i] = PalEntry (colors[0], colors[1], colors[2]); Remap[i] = i; } // Find white and black from the original palette so that they can be // used to make an educated guess of the translucency % for a BOOM // translucency map. WhiteIndex = BestColor ((DWORD *)BaseColors, 255, 255, 255, 0, 255); BlackIndex = BestColor ((DWORD *)BaseColors, 0, 0, 0, 0, 255); } // In ZDoom's new texture system, color 0 is used as the transparent color. // But color 0 is also a valid color for Doom engine graphics. What to do? // Simple. The default palette for every game has at least one duplicate // color, so find a duplicate pair of palette entries, make one of them a // duplicate of color 0, and remap every graphic so that it uses that entry // instead of entry 0. void FPalette::MakeGoodRemap () { PalEntry color0 = BaseColors[0]; int i; // First try for an exact match of color 0. Only Hexen does not have one. for (i = 1; i < 256; ++i) { if (BaseColors[i] == color0) { Remap[0] = i; break; } } // If there is no duplicate of color 0, find the first set of duplicate // colors and make one of them a duplicate of color 0. In Hexen's PLAYPAL // colors 209 and 229 are the only duplicates, but we cannot assume // anything because the player might be using a custom PLAYPAL where those // entries are not duplicates. if (Remap[0] == 0) { PalEntry sortcopy[256]; for (i = 0; i < 256; ++i) { sortcopy[i] = BaseColors[i] | (i << 24); } qsort (sortcopy, 256, 4, sortforremap); for (i = 255; i > 0; --i) { if ((sortcopy[i] & 0xFFFFFF) == (sortcopy[i-1] & 0xFFFFFF)) { int new0 = sortcopy[i].a; int dup = sortcopy[i-1].a; if (new0 > dup) { // Make the lower-numbered entry a copy of color 0. (Just because.) swapvalues (new0, dup); } Remap[0] = new0; Remap[new0] = dup; BaseColors[new0] = color0; break; } } } // If there were no duplicates, InitPalette() will remap color 0 to the // closest matching color. Hopefully nobody will use a palette where all // 256 entries are different. :-) } static int sortforremap (const void *a, const void *b) { return (*(const DWORD *)a & 0xFFFFFF) - (*(const DWORD *)b & 0xFFFFFF); } struct RemappingWork { DWORD Color; BYTE Foreign; // 0 = local palette, 1 = foreign palette BYTE PalEntry; // Entry # in the palette BYTE Pad[2]; }; void FPalette::MakeRemap (const DWORD *colors, BYTE *remap, const BYTE *useful, int numcolors) const { RemappingWork workspace[255+256]; int i, j, k; // Fill in workspace with the colors from the passed palette and this palette. // By sorting this array, we can quickly find exact matches so that we can // minimize the time spent calling BestColor for near matches. for (i = 1; i < 256; ++i) { workspace[i-1].Color = DWORD(BaseColors[i]) & 0xFFFFFF; workspace[i-1].Foreign = 0; workspace[i-1].PalEntry = i; } for (i = k = 0, j = 255; i < numcolors; ++i) { if (useful == NULL || useful[i] != 0) { workspace[j].Color = colors[i] & 0xFFFFFF; workspace[j].Foreign = 1; workspace[j].PalEntry = i; ++j; ++k; } else { remap[i] = 0; } } qsort (workspace, j, sizeof(RemappingWork), sortforremap2); // Find exact matches --j; for (i = 0; i < j; ++i) { if (workspace[i].Foreign) { if (!workspace[i+1].Foreign && workspace[i].Color == workspace[i+1].Color) { remap[workspace[i].PalEntry] = workspace[i+1].PalEntry; workspace[i].Foreign = 2; ++i; --k; } } } // Find near matches if (k > 0) { for (i = 0; i <= j; ++i) { if (workspace[i].Foreign == 1) { remap[workspace[i].PalEntry] = BestColor ((DWORD *)BaseColors, RPART(workspace[i].Color), GPART(workspace[i].Color), BPART(workspace[i].Color), 1, 255); } } } } static int sortforremap2 (const void *a, const void *b) { const RemappingWork *ap = (const RemappingWork *)a; const RemappingWork *bp = (const RemappingWork *)b; if (ap->Color == bp->Color) { return bp->Foreign - ap->Foreign; } else { return ap->Color - bp->Color; } } static bool FixBuildPalette (BYTE *opal, int lump, bool blood) { if (Wads.LumpLength (lump) < 768) { return false; } FMemLump data = Wads.ReadLump (lump); const BYTE *ipal = (const BYTE *)data.GetMem(); // Reverse the palette because BUILD used entry 255 as // transparent, but we use 0 as transparent. for (int c = 0; c < 768; c += 3) { if (!blood) { opal[c] = (ipal[765-c] << 2) | (ipal[765-c] >> 4); opal[c+1] = (ipal[766-c] << 2) | (ipal[766-c] >> 4); opal[c+2] = (ipal[767-c] << 2) | (ipal[767-c] >> 4); } else { opal[c] = ipal[765-c]; opal[c+1] = ipal[766-c]; opal[c+2] = ipal[767-c]; } } return true; } void InitPalette () { BYTE pal[768]; bool usingBuild = false; int lump; if ((lump = Wads.CheckNumForFullName ("palette.dat")) >= 0 && Wads.LumpLength (lump) >= 768) { usingBuild = FixBuildPalette (pal, lump, false); } else if ((lump = Wads.CheckNumForFullName ("blood.pal")) >= 0 && Wads.LumpLength (lump) >= 768) { usingBuild = FixBuildPalette (pal, lump, true); } if (!usingBuild) { FWadLump palump = Wads.OpenLumpName ("PLAYPAL"); palump.Read (pal, 768); } GPalette.SetPalette (pal); GPalette.MakeGoodRemap (); ColorMatcher.SetPalette ((DWORD *)GPalette.BaseColors); // The BUILD engine already has a transparent color, so it doesn't need any remapping. if (!usingBuild) { if (GPalette.Remap[0] == 0) { // No duplicates, so settle for something close to color 0 GPalette.Remap[0] = BestColor ((DWORD *)GPalette.BaseColors, GPalette.BaseColors[0].r, GPalette.BaseColors[0].g, GPalette.BaseColors[0].b, 1, 255); } } // Colormaps have to be initialized before actors are loaded, // otherwise Powerup.Colormap will not work. R_InitColormaps (); } void DoBlending_MMX (const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a); void DoBlending_SSE2 (const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a); void DoBlending (const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a) { if (a == 0) { if (from != to) { memcpy (to, from, count * sizeof(DWORD)); } return; } else if (a == 256) { DWORD t = MAKERGB(r,g,b); int i; for (i = 0; i < count; i++) { to[i] = t; } return; } #if defined(_M_X64) || defined(_M_IX86) || defined(__i386__) || defined(__amd64__) else if (CPU.bSSE2) { if (count >= 4) { int not3count = count & ~3; DoBlending_SSE2 (from, to, not3count, r, g, b, a); count &= 3; if (count <= 0) { return; } from += not3count; to += not3count; } } #endif #if defined(_M_IX86) || defined(__i386__) else if (CPU.bMMX) { if (count >= 4) { int not3count = count & ~3; DoBlending_MMX (from, to, not3count, r, g, b, a); count &= 3; if (count <= 0) { return; } from += not3count; to += not3count; } } #endif int i, ia; ia = 256 - a; r *= a; g *= a; b *= a; for (i = count; i > 0; i--, to++, from++) { to->r = (r + from->r * ia) >> 8; to->g = (g + from->g * ia) >> 8; to->b = (b + from->b * ia) >> 8; } } void V_SetBlend (int blendr, int blendg, int blendb, int blenda) { // Don't do anything if the new blend is the same as the old if (((blenda|BlendA) == 0) || (blendr == BlendR && blendg == BlendG && blendb == BlendB && blenda == BlendA)) return; V_ForceBlend (blendr, blendg, blendb, blenda); } void V_ForceBlend (int blendr, int blendg, int blendb, int blenda) { BlendR = blendr; BlendG = blendg; BlendB = blendb; BlendA = blenda; screen->SetFlash (PalEntry (BlendR, BlendG, BlendB), BlendA); } CCMD (testblend) { FString colorstring; int color; float amt; if (argv.argc() < 3) { Printf ("testblend <color> <amount>\n"); } else { if ( !(colorstring = V_GetColorStringByName (argv[1])).IsEmpty() ) { color = V_GetColorFromString (NULL, colorstring); } else { color = V_GetColorFromString (NULL, argv[1]); } amt = (float)atof (argv[2]); if (amt > 1.0f) amt = 1.0f; else if (amt < 0.0f) amt = 0.0f; BaseBlendR = RPART(color); BaseBlendG = GPART(color); BaseBlendB = BPART(color); BaseBlendA = amt; } } CCMD (testfade) { FString colorstring; DWORD color; if (argv.argc() < 2) { Printf ("testfade <color>\n"); } else { if ( !(colorstring = V_GetColorStringByName (argv[1])).IsEmpty() ) { color = V_GetColorFromString (NULL, colorstring); } else { color = V_GetColorFromString (NULL, argv[1]); } level.fadeto = color; NormalLight.ChangeFade (color); } } /****** Colorspace Conversion Functions ******/ // Code from http://www.cs.rit.edu/~yxv4997/t_convert.html // r,g,b values are from 0 to 1 // h = [0,360], s = [0,1], v = [0,1] // if s == 0, then h = -1 (undefined) // Green Doom guy colors: // RGB - 0: { .46 1 .429 } 7: { .254 .571 .206 } 15: { .0317 .0794 .0159 } // HSV - 0: { 116.743 .571 1 } 7: { 112.110 .639 .571 } 15: { 105.071 .800 .0794 } void RGBtoHSV (float r, float g, float b, float *h, float *s, float *v) { float min, max, delta, foo; if (r == g && g == b) { *h = 0; *s = 0; *v = r; return; } foo = r < g ? r : g; min = (foo < b) ? foo : b; foo = r > g ? r : g; max = (foo > b) ? foo : b; *v = max; // v delta = max - min; *s = delta / max; // s if (r == max) *h = (g - b) / delta; // between yellow & magenta else if (g == max) *h = 2 + (b - r) / delta; // between cyan & yellow else *h = 4 + (r - g) / delta; // between magenta & cyan *h *= 60; // degrees if (*h < 0) *h += 360; } void HSVtoRGB (float *r, float *g, float *b, float h, float s, float v) { int i; float f, p, q, t; if (s == 0) { // achromatic (grey) *r = *g = *b = v; return; } h /= 60; // sector 0 to 5 i = (int)floor (h); f = h - i; // factorial part of h p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch (i) { case 0: *r = v; *g = t; *b = p; break; case 1: *r = q; *g = v; *b = p; break; case 2: *r = p; *g = v; *b = t; break; case 3: *r = p; *g = q; *b = v; break; case 4: *r = t; *g = p; *b = v; break; default: *r = v; *g = p; *b = q; break; } } CCMD (testcolor) { FString colorstring; DWORD color; int desaturate; if (argv.argc() < 2) { Printf ("testcolor <color> [desaturation]\n"); } else { if ( !(colorstring = V_GetColorStringByName (argv[1])).IsEmpty() ) { color = V_GetColorFromString (NULL, colorstring); } else { color = V_GetColorFromString (NULL, argv[1]); } if (argv.argc() > 2) { desaturate = atoi (argv[2]); } else { desaturate = NormalLight.Desaturate; } NormalLight.ChangeColor (color, desaturate); } }
Saican/Whitman
src/v_palette.cpp
C++
gpl-3.0
14,656
#! /bin/false # vim: set autoindent shiftwidth=4 tabstop=4: # $Id: IBM918.pm,v 1.1 2009/11/01 19:00:08 pertusus Exp $ # Conversion routines for IBM918. # Copyright (C) 2002-2009 Guido Flohr <guido@imperia.net>, all # rights reserved. # This file is generated, do not edit! # This program 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, 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 # Library General Public License for more details. # You should have received a copy of the GNU Library 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. package Locale::RecodeData::IBM918; use strict; require Locale::RecodeData; use base qw(Locale::RecodeData); my @to_ucs4 = ( 0x0000, 0x0001, 0x0002, 0x0003, 0x009c, 0x0009, 0x0086, 0x007f, 0x0097, 0x008d, 0x008e, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x009d, 0x0085, 0x0008, 0x0087, 0x0018, 0x0019, 0x0092, 0x008f, 0x001c, 0x001d, 0x001e, 0x001f, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x000a, 0x0017, 0x001b, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x0005, 0x0006, 0x0007, 0x0090, 0x0091, 0x0016, 0x0093, 0x0094, 0x0095, 0x0096, 0x0004, 0x0098, 0x0099, 0x009a, 0x009b, 0x0014, 0x0015, 0x009e, 0x001a, 0x0020, 0x00a0, 0x060c, 0x061b, 0x061f, 0x0623, 0x0627, 0xfe8e, 0xfffd, 0x0628, 0x005b, 0x002e, 0x003c, 0x0028, 0x002b, 0x0021, 0x0026, 0xfe91, 0x067e, 0xfffd, 0x0629, 0x062a, 0xfe97, 0xfffd, 0xfffd, 0x062b, 0x005d, 0x0024, 0x002a, 0x0029, 0x003b, 0x005e, 0x002d, 0x002f, 0xfe9b, 0x062c, 0xfe9f, 0xfffd, 0xfffd, 0x062d, 0xfea3, 0x062e, 0x0060, 0x002c, 0x0025, 0x005f, 0x003e, 0x003f, 0x0660, 0x0661, 0x0662, 0x0663, 0x0664, 0x0665, 0x0666, 0x0667, 0x0668, 0x0669, 0x003a, 0x0023, 0x0040, 0x0027, 0x003d, 0x0022, 0xfea7, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x062f, 0xfffd, 0x0630, 0x0631, 0xfffd, 0x0632, 0xfffd, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0633, 0xfeb3, 0x0634, 0xfeb7, 0x0635, 0xfebb, 0x0636, 0x007e, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0xfebf, 0x0637, 0x0638, 0x0639, 0xfeca, 0xfecb, 0xfecc, 0x063a, 0xfece, 0xfecf, 0xfed0, 0x0641, 0xfed3, 0x0642, 0xfed7, 0x0643, 0xfedb, 0x007c, 0xfffd, 0xfffd, 0x0644, 0xfede, 0x007b, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x00ad, 0xfffd, 0x0645, 0xfee3, 0xfffd, 0x0646, 0x007d, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0xfee7, 0xfffd, 0x0648, 0xfffd, 0xfffd, 0xfffd, 0x005c, 0xfffd, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x0621, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0xfffd, 0xfffd, 0xfffd, 0x0651, 0xfe7d, 0x009f, ); my @to_utf8 = ( "\x00", "\x01", "\x02", "\x03", "\xc2\x9c", "\x09", "\xc2\x86", "\x7f", "\xc2\x97", "\xc2\x8d", "\xc2\x8e", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f", "\x10", "\x11", "\x12", "\x13", "\xc2\x9d", "\xc2\x85", "\x08", "\xc2\x87", "\x18", "\x19", "\xc2\x92", "\xc2\x8f", "\x1c", "\x1d", "\x1e", "\x1f", "\xc2\x80", "\xc2\x81", "\xc2\x82", "\xc2\x83", "\xc2\x84", "\x0a", "\x17", "\x1b", "\xc2\x88", "\xc2\x89", "\xc2\x8a", "\xc2\x8b", "\xc2\x8c", "\x05", "\x06", "\x07", "\xc2\x90", "\xc2\x91", "\x16", "\xc2\x93", "\xc2\x94", "\xc2\x95", "\xc2\x96", "\x04", "\xc2\x98", "\xc2\x99", "\xc2\x9a", "\xc2\x9b", "\x14", "\x15", "\xc2\x9e", "\x1a", "\x20", "\xc2\xa0", "\xd8\x8c", "\xd8\x9b", "\xd8\x9f", "\xd8\xa3", "\xd8\xa7", "\xef\xba\x8e", "\xef\xbf\xbd", "\xd8\xa8", "\x5b", "\x2e", "\x3c", "\x28", "\x2b", "\x21", "\x26", "\xef\xba\x91", "\xd9\xbe", "\xef\xbf\xbd", "\xd8\xa9", "\xd8\xaa", "\xef\xba\x97", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xd8\xab", "\x5d", "\x24", "\x2a", "\x29", "\x3b", "\x5e", "\x2d", "\x2f", "\xef\xba\x9b", "\xd8\xac", "\xef\xba\x9f", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xd8\xad", "\xef\xba\xa3", "\xd8\xae", "\x60", "\x2c", "\x25", "\x5f", "\x3e", "\x3f", "\xd9\xa0", "\xd9\xa1", "\xd9\xa2", "\xd9\xa3", "\xd9\xa4", "\xd9\xa5", "\xd9\xa6", "\xd9\xa7", "\xd9\xa8", "\xd9\xa9", "\x3a", "\x23", "\x40", "\x27", "\x3d", "\x22", "\xef\xba\xa7", "\x61", "\x62", "\x63", "\x64", "\x65", "\x66", "\x67", "\x68", "\x69", "\xd8\xaf", "\xef\xbf\xbd", "\xd8\xb0", "\xd8\xb1", "\xef\xbf\xbd", "\xd8\xb2", "\xef\xbf\xbd", "\x6a", "\x6b", "\x6c", "\x6d", "\x6e", "\x6f", "\x70", "\x71", "\x72", "\xd8\xb3", "\xef\xba\xb3", "\xd8\xb4", "\xef\xba\xb7", "\xd8\xb5", "\xef\xba\xbb", "\xd8\xb6", "\x7e", "\x73", "\x74", "\x75", "\x76", "\x77", "\x78", "\x79", "\x7a", "\xef\xba\xbf", "\xd8\xb7", "\xd8\xb8", "\xd8\xb9", "\xef\xbb\x8a", "\xef\xbb\x8b", "\xef\xbb\x8c", "\xd8\xba", "\xef\xbb\x8e", "\xef\xbb\x8f", "\xef\xbb\x90", "\xd9\x81", "\xef\xbb\x93", "\xd9\x82", "\xef\xbb\x97", "\xd9\x83", "\xef\xbb\x9b", "\x7c", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xd9\x84", "\xef\xbb\x9e", "\x7b", "\x41", "\x42", "\x43", "\x44", "\x45", "\x46", "\x47", "\x48", "\x49", "\xc2\xad", "\xef\xbf\xbd", "\xd9\x85", "\xef\xbb\xa3", "\xef\xbf\xbd", "\xd9\x86", "\x7d", "\x4a", "\x4b", "\x4c", "\x4d", "\x4e", "\x4f", "\x50", "\x51", "\x52", "\xef\xbb\xa7", "\xef\xbf\xbd", "\xd9\x88", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\x5c", "\xef\xbf\xbd", "\x53", "\x54", "\x55", "\x56", "\x57", "\x58", "\x59", "\x5a", "\xd8\xa1", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\x30", "\x31", "\x32", "\x33", "\x34", "\x35", "\x36", "\x37", "\x38", "\x39", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xd9\x91", "\xef\xb9\xbd", "\xc2\x9f", ); my %from_ucs4 = ( 0x00000000 => "\x00", 0x00000001 => "\x01", 0x00000002 => "\x02", 0x00000003 => "\x03", 0x00000004 => "\x37", 0x00000005 => "\x2d", 0x00000006 => "\x2e", 0x00000007 => "\x2f", 0x00000008 => "\x16", 0x00000009 => "\x05", 0x0000000a => "\x25", 0x0000000b => "\x0b", 0x0000000c => "\x0c", 0x0000000d => "\x0d", 0x0000000e => "\x0e", 0x0000000f => "\x0f", 0x00000010 => "\x10", 0x00000011 => "\x11", 0x00000012 => "\x12", 0x00000013 => "\x13", 0x00000014 => "\x3c", 0x00000015 => "\x3d", 0x00000016 => "\x32", 0x00000017 => "\x26", 0x00000018 => "\x18", 0x00000019 => "\x19", 0x0000001a => "\x3f", 0x0000001b => "\x27", 0x0000001c => "\x1c", 0x0000001d => "\x1d", 0x0000001e => "\x1e", 0x0000001f => "\x1f", 0x00000020 => "\x40", 0x00000021 => "\x4f", 0x00000022 => "\x7f", 0x00000023 => "\x7b", 0x00000024 => "\x5b", 0x00000025 => "\x6c", 0x00000026 => "\x50", 0x00000027 => "\x7d", 0x00000028 => "\x4d", 0x00000029 => "\x5d", 0x0000002a => "\x5c", 0x0000002b => "\x4e", 0x0000002c => "\x6b", 0x0000002d => "\x60", 0x0000002e => "\x4b", 0x0000002f => "\x61", 0x00000030 => "\xf0", 0x00000031 => "\xf1", 0x00000032 => "\xf2", 0x00000033 => "\xf3", 0x00000034 => "\xf4", 0x00000035 => "\xf5", 0x00000036 => "\xf6", 0x00000037 => "\xf7", 0x00000038 => "\xf8", 0x00000039 => "\xf9", 0x0000003a => "\x7a", 0x0000003b => "\x5e", 0x0000003c => "\x4c", 0x0000003d => "\x7e", 0x0000003e => "\x6e", 0x0000003f => "\x6f", 0x00000040 => "\x7c", 0x00000041 => "\xc1", 0x00000042 => "\xc2", 0x00000043 => "\xc3", 0x00000044 => "\xc4", 0x00000045 => "\xc5", 0x00000046 => "\xc6", 0x00000047 => "\xc7", 0x00000048 => "\xc8", 0x00000049 => "\xc9", 0x0000004a => "\xd1", 0x0000004b => "\xd2", 0x0000004c => "\xd3", 0x0000004d => "\xd4", 0x0000004e => "\xd5", 0x0000004f => "\xd6", 0x00000050 => "\xd7", 0x00000051 => "\xd8", 0x00000052 => "\xd9", 0x00000053 => "\xe2", 0x00000054 => "\xe3", 0x00000055 => "\xe4", 0x00000056 => "\xe5", 0x00000057 => "\xe6", 0x00000058 => "\xe7", 0x00000059 => "\xe8", 0x0000005a => "\xe9", 0x0000005b => "\x4a", 0x0000005c => "\xe0", 0x0000005d => "\x5a", 0x0000005e => "\x5f", 0x0000005f => "\x6d", 0x00000060 => "\x6a", 0x00000061 => "\x81", 0x00000062 => "\x82", 0x00000063 => "\x83", 0x00000064 => "\x84", 0x00000065 => "\x85", 0x00000066 => "\x86", 0x00000067 => "\x87", 0x00000068 => "\x88", 0x00000069 => "\x89", 0x0000006a => "\x91", 0x0000006b => "\x92", 0x0000006c => "\x93", 0x0000006d => "\x94", 0x0000006e => "\x95", 0x0000006f => "\x96", 0x00000070 => "\x97", 0x00000071 => "\x98", 0x00000072 => "\x99", 0x00000073 => "\xa2", 0x00000074 => "\xa3", 0x00000075 => "\xa4", 0x00000076 => "\xa5", 0x00000077 => "\xa6", 0x00000078 => "\xa7", 0x00000079 => "\xa8", 0x0000007a => "\xa9", 0x0000007b => "\xc0", 0x0000007c => "\xbb", 0x0000007d => "\xd0", 0x0000007e => "\xa1", 0x0000007f => "\x07", 0x00000080 => "\x20", 0x00000081 => "\x21", 0x00000082 => "\x22", 0x00000083 => "\x23", 0x00000084 => "\x24", 0x00000085 => "\x15", 0x00000086 => "\x06", 0x00000087 => "\x17", 0x00000088 => "\x28", 0x00000089 => "\x29", 0x0000008a => "\x2a", 0x0000008b => "\x2b", 0x0000008c => "\x2c", 0x0000008d => "\x09", 0x0000008e => "\x0a", 0x0000008f => "\x1b", 0x00000090 => "\x30", 0x00000091 => "\x31", 0x00000092 => "\x1a", 0x00000093 => "\x33", 0x00000094 => "\x34", 0x00000095 => "\x35", 0x00000096 => "\x36", 0x00000097 => "\x08", 0x00000098 => "\x38", 0x00000099 => "\x39", 0x0000009a => "\x3a", 0x0000009b => "\x3b", 0x0000009c => "\x04", 0x0000009d => "\x14", 0x0000009e => "\x3e", 0x0000009f => "\xff", 0x000000a0 => "\x41", 0x000000ad => "\xca", 0x0000060c => "\x42", 0x0000061b => "\x43", 0x0000061f => "\x44", 0x00000621 => "\xea", 0x00000623 => "\x45", 0x00000627 => "\x46", 0x00000628 => "\x49", 0x00000629 => "\x54", 0x0000062a => "\x55", 0x0000062b => "\x59", 0x0000062c => "\x63", 0x0000062d => "\x67", 0x0000062e => "\x69", 0x0000062f => "\x8a", 0x00000630 => "\x8c", 0x00000631 => "\x8d", 0x00000632 => "\x8f", 0x00000633 => "\x9a", 0x00000634 => "\x9c", 0x00000635 => "\x9e", 0x00000636 => "\xa0", 0x00000637 => "\xab", 0x00000638 => "\xac", 0x00000639 => "\xad", 0x0000063a => "\xb1", 0x00000641 => "\xb5", 0x00000642 => "\xb7", 0x00000643 => "\xb9", 0x00000644 => "\xbe", 0x00000645 => "\xcc", 0x00000646 => "\xcf", 0x00000648 => "\xdc", 0x00000651 => "\xfd", 0x00000660 => "\x70", 0x00000661 => "\x71", 0x00000662 => "\x72", 0x00000663 => "\x73", 0x00000664 => "\x74", 0x00000665 => "\x75", 0x00000666 => "\x76", 0x00000667 => "\x77", 0x00000668 => "\x78", 0x00000669 => "\x79", 0x0000067e => "\x52", 0x0000fe7d => "\xfe", 0x0000fe8e => "\x47", 0x0000fe91 => "\x51", 0x0000fe97 => "\x56", 0x0000fe9b => "\x62", 0x0000fe9f => "\x64", 0x0000fea3 => "\x68", 0x0000fea7 => "\x80", 0x0000feb3 => "\x9b", 0x0000feb7 => "\x9d", 0x0000febb => "\x9f", 0x0000febf => "\xaa", 0x0000feca => "\xae", 0x0000fecb => "\xaf", 0x0000fecc => "\xb0", 0x0000fece => "\xb2", 0x0000fecf => "\xb3", 0x0000fed0 => "\xb4", 0x0000fed3 => "\xb6", 0x0000fed7 => "\xb8", 0x0000fedb => "\xba", 0x0000fede => "\xbf", 0x0000fee3 => "\xcd", 0x0000fee7 => "\xda", ); sub _recode { if ($_[0]->{_from} eq 'INTERNAL') { $_[1] = join '', map $from_ucs4{$_} || (defined $from_ucs4{$_} ? $from_ucs4{$_} : "\x6f"), @{$_[1]}; } elsif ($_[0]->{_to} eq 'UTF-8',) { $_[1] = join '', map $to_utf8[$_], unpack 'C*', $_[1]; } else { $_[1] = [ map $to_ucs4[$_], unpack 'C*', $_[1] ]; } return 1; } 1; __END__ =head1 NAME Locale::RecodeData::IBM918 - Conversion routines for IBM918 =head1 SYNOPSIS This module is internal to libintl. Do not use directly! =head1 DESCRIPTION This module is generated and contains the conversion tables and routines for IBM918. =head1 COMMENTS The following comments have been extracted from the original charmap: version: 1.0 source: IBM NLS RM Vol2 SE09-8002-01, March 1990 alias CP918 alias EBCDIC-CP-AR2 Please note that aliases listed above are not necessarily valid! =head1 CHARACTER TABLE The following table is sorted in the same order as the original charmap. All character codes are in hexadecimal. Please read 'ISO-10646' as 'ISO-10646-UCS4'. Local | ISO-10646 | Description -------+-----------+------------------------------------------------- 00 | 00000000 | NULL (NUL) 01 | 00000001 | START OF HEADING (SOH) 02 | 00000002 | START OF TEXT (STX) 03 | 00000003 | END OF TEXT (ETX) 04 | 0000009C | STRING TERMINATOR (ST) 05 | 00000009 | CHARACTER TABULATION (HT) 06 | 00000086 | START OF SELECTED AREA (SSA) 07 | 0000007F | DELETE (DEL) 08 | 00000097 | END OF GUARDED AREA (EPA) 09 | 0000008D | REVERSE LINE FEED (RI) 0A | 0000008E | SINGLE-SHIFT TWO (SS2) 0B | 0000000B | LINE TABULATION (VT) 0C | 0000000C | FORM FEED (FF) 0D | 0000000D | CARRIAGE RETURN (CR) 0E | 0000000E | SHIFT OUT (SO) 0F | 0000000F | SHIFT IN (SI) 10 | 00000010 | DATALINK ESCAPE (DLE) 11 | 00000011 | DEVICE CONTROL ONE (DC1) 12 | 00000012 | DEVICE CONTROL TWO (DC2) 13 | 00000013 | DEVICE CONTROL THREE (DC3) 14 | 0000009D | OPERATING SYSTEM COMMAND (OSC) 15 | 00000085 | NEXT LINE (NEL) 16 | 00000008 | BACKSPACE (BS) 17 | 00000087 | END OF SELECTED AREA (ESA) 18 | 00000018 | CANCEL (CAN) 19 | 00000019 | END OF MEDIUM (EM) 1A | 00000092 | PRIVATE USE TWO (PU2) 1B | 0000008F | SINGLE-SHIFT THREE (SS3) 1C | 0000001C | FILE SEPARATOR (IS4) 1D | 0000001D | GROUP SEPARATOR (IS3) 1E | 0000001E | RECORD SEPARATOR (IS2) 1F | 0000001F | UNIT SEPARATOR (IS1) 20 | 00000080 | PADDING CHARACTER (PAD) 21 | 00000081 | HIGH OCTET PRESET (HOP) 22 | 00000082 | BREAK PERMITTED HERE (BPH) 23 | 00000083 | NO BREAK HERE (NBH) 24 | 00000084 | INDEX (IND) 25 | 0000000A | LINE FEED (LF) 26 | 00000017 | END OF TRANSMISSION BLOCK (ETB) 27 | 0000001B | ESCAPE (ESC) 28 | 00000088 | CHARACTER TABULATION SET (HTS) 29 | 00000089 | CHARACTER TABULATION WITH JUSTIFICATION (HTJ) 2A | 0000008A | LINE TABULATION SET (VTS) 2B | 0000008B | PARTIAL LINE FORWARD (PLD) 2C | 0000008C | PARTIAL LINE BACKWARD (PLU) 2D | 00000005 | ENQUIRY (ENQ) 2E | 00000006 | ACKNOWLEDGE (ACK) 2F | 00000007 | BELL (BEL) 30 | 00000090 | DEVICE CONTROL STRING (DCS) 31 | 00000091 | PRIVATE USE ONE (PU1) 32 | 00000016 | SYNCHRONOUS IDLE (SYN) 33 | 00000093 | SET TRANSMIT STATE (STS) 34 | 00000094 | CANCEL CHARACTER (CCH) 35 | 00000095 | MESSAGE WAITING (MW) 36 | 00000096 | START OF GUARDED AREA (SPA) 37 | 00000004 | END OF TRANSMISSION (EOT) 38 | 00000098 | START OF STRING (SOS) 39 | 00000099 | SINGLE GRAPHIC CHARACTER INTRODUCER (SGCI) 3A | 0000009A | SINGLE CHARACTER INTRODUCER (SCI) 3B | 0000009B | CONTROL SEQUENCE INTRODUCER (CSI) 3C | 00000014 | DEVICE CONTROL FOUR (DC4) 3D | 00000015 | NEGATIVE ACKNOWLEDGE (NAK) 3E | 0000009E | PRIVACY MESSAGE (PM) 3F | 0000001A | SUBSTITUTE (SUB) 40 | 00000020 | SPACE 41 | 000000A0 | NO-BREAK SPACE 42 | 0000060C | ARABIC COMMA 43 | 0000061B | ARABIC SEMICOLON 44 | 0000061F | ARABIC QUESTION MARK 45 | 00000623 | ARABIC LETTER ALEF WITH HAMZA ABOVE 46 | 00000627 | ARABIC LETTER ALEF 47 | 0000FE8E | ARABIC LETTER ALEF FINAL FORM 49 | 00000628 | ARABIC LETTER BEH 4A | 0000005B | LEFT SQUARE BRACKET 4B | 0000002E | FULL STOP 4C | 0000003C | LESS-THAN SIGN 4D | 00000028 | LEFT PARENTHESIS 4E | 0000002B | PLUS SIGN 4F | 00000021 | EXCLAMATION MARK 50 | 00000026 | AMPERSAND 51 | 0000FE91 | ARABIC LETTER BEH INITIAL FORM 52 | 0000067E | ARABIC LETTER PEH 54 | 00000629 | ARABIC LETTER TEH MARBUTA 55 | 0000062A | ARABIC LETTER TEH 56 | 0000FE97 | ARABIC LETTER TEH INITIAL FORM 59 | 0000062B | ARABIC LETTER THEH 5A | 0000005D | RIGHT SQUARE BRACKET 5B | 00000024 | DOLLAR SIGN 5C | 0000002A | ASTERISK 5D | 00000029 | RIGHT PARENTHESIS 5E | 0000003B | SEMICOLON 5F | 0000005E | CIRCUMFLEX ACCENT 60 | 0000002D | HYPHEN-MINUS 61 | 0000002F | SOLIDUS 62 | 0000FE9B | ARABIC LETTER THEH INITIAL FORM 63 | 0000062C | ARABIC LETTER JEEM 64 | 0000FE9F | ARABIC LETTER JEEM INITIAL FORM 67 | 0000062D | ARABIC LETTER HAH 68 | 0000FEA3 | ARABIC LETTER HAH INITIAL FORM 69 | 0000062E | ARABIC LETTER KHAH 6A | 00000060 | GRAVE ACCENT 6B | 0000002C | COMMA 6C | 00000025 | PERCENT SIGN 6D | 0000005F | LOW LINE 6E | 0000003E | GREATER-THAN SIGN 6F | 0000003F | QUESTION MARK 70 | 00000660 | ARABIC-INDIC DIGIT ZERO 71 | 00000661 | ARABIC-INDIC DIGIT ONE 72 | 00000662 | ARABIC-INDIC DIGIT TWO 73 | 00000663 | ARABIC-INDIC DIGIT THREE 74 | 00000664 | ARABIC-INDIC DIGIT FOUR 75 | 00000665 | ARABIC-INDIC DIGIT FIVE 76 | 00000666 | ARABIC-INDIC DIGIT SIX 77 | 00000667 | ARABIC-INDIC DIGIT SEVEN 78 | 00000668 | ARABIC-INDIC DIGIT EIGHT 79 | 00000669 | ARABIC-INDIC DIGIT NINE 7A | 0000003A | COLON 7B | 00000023 | NUMBER SIGN 7C | 00000040 | COMMERCIAL AT 7D | 00000027 | APOSTROPHE 7E | 0000003D | EQUALS SIGN 7F | 00000022 | QUOTATION MARK 80 | 0000FEA7 | ARABIC LETTER KHAH INITIAL FORM 81 | 00000061 | LATIN SMALL LETTER A 82 | 00000062 | LATIN SMALL LETTER B 83 | 00000063 | LATIN SMALL LETTER C 84 | 00000064 | LATIN SMALL LETTER D 85 | 00000065 | LATIN SMALL LETTER E 86 | 00000066 | LATIN SMALL LETTER F 87 | 00000067 | LATIN SMALL LETTER G 88 | 00000068 | LATIN SMALL LETTER H 89 | 00000069 | LATIN SMALL LETTER I 8A | 0000062F | ARABIC LETTER DAL 8C | 00000630 | ARABIC LETTER THAL 8D | 00000631 | ARABIC LETTER REH 8F | 00000632 | ARABIC LETTER ZAIN 91 | 0000006A | LATIN SMALL LETTER J 92 | 0000006B | LATIN SMALL LETTER K 93 | 0000006C | LATIN SMALL LETTER L 94 | 0000006D | LATIN SMALL LETTER M 95 | 0000006E | LATIN SMALL LETTER N 96 | 0000006F | LATIN SMALL LETTER O 97 | 00000070 | LATIN SMALL LETTER P 98 | 00000071 | LATIN SMALL LETTER Q 99 | 00000072 | LATIN SMALL LETTER R 9A | 00000633 | ARABIC LETTER SEEN 9B | 0000FEB3 | ARABIC LETTER SEEN INITIAL FORM 9C | 00000634 | ARABIC LETTER SHEEN 9D | 0000FEB7 | ARABIC LETTER SHEEN INITIAL FORM 9E | 00000635 | ARABIC LETTER SAD 9F | 0000FEBB | ARABIC LETTER SAD INITIAL FORM A0 | 00000636 | ARABIC LETTER DAD A1 | 0000007E | TILDE A2 | 00000073 | LATIN SMALL LETTER S A3 | 00000074 | LATIN SMALL LETTER T A4 | 00000075 | LATIN SMALL LETTER U A5 | 00000076 | LATIN SMALL LETTER V A6 | 00000077 | LATIN SMALL LETTER W A7 | 00000078 | LATIN SMALL LETTER X A8 | 00000079 | LATIN SMALL LETTER Y A9 | 0000007A | LATIN SMALL LETTER Z AA | 0000FEBF | ARABIC LETTER DAD INITIAL FORM AB | 00000637 | ARABIC LETTER TAH AC | 00000638 | ARABIC LETTER ZAH AD | 00000639 | ARABIC LETTER AIN AE | 0000FECA | ARABIC LETTER AIN FINAL FORM AF | 0000FECB | ARABIC LETTER AIN INITIAL FORM B0 | 0000FECC | ARABIC LETTER AIN MEDIAL FORM B1 | 0000063A | ARABIC LETTER GHAIN B2 | 0000FECE | ARABIC LETTER GHAIN FINAL FORM B3 | 0000FECF | ARABIC LETTER GHAIN INITIAL FORM B4 | 0000FED0 | ARABIC LETTER GHAIN MEDIAL FORM B5 | 00000641 | ARABIC LETTER FEH B6 | 0000FED3 | ARABIC LETTER FEH INITIAL FORM B7 | 00000642 | ARABIC LETTER QAF B8 | 0000FED7 | ARABIC LETTER QAF INITIAL FORM B9 | 00000643 | ARABIC LETTER KAF BA | 0000FEDB | ARABIC LETTER KAF INITIAL FORM BB | 0000007C | VERTICAL LINE BE | 00000644 | ARABIC LETTER LAM BF | 0000FEDE | ARABIC LETTER LAM FINAL FORM C0 | 0000007B | LEFT CURLY BRACKET C1 | 00000041 | LATIN CAPITAL LETTER A C2 | 00000042 | LATIN CAPITAL LETTER B C3 | 00000043 | LATIN CAPITAL LETTER C C4 | 00000044 | LATIN CAPITAL LETTER D C5 | 00000045 | LATIN CAPITAL LETTER E C6 | 00000046 | LATIN CAPITAL LETTER F C7 | 00000047 | LATIN CAPITAL LETTER G C8 | 00000048 | LATIN CAPITAL LETTER H C9 | 00000049 | LATIN CAPITAL LETTER I CA | 000000AD | SOFT HYPHEN CC | 00000645 | ARABIC LETTER MEEM CD | 0000FEE3 | ARABIC LETTER MEEM INITIAL FORM CF | 00000646 | ARABIC LETTER NOON D0 | 0000007D | RIGHT CURLY BRACKET D1 | 0000004A | LATIN CAPITAL LETTER J D2 | 0000004B | LATIN CAPITAL LETTER K D3 | 0000004C | LATIN CAPITAL LETTER L D4 | 0000004D | LATIN CAPITAL LETTER M D5 | 0000004E | LATIN CAPITAL LETTER N D6 | 0000004F | LATIN CAPITAL LETTER O D7 | 00000050 | LATIN CAPITAL LETTER P D8 | 00000051 | LATIN CAPITAL LETTER Q D9 | 00000052 | LATIN CAPITAL LETTER R DA | 0000FEE7 | ARABIC LETTER NOON INITIAL FORM DC | 00000648 | ARABIC LETTER WAW E0 | 0000005C | REVERSE SOLIDUS E2 | 00000053 | LATIN CAPITAL LETTER S E3 | 00000054 | LATIN CAPITAL LETTER T E4 | 00000055 | LATIN CAPITAL LETTER U E5 | 00000056 | LATIN CAPITAL LETTER V E6 | 00000057 | LATIN CAPITAL LETTER W E7 | 00000058 | LATIN CAPITAL LETTER X E8 | 00000059 | LATIN CAPITAL LETTER Y E9 | 0000005A | LATIN CAPITAL LETTER Z EA | 00000621 | ARABIC LETTER HAMZA F0 | 00000030 | DIGIT ZERO F1 | 00000031 | DIGIT ONE F2 | 00000032 | DIGIT TWO F3 | 00000033 | DIGIT THREE F4 | 00000034 | DIGIT FOUR F5 | 00000035 | DIGIT FIVE F6 | 00000036 | DIGIT SIX F7 | 00000037 | DIGIT SEVEN F8 | 00000038 | DIGIT EIGHT F9 | 00000039 | DIGIT NINE FD | 00000651 | ARABIC SHADDA FE | 0000FE7D | ARABIC SHADDA MEDIAL FORM FF | 0000009F | APPLICATION PROGRAM COMMAND (APC) =head1 AUTHOR Copyright (C) 2002-2009, Guido Flohr E<lt>guido@imperia.netE<gt>, all rights reserved. See the source code for details. This software is contributed to the Perl community by Imperia (L<http://www.imperia.net/>). =head1 SEE ALSO Locale::RecodeData(3), Locale::Recode(3), perl(1) =cut Local Variables: mode: perl perl-indent-level: 4 perl-continued-statement-offset: 4 perl-continued-brace-offset: 0 perl-brace-offset: -4 perl-brace-imaginary-offset: 0 perl-label-offset: -4 cperl-indent-level: 4 cperl-continued-statement-offset: 2 tab-width: 4 End: =cut
cgwalters/texinfo-git-mirror
texi2html/lib/libintl-perl/lib/Locale/RecodeData/IBM918.pm
Perl
gpl-3.0
25,611
package io.github.mightybeards.flyting.domain; import android.media.MediaRecorder; import android.util.Log; import java.io.File; import java.io.IOException; public class AudioRecorder { private MediaRecorder recorder; private String path; private int currentRecord = 1; public AudioRecorder(String path) { this.path = path += "/" + System.currentTimeMillis(); new File(path).mkdir(); } /* * Returns the path to the newly written file. */ public String startRecord() { recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); String outputFile = path + "/" + currentRecord + ".mp4"; recorder.setOutputFile(outputFile); try { recorder.prepare(); } catch (IOException e) { Log.e("AudioRecorder", "prepare() failed"); } recorder.start(); return outputFile; } public void stopRecord() { recorder.stop(); recorder.reset(); recorder.release(); currentRecord++; } }
Mighty-Beards/Flyting
app/src/main/java/io/github/mightybeards/flyting/domain/AudioRecorder.java
Java
gpl-3.0
1,228
<?php session_start(); ?> <html> <head><title>Envoi de message</title></head> <link rel="stylesheet" type="text/css" href="styleidentification.css" media="all"/> <body> <?php if(!isset($_SESSION['Pseudo'])) { echo "<script>alert(\"Vous n etes pas connecte\")</script>"; session_destroy(); header('Location: identification.php'); } else { if (isset($_POST['verif'])) { if ($C = valider_form()) { afficher_form($C); } else { traiter_form(); } } else { afficher_form($C = 0); } } function afficher_form($e) { echo '<form class="form-container" method="post" action=' . $_SERVER["PHP_SELF"] . '>'; echo '<label class="form-title" for="PseudoDest">Pseudo du destinataire</label><input class="form-field" type="text" name="PseudoDest"/><br>'; echo '<label class="form-title" for="Message">Message </label><textarea rows="4" cols="50" name="Message" placeholder="Entrez votre message ici.."></textarea><br>'; echo '<input type="hidden" value="1" name="verif">'; if ($e) { echo "<ul>"; foreach ($e as $message) { echo "<li class='erreur'> $message </li>"; } echo "</ul>"; } echo '<input class="submit-container" type="submit" name="send" value="Valider"><br> '; echo '</form> '; } function valider_form() { $erreur = array(); if (empty($_POST["PseudoDest"])) { $erreur[] = "Veuillez entrer le pseudo du destinataire."; } if (empty($_POST["Message"])) { $erreur[] = "Veuillez ecrire un message."; } return $erreur; } function traiter_form() { $PseudoDest = $_POST['PseudoDest']; $Message = $_POST['Message']; $array = array('type' => "5", 'from' => $_SESSION['Pseudo'], 'dest' => $PseudoDest, 'contenu' => $Message); $donnees = http_build_query(array('donnees' => json_encode($array))); $options = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $donnees ) ); // Envoi de la requête et lecture du JSON reçu $contexte = stream_context_create($options); $jsonTexte = file_get_contents('http://localhost:8565/message.html', false, $contexte); // Analyse du JSON reçu $tab = json_decode($jsonTexte, true); if ($tab['accepted'] == "true"){ echo "Envoi message reussi.<br>"; }else { echo "Envoi message echoue.<br>"; } } ?> </body> </html>
INFO070820162017/CYAN
Version_1/Site/msgsend.php
PHP
gpl-3.0
2,439
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>pstat: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">pstat &#160;<span id="projectnumber">0.6</span> </div> <div id="projectbrief">Parallel filesystem stat</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classtbb_1_1concurrent__unordered__map.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">tbb::concurrent_unordered_map&lt; Key, T &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>count</b>(const Key &amp;key) (defined in <a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a>)</td><td class="entry"><a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>m_Map</b> (defined in <a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a>)</td><td class="entry"><a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>m_Mutex</b> (defined in <a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a>)</td><td class="entry"><a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a></td><td class="entry"><span class="mlabel">private</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>operator[]</b>(const Key &amp;key) (defined in <a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a>)</td><td class="entry"><a class="el" href="classtbb_1_1concurrent__unordered__map.html">tbb::concurrent_unordered_map&lt; Key, T &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Fri Sep 11 2015 23:33:39 for pstat by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
ParallelMazen/pstat
docs/html/classtbb_1_1concurrent__unordered__map-members.html
HTML
gpl-3.0
6,612
/* * GPL HEADER START * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 only, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is included * in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU General Public License * version 2 along with this program; If not, see * http://www.gnu.org/licenses/gpl-2.0.html * * GPL HEADER END */ /* * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. * Use is subject to license terms. * * Copyright (c) 2011, 2014, Intel Corporation. */ #define DEBUG_SUBSYSTEM S_LLITE #include "../include/lustre/lustre_idl.h" #include "../include/cl_object.h" #include "../include/obd.h" #include "../include/obd_support.h" #include "llite_internal.h" #include "vvp_internal.h" static inline struct vvp_req *cl2vvp_req(const struct cl_req_slice *slice) { return container_of0(slice, struct vvp_req, vrq_cl); } /** * Implementation of struct cl_req_operations::cro_attr_set() for VVP * layer. VVP is responsible for * * - o_[mac]time * * - o_mode * * - o_parent_seq * * - o_[ug]id * * - o_parent_oid * * - o_parent_ver * * - o_ioepoch, * */ static void vvp_req_attr_set(const struct lu_env *env, const struct cl_req_slice *slice, const struct cl_object *obj, struct cl_req_attr *attr, u64 flags) { struct inode *inode; struct obdo *oa; u32 valid_flags; oa = attr->cra_oa; inode = vvp_object_inode(obj); valid_flags = OBD_MD_FLTYPE; if (slice->crs_req->crq_type == CRT_WRITE) { if (flags & OBD_MD_FLEPOCH) { oa->o_valid |= OBD_MD_FLEPOCH; oa->o_ioepoch = ll_i2info(inode)->lli_ioepoch; valid_flags |= OBD_MD_FLMTIME | OBD_MD_FLCTIME | OBD_MD_FLUID | OBD_MD_FLGID; } } obdo_from_inode(oa, inode, valid_flags & flags); obdo_set_parent_fid(oa, &ll_i2info(inode)->lli_fid); if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_INVALID_PFID)) { oa->o_parent_oid++; } memcpy(attr->cra_jobid, ll_i2info(inode)->lli_jobid, LUSTRE_JOBID_SIZE); } static void vvp_req_completion(const struct lu_env *env, const struct cl_req_slice *slice, int ioret) { struct vvp_req *vrq; if (ioret > 0) { cl_stats_tally(slice->crs_dev, slice->crs_req->crq_type, ioret); } vrq = cl2vvp_req(slice); kmem_cache_free(vvp_req_kmem, vrq); } static const struct cl_req_operations vvp_req_ops = { .cro_attr_set = vvp_req_attr_set, .cro_completion = vvp_req_completion }; int vvp_req_init(const struct lu_env *env, struct cl_device *dev, struct cl_req *req) { struct vvp_req *vrq; int result; vrq = kmem_cache_zalloc(vvp_req_kmem, GFP_NOFS); if (vrq) { cl_req_slice_add(req, &vrq->vrq_cl, dev, &vvp_req_ops); result = 0; } else { result = -ENOMEM; } return result; }
williamfdevine/PrettyLinux
drivers/staging/lustre/lustre/llite/vvp_req.c
C
gpl-3.0
3,218
/*! * Ext JS Library 3.4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.onReady(function(){ var tabs = new Ext.TabPanel({ renderTo:'tabs', resizeTabs:true, // turn on tab resizing minTabWidth: 115, tabWidth:135, enableTabScroll:true, width:600, height:250, defaults: {autoScroll:true}, plugins: new Ext.ux.TabCloseMenu() }); // tab generation code var index = 0; while(index < 7){ addTab(); } function addTab(){ tabs.add({ title: 'New Tab 测试 ' + (++index), iconCls: 'tabs', html: 'Tab Body ' + (index) + '<br/><br/>' + Ext.example.bogusMarkup, closable:true }).show(); } new Ext.Button({ text: 'Add Tab', handler: addTab, iconCls:'new-tab' }).render(document.body, 'tabs'); });
doujiangbaozi/SliverFramework
WebRoot/js/Ext/examples/tabs/tabs-adv.js
JavaScript
gpl-3.0
986
function removerreserva(id) { $.get("/reservaja/removerreserva?", { 'id' : id }, function() { $("#res" + id).remove(); }); }
rasertux/reservaja
src/main/webapp/themes/js/removerreserva.js
JavaScript
gpl-3.0
131
#include <fstream> #include <functional> #include "collector.h" Collector::Collector(std::string filename, size_t width, size_t height, size_t num_splits) : pixmap(PnmImage(width, height)) { std::ifstream ifile(filename, std::ifstream::binary); Json::Reader reader; if (reader.parse(ifile, scene, false) == false) { std::cerr << "Error parsing scene" << std::endl; } /* Split the work (a render of the whole scene) into num_splits pieces. */ work_t initial = work_t(0, 0, width, height, width, height, 255); queue.split(initial, num_splits); remaining_work = num_splits; finished.lock(); /* Every request hits this lambda. */ server = new TCPServer([=](std::string req) { return this->serve_request(req); }); } Collector::~Collector() { delete server; } bool Collector::start(std::string host, int port) { std::cout << "Listening on " << host << ":" << port << "...\n"; return server->start(host, port); } void Collector::stop() { server->stop(); } std::string Collector::serve_request(std::string req) { Json::Value root; Json::Reader reader; if (reader.parse(req, root, false) == false) { return generate_error("bad_json"); } if (root["status"] == "have_work") { std::cout << "work: " << root["work"] << std::endl; /* Add the pixels to the pixmap. */ process_work(root["work"], root["pixels"]); Json::Value root; root["success"] = true; return json_to_string(root); } else if (root["status"] == "need_work") { /* We want to reduce network slowdown by only sending the scene when necessary. */ return generate_work(root["have_scene"].asBool()); } else { return generate_error("bad_request"); } } std::string Collector::generate_work(bool has_scene) { Json::Value root; /* No need to send scene if client already has it. */ if (has_scene == false) { root["scene"] = scene; std::cout << "client needs scene" << std::endl; } /* Return work from the queue, but don't remove it just yet. */ root["work"] = queue.get().to_json_value(); return json_to_string(root); } /* Allows Collector process to finish when it acquires the lock. */ bool Collector::finish() { finished.lock(); finished.unlock(); return true; } std::string Collector::generate_error(std::string type) { Json::Value error; error["error"] = true; error["type"] = type; return json_to_string(error); } /* Parse work, store in pixmap. */ void Collector::process_work(Json::Value json_work, Json::Value json_pixels) { work_t work = work_t(json_work); std::cerr << work.id << std::endl; queue_lock.lock(); if (!queue.isdone(work.id)) { /* This comes first so we don't double-assign. */ queue.remove(work.id); remaining_work--; queue_lock.unlock(); pixel_t **pixels = pixel_t::from_json_value(json_pixels, work.width, work.height); pixmap.insert_chunk(pixels, work.x, work.y, work.width, work.height); std::cerr << "Insert!" << std::endl; } else { /* Need else case so we can a) unlock early in above case and b) unlock if above case does not happen. */ queue_lock.unlock(); } /* Finished rendering everything! */ if (remaining_work == 0) { finished.unlock(); } } void Collector::write_image(std::string filename) { pixmap.write(filename); }
TheiaRT/tracer
src/collector.cpp
C++
gpl-3.0
3,708
package br.com.squamata.gastos.enumeration; public enum TipoMensagemEnum { SUCCESS(1, "alert-success"), INFO (2, "alert-info"), WARNING(3, "alert-warning"), DANGER (4, "alert-danger"); private Integer codigo; private String classe; private TipoMensagemEnum(final Integer codigo, final String classe) { this.codigo = codigo; this.classe = classe; } public Integer getCodigo() { return codigo; } public String getClasse() { return classe; } }
FelipeAdorno/gastosAPP
src/main/java/br/com/squamata/gastos/enumeration/TipoMensagemEnum.java
Java
gpl-3.0
474
package model import org.joda.time.DateTime case class Ticker (tradePair: TradePair, time: DateTime, interval: Interval, open: Price, high: Price, low: Price, close: Price, volume: Volume)
avalon12/crypto-trader
traderbot/src/main/scala/model/Ticker.scala
Scala
gpl-3.0
191
package org.jasonleaster.utils.common; import java.util.HashMap; import java.util.Map; import org.junit.Test; /** * Author: jasonleaster * Date : 2017/6/30 * Email : jasonleaster@gmail.com * Description: */ public class CommonUtilsTest { @Test public void mergeMapVal() throws Exception { Map<Integer, Integer> mapA = new HashMap<>(); Map<Integer, Integer> mapB = new HashMap<>(); mapA.put(1,1); mapA.put(2,2); mapB.put(2,2); mapB.put(3,3); CommonUtils.mergeMapVal(mapA, mapB, Integer::sum); } }
jasonleaster/TheWayToJava
CommonTools/src/test/java/org/jasonleaster/utils/common/CommonUtilsTest.java
Java
gpl-3.0
576
/** * Copyright (C) 2010-2016 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.websocket.command; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.jetty.websocket.api.Session; import org.structr.common.SecurityContext; import org.structr.common.error.FrameworkException; import org.structr.core.GraphObject; import org.structr.core.app.App; import org.structr.core.app.StructrApp; import org.structr.core.entity.AbstractNode; import org.structr.core.entity.AbstractRelationship; import org.structr.core.graph.Tx; import org.structr.core.property.PropertyMap; import org.structr.web.entity.Widget; import org.structr.web.entity.dom.DOMNode; import org.structr.web.entity.dom.Page; import org.structr.web.entity.dom.ShadowDocument; import org.structr.websocket.StructrWebSocket; import org.structr.websocket.message.WebSocketMessage; //~--- classes ---------------------------------------------------------------- /** * Base class for all WebSocket commands in structr. * * */ public abstract class AbstractCommand { public static final String COMMAND_KEY = "command"; public static final String ID_KEY = "id"; private static final Logger logger = Logger.getLogger(AbstractCommand.class.getName()); protected Session session = null; protected StructrWebSocket webSocket = null; protected String callback = null; public abstract void processMessage(final WebSocketMessage webSocketData) throws FrameworkException; public abstract String getCommand(); public Session getSession() { return session; } public StructrWebSocket getWebSocket() { return webSocket; } public Page getPage(final String id) { final AbstractNode node = getNode(id); if (node != null && node instanceof Page) { return (Page) node; } return null; } public DOMNode getDOMNode(final String id) { final AbstractNode node = getNode(id); if (node != null && node instanceof DOMNode) { return (DOMNode) node; } return null; } public Widget getWidget(final String id) { final AbstractNode node = getNode(id); if (node != null && node instanceof Widget) { return (Widget) node; } return null; } /** * Returns the graph object to which the uuid parameter * of this command refers to. * * @param id * @return the graph object */ public GraphObject getGraphObject(final String id) { final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { final GraphObject graphObject = (GraphObject) app.get(id); tx.success(); return graphObject; } catch (FrameworkException fex) { logger.log(Level.WARNING, "Unable to get graph object", fex); } return null; } /** * Returns the node to which the uuid parameter * of this command refers to. * * @param id * @return the node */ public AbstractNode getNode(final String id) { final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { final AbstractNode node = (AbstractNode) app.getNodeById(id); tx.success(); return node; } catch (FrameworkException fex) { logger.log(Level.WARNING, "Unable to get node", fex); } return null; } /** * Returns the relationship to which the uuid parameter * of this command refers to. * * @param id * @return the node */ public AbstractRelationship getRelationship(final String id) { if (id == null) { return null; } final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { final AbstractRelationship rel = (AbstractRelationship) app.getRelationshipById(id); tx.success(); return rel; } catch (FrameworkException fex) { logger.log(Level.WARNING, "Unable to get relationship", fex); } return null; } /** * Override this method if the websocket command will create its own * transaction context * * @return a boolean */ public boolean requiresEnclosingTransaction() { return true; } /** * Make child nodes of the source nodes child nodes of the target node. * * @param sourceNode * @param targetNode */ protected void moveChildNodes(final DOMNode sourceNode, final DOMNode targetNode) { DOMNode child = (DOMNode) sourceNode.getFirstChild(); while (child != null) { DOMNode next = (DOMNode) child.getNextSibling(); targetNode.appendChild(child); child = next; } } /** * Search for a hidden page named __ShadowDocument__ of type. * * If found, return it, if not, create it. * The shadow page is the DOM document all reusable components are connected to. * It is necessary to comply with DOM standards. * * @return shadow document * @throws FrameworkException */ protected ShadowDocument getOrCreateHiddenDocument() throws FrameworkException { final App app = StructrApp.getInstance(); ShadowDocument doc = app.nodeQuery(ShadowDocument.class).includeDeletedAndHidden().getFirst(); if (doc == null) { final PropertyMap properties = new PropertyMap(); properties.put(AbstractNode.type, ShadowDocument.class.getSimpleName()); properties.put(AbstractNode.name, "__ShadowDocument__"); properties.put(AbstractNode.hidden, true); properties.put(AbstractNode.visibleToAuthenticatedUsers, true); doc = app.create(ShadowDocument.class, properties); } return doc; } public void setSession(final Session session) { this.session = session; } public void setWebSocket(final StructrWebSocket webSocket) { this.webSocket = webSocket; } public void setCallback(final String callback) { this.callback = callback; } }
derkaiserreich/structr
structr-ui/src/main/java/org/structr/websocket/command/AbstractCommand.java
Java
gpl-3.0
6,566
<?php namespace Faker\Provider\ro_MD; class Address extends \Faker\Provider\Address { protected static $buildingNumber = array('###', '##', '#', '#/#', '#A', '#B'); protected static $apartmentNumber = array('#', '##'); protected static $floor = array('#', '##'); protected static $block = array('#', '##', 'A', 'B', 'C', 'D'); protected static $blockSegment = array('A', 'B', 'C', 'D'); protected static $streetPrefix = array( 'Str.', 'B-dul.', 'Aleea', 'Calea', 'P-ța', 'Str-la' ); // random selection of seemingly frequently used streets and naming categories protected static $streetPlainName = array( // historical events 'Eroilor', 'Independenței', 'Lenin', 'Unirii', '31 August 1989', 'Sovietului', // historical people 'Mihai Viteazul', 'Mircea cel Bătrân', 'Mitropolitul Varlaam', 'Traian', 'Decebal', 'Alexandru cel Bun', 'Alexandri V.', 'Arhangelul Mihail', // national and international people names 'Veronica Micle', 'Ion Creangă', 'Mihai Eminescu', 'B. P. Hașdeu', // nature-related 'Cireșilor', 'Frasinului', 'Salcâmilor', 'Brăduțului', 'Frunzișului', 'Castanilor', 'Mesteacănului', 'Florilor', 'Pădurii', 'Piersicului', 'Trandafirilor', // work-related 'Croitorilor', 'Meșterilor', 'Zidarilor', 'Păcurari', 'Muncii', 'Învățătorului', // geography related 'Chisinau', 'Paris' ); protected static $postcode = array('####'); // http://ro.wikipedia.org/wiki/Lista_ora%C8%99elor_din_Republica_Moldova protected static $cityNames = array( 'Chișinău', 'Tiraspol', 'Bălți', 'Tighina', 'Râbnița', 'Cahul', 'Ungheni', 'Soroca', 'Orhei', 'Dubăsari', 'Comrat', 'Ceadâr-Lunga', 'Strășeni', 'Căușeni', 'Drochia', 'Slobozia', 'Edineț', 'Vulcănești', 'Durlești', 'Hâncești', 'Ialoveni', 'Fălești', 'Călărași', 'Codru', 'Taraclia', 'Florești', 'Cimișlia', 'Sângerei', 'Dnestrovsc', 'Nisporeni', 'Grigoriopol', 'Basarabeasca', 'Râșcani', 'Glodeni', 'Camenca', 'Rezina', 'Leova', 'Cricova', 'Dondușeni', 'Ocnița', 'Briceni', 'Otaci', 'Anenii Noi', 'Ștefan Vodă', 'Cupcini', 'Sângera', 'Criuleni', 'Telenești', 'Șoldănești', 'Tvardița', 'Lipcani', 'Vadul lui Vodă', 'Iargara', 'Căinari', 'Cantemir', 'Vatra', 'Biruința', 'Crasnoe', 'Cornești', 'Costești', 'Mărculești', 'Ghindești', 'Tiraspolul Nou', 'Frunză', 'Bucovăț', 'Maiac' ); // http://ro.wikipedia.org/wiki/Lista_statelor_lumii#Lista_statelor_lumii protected static $country = array( 'Afganistan', 'Africa de Sud', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua și Barbuda', 'Arabia Saudită', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaidjan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgia', 'Belize', 'Benin', 'Bhutan', 'Birmania', 'Bolivia', 'Bosnia și Herțegovina', 'Botswana', 'Brazilia', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodgia', 'Camerun', 'Canada', 'Capul Verde', 'Cehia', 'Republica Centrafricană', 'Chile', 'Republica Populară Chineză', 'Ciad', 'Cipru', 'Columbia', 'Comore', 'Republica Democrată Congo', 'Republica Congo', 'Coreea de Nord', 'Coreea de Sud', 'Costa Rica', 'Coasta de Fildeș', 'Croația', 'Cuba', 'Danemarca', 'Djibouti', 'Dominica', 'Republica Dominicană', 'Ecuador', 'Egipt', 'El Salvador', 'Elveția', 'Emiratele Arabe Unite', 'Eritreea', 'Estonia', 'Etiopia', 'Fiji', 'Filipine', 'Finlanda', 'Franța', 'Gabon', 'Gambia', 'Georgia', 'Germania', 'Ghana', 'Grecia', 'Grenada', 'Guatemala', 'Guineea', 'Guineea-Bissau', 'Guineea Ecuatorială', 'Guyana', 'Haiti', 'Honduras', 'India', 'Indonezia', 'Iordania', 'Irak', 'Iran', 'Republica Irlanda', 'Islanda', 'Israel', 'Italia', 'Jamaica', 'Japonia', 'Kazahstan', 'Kenya', 'Kirghizstan', 'Kiribati', 'Kuweit', 'Laos', 'Lesotho', 'Letonia', 'Liban', 'Liberia', 'Libia', 'Liechtenstein', 'Lituania', 'Luxemburg', 'Republica Macedonia', 'Madagascar', 'Malawi', 'Malaezia', 'Maldive', 'Mali', 'Malta', 'Maroc', 'Insulele Marshall', 'Mauritania', 'Mauritius', 'Mexic', 'Statele Federate ale Microneziei', 'Republica Moldova', 'Monaco', 'Mongolia', 'Mozambic', 'Muntenegru', 'Namibia', 'Nauru', 'Nepal', 'Nicaragua', 'Niger', 'Nigeria', 'Norvegia', 'Noua Zeelandă', 'Olanda', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua Noua Guinee', 'Paraguay', 'Peru', 'Polonia', 'Portugalia', 'Qatar', 'Regatul Unit', 'România', 'Rusia', 'Rwanda', 'Samoa', 'San Marino', 'São Tomé și Príncipe', 'São Tomé e Príncipe', 'Senegal', 'Serbia', 'Seychelles', 'Sfânta Lucia', 'Sfântul Cristofor și Nevis', 'Saint Vincent and the Grenadines', 'Sierra Leone', 'Singapore', 'Siria', 'Slovacia', 'Slovenia', 'Insulele Solomon', 'Somalia', 'Spania', 'Sri Lanka', 'Statele Unite ale Americii', 'Sudan', 'Sudanul de Sud', 'Suedia', 'Surinam', 'Swaziland', 'Tadjikistan', 'Tanzania', 'Thailanda', 'Timorul de Est', 'Togo', 'Tonga', 'Trinidad-Tobago', 'Tunisia', 'Turcia', 'Turkmenistan', 'Tuvalu', 'Ucraina', 'Uganda', 'Ungaria', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe' ); protected static $cityFormats = array( '{{cityName}}', 'Mun. {{cityName}}', ); protected static $streetNameFormats = array( '{{streetPrefix}} {{streetPlainName}}', ); protected static $streetAddressFormats = array( '{{streetName}} {{buildingNumber}}', '{{streetName}} {{buildingNumber}}', '{{streetName}} {{buildingNumber}}', '{{streetName}} nr. {{buildingNumber}}, bl. {{block}}, ap. {{apartmentNumber}}', '{{streetName}} nr. {{buildingNumber}}, bl. {{block}}, et. {{floor}}, ap. {{apartmentNumber}}', '{{streetName}} nr. {{buildingNumber}}, bl. {{block}}, sc. {{blockSegment}}, et. {{floor}}, ap. {{apartmentNumber}}', ); protected static $addressFormats = array( "{{streetAddress}}, {{city}}, CP {{postcode}}", ); public function cityName() { return static::randomElement(static::$cityNames); } public static function block() { return static::numerify(static::randomElement(static::$block)); } public function blockSegment() { return static::randomElement(static::$blockSegment); } public static function floor() { return static::numerify(static::randomElement(static::$floor)); } public static function apartmentNumber() { return static::numerify(static::randomElement(static::$apartmentNumber)); } public function streetPrefix() { return static::randomElement(static::$streetPrefix); } /** * @example 'Independenței' */ public function streetPlainName() { return static::randomElement(static::$streetPlainName); } /** * @example 'Splaiul Independenței' */ public function streetName() { $format = static::randomElement(static::$streetNameFormats); return $this->generator->parse($format); } public function address() { $format = static::randomElement(static::$addressFormats); return $this->generator->parse($format); } public function streetAddress() { $format = static::randomElement(static::$streetAddressFormats); return $this->generator->parse($format); } }
Drxmo/imaginarium
vendor/fzaninotto/faker/src/Faker/Provider/ro_MD/Address.php
PHP
gpl-3.0
7,297
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * 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. */ package it.gebhard.qa.model.impl; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import it.gebhard.qa.model.Answer; import java.io.Serializable; import java.util.Date; /** * The cache model class for representing Answer in entity cache. * * @author Philipp Gebhard * @see Answer * @generated */ public class AnswerCacheModel implements CacheModel<Answer>, Serializable { @Override public String toString() { StringBundler sb = new StringBundler(17); sb.append("{answerId="); sb.append(answerId); sb.append(", questionId="); sb.append(questionId); sb.append(", userId="); sb.append(userId); sb.append(", message="); sb.append(message); sb.append(", guestUserId="); sb.append(guestUserId); sb.append(", created="); sb.append(created); sb.append(", modified="); sb.append(modified); sb.append(", accepted="); sb.append(accepted); sb.append("}"); return sb.toString(); } public Answer toEntityModel() { AnswerImpl answerImpl = new AnswerImpl(); answerImpl.setAnswerId(answerId); answerImpl.setQuestionId(questionId); answerImpl.setUserId(userId); if (message == null) { answerImpl.setMessage(StringPool.BLANK); } else { answerImpl.setMessage(message); } answerImpl.setGuestUserId(guestUserId); if (created == Long.MIN_VALUE) { answerImpl.setCreated(null); } else { answerImpl.setCreated(new Date(created)); } if (modified == Long.MIN_VALUE) { answerImpl.setModified(null); } else { answerImpl.setModified(new Date(modified)); } answerImpl.setAccepted(accepted); answerImpl.resetOriginalValues(); return answerImpl; } public long answerId; public long questionId; public long userId; public String message; public long guestUserId; public long created; public long modified; public boolean accepted; }
p-gebhard/QuickAnswer
docroot/WEB-INF/src/it/gebhard/qa/model/impl/AnswerCacheModel.java
Java
gpl-3.0
2,518
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package BusinessLogicLayer.BusinessObjects; /** * * @author al.hasan.fadel@gmail.com */ public class ProperAdjectiveBO { private int properAdjectiveId; private NounBO properAdjective; private SemanticNounBO properAdjectiveMeaning; private String status; public int getProperAdjectiveId() { return properAdjectiveId; } public void setProperAdjectiveId( int properAdjectiveId ) { this.properAdjectiveId = properAdjectiveId; } public NounBO getProperAdjective() { return properAdjective; } public void setProperAdjective( NounBO properAdjective ) { this.properAdjective = properAdjective; } public SemanticNounBO getProperAdjectiveMeaning() { return properAdjectiveMeaning; } public void setProperAdjectiveMeaning( SemanticNounBO properAdjectiveMeaning ) { this.properAdjectiveMeaning = properAdjectiveMeaning; } public String getStatus() { return status; } public void setStatus( String status ) { this.status = status; } }
oghalawinji/InteractiveArabicDictionary
IAD/src/java/BusinessLogicLayer/BusinessObjects/ProperAdjectiveBO.java
Java
gpl-3.0
1,211
@font-face { font-family: roboto; src: url('../fonts/roboto.regular.ttf'); } /* ======================================================================= inc_top.mako ========================================================================== */ .fa { margin-left: -2px; margin-right: 4px; } .navbaricon { margin-top: -15px; margin-bottom: -15px; } .icon-white { background-image: url("../images/glyphicons-halflings-white.png"); } .ui-autocomplete-loading { background: white url("../images/loading16.gif") right center no-repeat; } .browserDialog.busy .ui-dialog-buttonpane { background: url("../images/loading.gif") 10px 50% no-repeat !important; } .ui-progressbar .ui-progressbar-overlay { background: url("../css/lib/images/animated-overlay.gif"); } .ui-dialog, .ui-dialog-buttonpane { background: #ECEADF url("../css/lib/images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat !important; } /* restore 1.8.x resize handle on dialog button pane */ .ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; background-position: -80px -224px; } .ui-accordion-content, .ui-tabs-panel { background: #EDEDED none !important; } .ui-widget { font-family: inherit; font-size: 1em; } .ui-widget-content { background: #DCDCDC url("../css/lib/images/ui-bg_highlight-soft_75_dcdcdc_1x100.png") 50% top repeat-x; } .ui-widget-header { background: #FFFFFF url("../css/lib/images/ui-bg_flat_0_ffffff_40x100.png") 50% 50% repeat-x; } .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { background: #FFFFFF; border: 1px solid #CCCCCC; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { background: #FFFFFF; } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { background: #F7F7F7; } .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { background: #FBF9EE url("../css/lib/images/ui-bg_glass_55_fbf9ee_1x400.png") 50% 50% repeat-x; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { background: #FEF1EC url("../css/lib/images/ui-bg_glass_95_fef1ec_1x400.png") 50% 50% repeat-x; } .ui-icon { float: left; } .ui-icon, .ui-widget-content .ui-icon { background-image: url("../css/lib/images/ui-icons_222222_256x240.png"); } .ui-widget-header .ui-icon { background-image: url("../css/lib/images/ui-icons_222222_256x240.png"); } .ui-state-default .ui-icon { background-image: url("../css/lib/images/ui-icons_8c291d_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { background-image: url("../css/lib/images/ui-icons_222222_256x240.png"); } .ui-state-active .ui-icon { background-image: url("../css/lib/images/ui-icons_8c291d_256x240.png"); } .ui-state-highlight .ui-icon { background-image: url("../css/lib/images/ui-icons_2e83ff_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { background-image: url("../css/lib/images/ui-icons_cd0a0a_256x240.png"); } .ui-widget-overlay { background: #AAAAAA url("../css/lib/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; } .ui-widget-shadow { background: #000000 url("../css/lib/images/ui-bg_flat_0_000000_40x100.png") 50% 50% repeat-x; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #140F06; text-decoration: none; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #222222; text-decoration: none; } .ui-tabs { padding: 0; background: none; border-width: 0; } .ui-tabs .ui-tabs-nav { padding-left: 0; background: transparent; border-width: 0; -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; } .ui-tabs .ui-tabs-panel { background-color: #F7F7F7 !important; border: 1px solid #CCCCCC !important; padding: 1em; } .ui-tabs .ui-tabs-nav li.ui-tabs-active { border-top-left-radius: 5px; border-top-right-radius: 5px; } .ui-tabs-nav > :not(.ui-tabs-active) { border-top-left-radius: 5px; border-top-right-radius: 5px; } #sub-menu-container { margin: 0; } #sub-menu { clear: both; font-size: 12px; align-content: flex-end; } #sub-menu a { clear-after: top; margin: 2px; float: right; } .upgrade-notification { max-width: 600px; text-align: center; margin: 10px auto; } [class^="menu-icon-"], [class*=" menu-icon-"] { background: url("../images/menu/16px_sprite_colored_menu_icons.png"); height: 16px; width: 16px; display: inline-block; position: relative; right: 3px; top: 0; float: left; } .navbar [class^="menu-icon-"], .navbar [class*=" menu-icon-"] { top: 1px; } .menu-icon-addshow { background-position: 0 0; } .menu-icon-anime { background-position: -21px 0; } .menu-icon-backlog-view { background-position: -42px 0; } .menu-icon-backlog { background-position: -63px 0; } .menu-icon-bittorrent { background-position: -84px 0; } .menu-icon-config-index { background-position: -105px 0; } .menu-icon-config { background-position: -126px 0; } .menu-icon-failed-download { background-position: -147px 0; } .menu-icon-home { background-position: -168px 0; } .menu-icon-manage { background-position: -189px 0; } .menu-icon-manage-searches { background-position: -210px 0; } .menu-icon-poster { background-position: -231px 0; } .menu-icon-postprocess { background-position: -252px 0; } .menu-icon-restart { background-position: -273px 0; } .menu-icon-shutdown { background-position: -294px 0; } .menu-icon-update { background-position: -315px 0; } .menu-icon-viewlog-errors { background-position: -336px 0; } .menu-icon-viewlog { background-position: -357px 0; } .menu-icon-kodi { background-position: -378px 0; } .menu-icon-help { background-position: -399px 0; } .menu-icon-info { background-position: -418px 0; } .menu-icon-error { background-position: -436px 0; } .menu-icon-news { background-position: -456px 0; } .menu-icon-irc { background-position: -478px 0; } .menu-icon-changelog { background-position: -495px 0; } .menu-icon-support { background-position: -516px 0; } .menu-icon-plex { background-position: -536px 0; } .menu-icon-backup { background-position: -556px 0; } .menu-icon-provider { background-position: -576px 0; } .menu-icon-notification { background-position: -597px 0; } .menu-icon-emby { background-position: -614px 0; } .menu-icon-blackhole { background-position: -632px 0; } .menu-icon-schedule { background-position: -653px 0; } .menu-icon-manage2 { background-position: -673px 0; } .menu-icon-history { background-position: -695px 0; } .menu-icon-trash { background-position: -711px 0; } .menu-icon-cut { background-position: -727px 0; } .menu-icon-select { background-position: -742px 0; } /* ======================================================================= inc_bottom.mako ========================================================================== */ .footer { padding: 20px 0; color: #4E4E4E; text-align: center; font-size: 12px; } .footerhighlight { color: #111111; display: inline; } .footer-item { white-space: nowrap; } /* ======================================================================= inc_rootDirs.mako ========================================================================== */ .rootdir-selectbox, .rootdir-selectbox #rootDirs, .rootdir-controls { width: 100%; } .rootdir-selectbox { padding: 0 0 5px; } .rootdir-controls { text-align: center; } /* ======================================================================= home.mako ========================================================================== */ .imgbanner .banner { border: 1px solid #CCCCCC; overflow: hidden; height: 66px; border-radius: 8px; vertical-align: top; width: 360px; display: block; margin-left: auto; margin-right: auto; } .imgsmallposter .small { height: 66px; overflow: hidden; border-radius: 3px; vertical-align: middle; width: 45px; border: 1px solid #CCCCCC; margin-right: 5px; } .search { margin-bottom: 10px; } .ui-progressbar { height: 20px; line-height: 18px; } .ui-progressbar .ui-progressbar-value { box-sizing: content-box !important; } .progressbarText { position: absolute; top: 0; width: 100%; height: 100%; overflow: visible; text-align: center; text-shadow: 0 0 0.1em #FFFFFF; vertical-align: middle; font-size: 12px; color: #000000; } .progress-100 { background-image: -moz-linear-gradient(#A6CF41, #5B990D); background-image: linear-gradient(#A6CF41, #5B990D); background-image: -webkit-linear-gradient(#A6CF41, #5B990D); background-image: -o-linear-gradient(#A6CF41, #5B990D); -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; } .progress-80 { background-image: -moz-linear-gradient(#E1FF97, #9DB269); background-image: linear-gradient(#E1FF97, #9DB269); background-image: -webkit-linear-gradient(#E1FF97, #9DB269); background-image: -o-linear-gradient(#E1FF97, #9DB269); -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; } .progress-60 { background-image: -moz-linear-gradient(#FAD440, #F2A70D); background-image: linear-gradient(#FAD440, #F2A70D); background-image: -webkit-linear-gradient(#FAD440, #F2A70D); background-image: -o-linear-gradient(#FAD440, #F2A70D); -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; } .progress-40 { background-image: -moz-linear-gradient(#FAB543, #F2700D); background-image: linear-gradient(#FAB543, #F2700D); background-image: -webkit-linear-gradient(#FAB543, #F2700D); background-image: -o-linear-gradient(#FAB543, #F2700D); -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; } .progress-20 { background-image: -moz-linear-gradient(#DA5945, #B11A10); background-image: linear-gradient(#DA5945, #B11A10); background-image: -webkit-linear-gradient(#DA5945, #B11A10); background-image: -o-linear-gradient(#DA5945, #B11A10); -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; } span.show-option { white-space: nowrap; margin-left: 10px; line-height: 40px; } .show-grid { display: none; } .poster-container { padding-right: 10px; } .info-container { overflow: hidden; } #container, #container-anime { margin: 0 auto; } .loading-spinner { background-image: url("../images/loading32.gif"); width: 32px; height: 32px; display: inline-block; } .show-container { margin: 4px; background-color: #F3F3F3; border: 5px solid #F3F3F3; overflow: hidden; box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.31); } .show-details { height: 32px; overflow: hidden; } .show-image { overflow: hidden; max-width: 100%; } .show-container .ui-progressbar { height: 7px !important; top: -2px; } .show-container .ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { border-bottom-right-radius: 0; } .show-container .ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { border-bottom-left-radius: 0; } .show-container .ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { border-top-right-radius: 0; } .show-container .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { border-top-left-radius: 0; } .show-container .ui-widget-content { border-top: 1px solid #111111; border-bottom: 1px solid #111111; border-left: 0; border-right: 0; } .ui-progressbar .ui-progressbar-value { height: 20px } .ui-progressbar .progress-20 { border: none; } .show-container .progress-20, .show-container .progress-40, .show-container .progress-60, .show-container .progress-80 { border-radius: 0; height: 7px } .show-title { position: relative; overflow: hidden; white-space: nowrap; font-size: 11px; margin: 4px 4px 0 4px; } .show-title:after { content: ""; pointer-events: none; position: absolute; width: 20px; height: 100%; top: 0; right: 0; background-image: -webkit-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: -moz-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: -ms-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: -o-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: linear-gradient(to left, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); } .show-date { position: relative; overflow: hidden; white-space: nowrap; font-size: 11px; margin: 0 4px 4px 4px; color: #949494; } .show-date:after { content: ""; pointer-events: none; position: absolute; width: 20px; height: 100%; top: 0; right: 0; background-image: -webkit-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: -moz-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: -ms-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: -o-linear-gradient(right, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); background-image: linear-gradient(to left, rgba(243, 243, 243, 1), rgba(243, 243, 243, 0)); } .show-table { text-align: center; vertical-align: middle; width: 33% } .show-add { font-size: 11px; text-align: left; display: block; } .show-status { font-size: 11px; text-align: left; display: block; } .show-network-image { width: 50px; height: auto; } .show-dlstats { font-size: 11px; text-align: left; display: block; margin-left: 4px; } .show-quality { font-size: 11px; text-align: right; display: block; margin-right: 4px; } #sort-by { display: inline; list-style-type: none; padding: 0; margin-left: 5px; } #sort-by ul, #sort-by li { display: inline; margin: 0; padding: 0; } .posterview { margin: 0 auto; } td.tvShow a { color: #000000; text-decoration: none; } td.tvShow a:hover { cursor: pointer; color: #428BCA; } #popover-target label { margin: 0 5px; display: block; } #popover-target input { margin-right: 5px; } .popover { margin-left: -48px; } /* ======================================================================= home_addShows.mako ========================================================================== */ #addShowPortal { max-width: 700px; margin: 15px auto; } #addShowPortal a { padding: 10px; } div.button { display: table-cell; vertical-align: middle; padding-left: 10px; } div.buttontext { display: table-cell; padding-left: 20px; text-align: left; white-space: normal; } div.buttontext h3 { margin-top: 10px; } div.buttontext p { font-size: 13px; } [class^="add-list-icon-"], [class*=" add-list-icon-"] { background: url("../images/32px_sprite_colored_add_lists.png"); height: 32px; width: 32px; display: inline-block; position: relative; top: 2px; float: left; } .add-list-icon-addnewshow { background-position: 0 0; } .add-list-icon-addtrakt { background-position: -38px 0; } .add-list-icon-addimdb { background-position: -76px 0; } .add-list-icon-addexistingshow { background-position: -113px 0; } .add-list-icon-addanime { background-position: -150px 0; } /* ======================================================================= home_newShow.mako ========================================================================== */ #addShowForm, #recommendedShowsForm { font-size: 13px; } #displayText { padding: 8px; overflow: hidden; font-size: 14px; background-color: #EFEFEF; border: 1px solid #DFDEDE; } #searchResults input[type="radio"] { vertical-align: -2px; } /* ======================================================================= home_addExistingShow.mako ========================================================================== */ .existingtabs { padding: 1em 1.4em; } ul#rootDirStaticList { margin-right: auto; margin-left: auto; text-align: left; padding-left: 0; } ul#rootDirStaticList li { padding: 4px 5px 4px 5px; margin: 2px; list-style: none outside none; background: url('../css/lib/images/ui-bg_highlight-soft_75_efefef_1x100.png') repeat-x scroll 50% 50% #EFEFEF; } ul#rootDirStaticList li label { margin-top: 5px; margin-bottom: 5px; cursor: pointer; } ul#rootDirStaticList li input[type="checkbox"] { vertical-align: -3px; } /* ======================================================================= home_trendingShows.mako ========================================================================== */ .traktShowTitleIcons { float: right; padding-right: 4px; padding-bottom: 4px; } .traktContainer p { padding-top: 2px; } .traktContainer p img { position: relative; top: -2px; } .traktContainer p, .traktContainer i { white-space: nowrap; font-size: 12px; overflow: hidden; padding-left: 4px; margin: 0; } .traktContainer { margin: 12px; width: 188px; background-color: #DFDACF; border: 1px solid #111111; border-radius: 6px; } .trakt-image { height: 273px; width: 186px; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom: 1px solid #111111; } /* ======================================================================= displayShow.mako ========================================================================== */ #pickShow { display: inline-block; width: calc(100% - 40px); } .poster-container { float:left; } #posterCol { float: left; margin-right: 10px; margin-bottom: 20px; } .navShow { display: inline; cursor: pointer; } #prevShow, #nextShow, #topcontrol { -webkit-filter: grayscale(100%); filter: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' height='0'><filter id='greyscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0' /></filter></svg>#greyscale"); } h1.title { padding-bottom: 12px; margin-bottom: 15px; line-height: 30px; text-align: left; text-rendering: optimizelegibility; border-bottom: 1px solid #888888; } .displayspecials { position: relative; top: -24px; } #showinfo { cursor: default; } #showinfo { display: inline-block; position: relative; } span.imdbstars { display: inline-block; vertical-align: top; cursor: help; margin-top: 4px; } span.imdbstars, span.imdbstars > * { height: 12px; background: url(../images/rating.png) 0 -12px repeat-x; width: 120px; display: inline-block; vertical-align: top; } span.imdbstars > * { background-position: 0 0; max-width: 120px; } ul.tags { list-style-type: none; position: relative; top: 4px; margin-left: -40px; } ul.tags li { margin-right: 4px; margin-bottom: 5px; padding: 3px 4px 3px 25px; background: url(../images/tag.png) no-repeat scroll 5px 4px #555555; border-radius: 3px; border: 1px solid #111111; color: #FFFFFF; font: 14px/18px roboto, "Open Sans", "Helvetica Neue", Helvetica, Arial, Geneva, sans-serif; text-shadow: 0 1px rgba(0, 0, 0, 0.8); float: left; } ul.tags li a { color: #FFFFFF; } .tvshowImg { border: 1px solid #CCCCCC; border-radius: 5px; max-height: 311px; margin: 0 auto; } #summary { margin-top: 5px; margin-bottom: 5px; padding: 10px; background-color: #EFEFEF; border: 1px solid #DFDEDE; width: 100%; overflow: auto; cursor: default; opacity: 0.8; } .summaryTable { overflow: hidden; } #checkboxControls { padding-top: 5px; } #checkboxControls span { padding: 5px; font-size: 13px; font-weight: bold; border-radius: 5px; } #checkboxControls label { white-space: nowrap; display: inline-block; margin: 7px 2px; } .unaired { background-color: #F5F1E4; } .skipped { background-color: #BEDEED; } .good { background-color: #C3E3C8; } .qual { background-color: #FFDA8A; } .wanted { background-color: #FFB0B0; } .snatched { background-color: #EBC1EA; } span.unaired { color: #584B20; border: 1px solid #584B20; } span.skipped { color: #1D5068; border: 1px solid #1D5068; } span.good { color: #295730; border: 1px solid #295730; } span.qual { color: #765100; border: 1px solid #765100; } span.wanted { color: #890000; border: 1px solid #890000; } span.snatched { color: #652164; border: 1px solid #652164; } span.unaired b, span.skipped b, span.good b, span.qual b, span.wanted b, span.snatched b { color: #000000; font-weight: 800; } .plotInfo { cursor: help; float: right; position: relative; top: 2px; } .plotInfoNone { cursor: help; float: right; position: relative; top: 2px; opacity: 0.4; } .displayShowTable { table-layout: auto; width: 100%; border-collapse: collapse; border-spacing: 0; text-align: center; border: none; empty-cells: show; color: #000000 !important; } .displayShowTable.display_show { clear: both; opacity: 0.8; } .displayShowTable th.row-seasonheader { border: none !important; background-color: #FFFFFF; color: #FFFFFF !important; padding-top: 15px !important; text-align: left !important; } .displayShowTable td.col-search { text-align: center; } .sickbeardTable { table-layout: auto; width: 100%; border-collapse: collapse; border-spacing: 0; text-align: center; border: none; empty-cells: show; } .sickbeardTable.display_show { clear: both } .sickbeardTable th { color: #FFFFFF; text-align: center; background-color: #333333; white-space: nowrap; } .sickbeardTable th, .sickbeardTable td { border-top: 1px solid #FFFFFF; border-left: 1px solid #FFFFFF; padding: 4px; } th.row-seasonheader { border: none; background-color: #FFFFFF; color: #000000; padding-top: 15px; text-align: left; } tr.seasonheader { padding-bottom: 5px; padding-top: 10px; text-align: left; border: none; color: #FFFFFF; } th.col-checkbox, td.col-checkbox { width: 30px; border-left: none; text-align: center; } th.col-checkbox input[type="checkbox"], td.col-checkbox input[type="checkbox"] { vertical-align: -2px; } th.col-metadata, td.col-metadata { width: 28px; } th.col-ep, td.col-ep { width: 50px; white-space: nowrap; } th.col-airdate, td.col-airdate { width: 86px; white-space: nowrap; } th.col-name, td.col-name { min-width: 100px; } td.col-name { text-align: left; } th.col-subtitles, td.col-subtitles { width: 150px; text-align: center; } th.col-status, td.col-status { width: 230px; text-align: center; } th.col-quality, td.col-quality { width: 110px; } th.col-legend, td.col-legend { width: 80px; } th.col-search, td.col-search { width: 46px; } .showLegend { padding-right: 6px; padding-bottom: 1px; width: 150px; } .input-scene { height: 20px; line-height: 1.5; border-radius: 3px; } #editShow { width: 700px; padding-top: 10px; margin-right: auto; margin-left: auto; } [class^="displayshow-icon-"], [class*=" displayshow-icon-"] { background: url("../images/16px_sprite_colored_show.png"); height: 16px; width: 16px; display: inline-block; position: relative; top: 3px; } .displayshow-icon-left { background-position: 0 0; } .displayshow-icon-right { background-position: -18px 0; } .displayshow-icon-imdb { background-position: -37px 0; } .displayshow-icon-tvdb { background-position: -56px 0; } .displayshow-icon-tvrage { background-position: -76px 0; } .displayshow-icon-tvmaze { background-position: -95px 0; } .displayshow-icon-sportdb { background-position: -113px 0; } .displayshow-icon-tmdb { background-position: -129px 0; } .displayshow-icon-anime { background-position: -150px 0; } .displayshow-icon-xem { background-position: -170px 0; } .displayshow-icon-disable { background-position: -190px 0; } .displayshow-icon-enable { background-position: -206px 0; } .displayshow-icon-sub { background-position: -224px 0; } .displayshow-icon-search { background-position: -243px 0; } .displayshow-icon-info { background-position: -261px 0; } .displayshow-icon-heart { background-position: -278px 0; } .displayshow-icon-legend { background-position: -297px 0; margin-top: 10px; } .displayshow-icon-warning { background-position: -316px 0; } .displayshow-icon-tag { background-position: -333px 0; } .displayshow-icon-clock { background-position: -350px 0; } .displayshow-icon-minus { background-position: -369px 0; } .displayshow-icon-plus { background-position: -387px 0; } .displayshow-icon-good { background-position: -403px 0; } .displayshow-icon-bad { background-position: -421px 0; } .displayshow-icon-fanart { background-position: -439px 0; } /* ======================================================================= schedule.mako ========================================================================== */ .key { margin-bottom: 20px; } .listing-key { padding: 5px; font-size: 13px; font-weight: bold; border-radius: 5px; } .listing-default { background-color: #F5F1E4; } .listing-current { background-color: #DDFFDD; } .listing-overdue { background-color: #FFDDDD; } .listing-toofar { background-color: #BEDEED; } span.listing-default { color: #826F30; border: 1px solid #826F30; } span.listing-current { color: #295730; border: 1px solid #295730; } span.listing-overdue { color: #890000; border: 1px solid #890000; } span.listing-toofar { color: #1D5068; border: 1px solid #1D5068; } h2.day, h2.network { margin: 0 0 10px 0; font-size: 24px; line-height: 36px; font-weight: bold; letter-spacing: 1px; color: #FFFFFF; text-align: center; text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3); background-color: #333333; } .tvshowDiv { display: block; clear: both; border: 1px solid #CCCCCC; margin: auto; padding: 0; text-align: left; width: 100%; border-radius: 5px; background: #FFFFFF; cursor: default; overflow: hidden; } .tvshowDiv a:hover { color: #428BCA; } .tvshowDiv a, .tvshowDiv a:link, .tvshowDiv a:visited, .tvshowDiv a:hover { text-decoration: none; background: none; } .tvshowTitle a { color: #000000; float: left; line-height: 1.4em; font-size: 1.4em; text-shadow: -1px -1px 0 #FFFFFF; } .tvshowTitleIcons { float: right; padding: 3px 5px; } .tvshowDiv td { padding: 5px 10px; } .tvshowDiv td.next_episode { width: 100%; height: 90%; border-bottom: 1px solid #CCCCCC; vertical-align: top; color: #000000; } .bannerThumb { vertical-align: top; height: auto; width: 100%; border-bottom: 1px solid #CCCCCC; } .posterThumb { vertical-align: top; height: auto; width: 180px; border-right: 1px solid #CCCCCC; } .ep_listing { width: auto; border: 1px solid #CCCCCC; margin-bottom: 10px; padding: 10px; } .ep_summary { margin-left: 5px; font-style: italic; } .ep_summaryTrigger { cursor: pointer; vertical-align: middle; } .ep_summaryTriggerNone { opacity: 0.4; vertical-align: middle; } .calendarWrapper { width: 1000px; margin: 0 auto; padding: 0 3px } .calendarTable { float: left; width: 142px !important; white-space: nowrap; table-layout: fixed !important; } .calendarShow { padding: 0 !important } .calendarShow .poster { padding-bottom: 2px } .calendarShow .poster img { width: 142px; height: auto } .calendarShow .text { padding: 0 5px 10px 5px } .calendarShow .text .airtime, .calendarShow .text .episode-title { overflow: hidden; text-overflow: ellipsis; display: block; font-size: 11px } .calendarShow .show-status { padding: 5px 10px 10px; text-align: center } table.cal-odd { background-color: #DDDDDD; } table.cal-even { background-color: #D2D2D2; } .calendarShow .text .airtime { color: #000000 } .calendarShow .text .episode-title { color: #888888 } /* ======================================================================= config*.mako ========================================================================== */ #config-content { display: block; width: 960px; padding: 0 0 40px; margin: 0 auto; clear: both; text-align: left; } #config input[type=checkbox] ~ label { padding-top: 4px; } .config-group-divider { margin: 20px 0; border-bottom: 1px dotted #CCCCCC; } .component-group { padding: 25px 0; border-bottom: 1px dotted #CCCCCC; } .component-item { border-bottom: 1px dotted #666666; min-height: 200px; } .component-group-desc { float: left; } .component-group-desc h3 { margin-top: 5px; } .component-group-desc p { width: 90%; margin: 10px 0; color: #666666; } #config div.field-pair { padding: 12px 0; } #config div.field-pair select, #config div.field-pair input { margin-right: 6px; } #config div.field-pair input { float: left; } #config label.component-title, #config span.component-title { float: left; margin-right: 10px; font-size: 13px; font-weight: bold; } #config .component-desc { font-size: 12px; font-weight: normal; display: block; } #config label.space-right { margin-right: 10px } #config .metadataDiv { display: none; } .component-group-save { float: right; padding-top: 10px; } select .selected { font-weight: 700; } .jumbo { font-size: 15px !important; line-height: 24px; } .testNotification { padding: 5px; margin-bottom: 10px; line-height: 20px; border: 1px dotted #CCCCCC; } #providerOrderList { width: 250px; padding-left: 20px; list-style-type: none; } #provider_order_list, #service_order_list { width: 250px; padding-left: 20px; list-style-type: none; } #provider_order_list li, #service_order_list li { padding: 5px; margin: 5px 0; font-size: 14px; } #provider_order_list .ui-state-default.torrent-provider { background-color: #FFFFFF !important; } #provider_order_list .ui-state-default.nzb-provider { background-color: #DDDDDD !important; } #provider_order_list input, #service_order_list input { margin: 0 2px; } #config .tip_scale label span.component-title { width: 85px !important; font-size: 12px !important; margin-top: 2px !important; } #config .tip_scale label span.component-desc { margin-left: 120px !important; width: 220px !important; } .infoTableHeader, .infoTableCell { padding: 5px; } .infoTableSeperator { border-top: 1px dotted #666666; } .infoTableHeader { vertical-align: top; } [class^="icon16-config-"], [class*=" icon16-config-"] { background: url("../images/16px_sprite_colored_help-info.png") no-repeat -40px 0; display: inline-block; height: 16px; width: 16px; line-height: 16px; vertical-align: text-top; } .icon16-config-sickrage { background-position: 0 0; } .icon16-config-version { background-position: -17px 0; } .icon16-config-python { background-position: -37px 0; } .icon16-config-ssl { background-position: -56px 0; } .icon16-config-locale { background-position: -73px 0; } .icon16-config-user { background-position: -91px 0; } .icon16-config-dir { background-position: -111px 0; } .icon16-config-config { background-position: -129px 0; } .icon16-config-db { background-position: -147px 0; } .icon16-config-cache { background-position: -166px 0; } .icon16-config-log { background-position: -182px 0; } .icon16-config-arguments { background-position: -204px 0; } .icon16-config-github { background-position: -224px 0; } .icon16-config-mirc { background-position: -243px 0; } .icon16-config-web { background-position: -262px 0; } .icon16-config-os { background-position: -280px 0; } .icon16-config-wiki { background-position: -299px 0; } [class^="add-client-icon-"], [class*=" add-client-icon-"] { background: url("../images/32px_sprite_colored_clients.png"); height: 32px; width: 32px; display: inline-block; position: relative; top: 2px; float: left; } .add-client-icon-sabnzbd { background-position: 0 0; } .add-client-icon-nzbget { background-position: -34px 0; } .add-client-icon-blackhole { background-position: -71px 0; } .add-client-icon-deluge { background-position: -106px 0; } .add-client-icon-deluged { background-position: -106px 0; } .add-client-icon-qbittorrent { background-position: -138px 0; } .add-client-icon-rtorrent { background-position: -172px 0; } .add-client-icon-download-station { background-position: -205px 0; } .add-client-icon-transmission { background-position: -241px 0; } .add-client-icon-utorrent { background-position: -273px 0; } .add-client-icon-spotnet { background-position: -311px 0; } .add-client-icon-mlnet { background-position: -344px 0; } .add-client-icon-rss { background-position: -380px 0; } .add-client-icon-folder { background-position: -416px 0; } .add-client-icon-ftp { background-position: -452px 0; } .add-client-icon-irc { background-position: -488px 0; } .add-client-icon-putio { background-position: -517px 0; } /* ======================================================================= config_postProcessing.mako ========================================================================== */ #config div.example { padding: 10px; background-color: #EFEFEF; } .Key { width: 100%; padding: 6px; font-size: 13px; background-color: #F4F4F4; border: 1px solid #CCCCCC; border-collapse: collapse; border-spacing: 0; } .Key th, .tableHeader { padding: 3px 9px; margin: 0; color: #FFFFFF; text-align: center; background: none repeat scroll 0 0 #666666; } .Key td { padding: 1px 5px !important; } .Key tr { border-bottom: 1px solid #CCCCCC; } .Key tr.even { background-color: #DFDEDE; } .legend { position: relative; top: 2px; } /* ======================================================================= config_notifications.mako ========================================================================== */ div.metadata_options { padding: 7px; overflow: auto; background: #F5F1E4; border: 1px solid #CCCCCC; } div.metadata_options label:hover { color: #FFFFFF; background-color: #57442B; cursor: pointer; } div.metadata_options label { display: block; padding-left: 7px; line-height: 20px; color: #003366; } div.metadata_example { padding: 8px; } div.metadata_example label { display: block; line-height: 21px; color: #000000; cursor: pointer; } div.metadataDiv .disabled { color: #CCCCCC; } .notifier-icon { float: left; margin: 6px 4px 0 0; } .warning { border-color: #F89406; background: url("../images/warning16.png") no-repeat right 5px center #FFFFFF; } [class^="icon-notifiers-"], [class*=" icon-notifiers-"] { background: url("../images/32px_sprite_colored_notifiers.png"); height: 32px; width: 32px; display: inline-block; position: relative; right: 5px; top: 2px; float: left; } .icon-notifiers-slack { background: url("../images/Slack_Mark_Web.png"); background-size: 32px; } .icon-notifiers-kodi { background-position: 0 0; } .icon-notifiers-plex { background-position: -35px 0; } .icon-notifiers-plexth { background-position: -69px 0; } .icon-notifiers-emby { background-position: -104px 0; } .icon-notifiers-nmj { background-position: -136px 0; } .icon-notifiers-syno1 { background-position: -168px 0; } .icon-notifiers-syno2 { background-position: -202px 0; } .icon-notifiers-pytivo { background-position: -238px 0; } .icon-notifiers-growl { background-position: -272px 0; } .icon-notifiers-prowl { background-position: -310px 0; } .icon-notifiers-libnotify { background-position: -345px 0; } .icon-notifiers-pushover { background-position: -377px 0; } .icon-notifiers-boxcar2 { background-position: -414px 0; } .icon-notifiers-nma { background-position: -450px 0; } .icon-notifiers-pushalot { background-position: -487px 0; } .icon-notifiers-pushbullet { background-position: -519px 0; } .icon-notifiers-freemobile { background-position: -551px 0; } .icon-notifiers-telegram { background-position: -588px 0; } .icon-notifiers-join { background-position: -802px 0; } .icon-notifiers-twitter { background-position: -624px 0; } .icon-notifiers-twilio { background-position: -836px 0; } .icon-notifiers-trakt { background-position: -660px 0; } .icon-notifiers-email { background-position: -695px 0; } .icon-notifiers-anime { background-position: -733px 0; } .icon-notifiers-look { background-position: -769px 0; } /* ======================================================================= manage*.mako ========================================================================== */ .manageTable th { white-space: normal; line-height: 24px; } .manageTable td.tableright { text-align: left; } td.tableright { text-align: center; } .optionWrapper { width: 450px; margin-left: auto; margin-right: auto; padding: 6px 12px; } .optionWrapper span.selectTitle { float: left; text-align: left; vertical-align: middle; width: 225px; padding: 6px 0; } .optionWrapper div.selectChoices { float: left; width: 175px; margin-left: 25px; } .optionWrapper br { clear: both; } .manageCustom { text-align: center; padding: 6px; margin-left: 25px; } .separator { font-size: 90%; color: #333333; } a.whitelink { color: #FFFFFF; } #failedTable tbody span { word-break: break-all; } /* ======================================================================= Global ========================================================================== */ .header { margin-top: 0; } span.path { padding: 3px 6px; color: #8B0000; background-color: #F5F1E4; } span.config-path-title { padding: 3px 0; display: inline-block; } .align-left { text-align: left; } .h2footer { margin: -45px 0 8px; line-height: 18px; } span.quality { font: 12px/13px "Open Sans", verdana, sans-serif; background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.25)); background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.25)); background-image: -o-linear-gradient(top, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.25)); background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.25)); -webkit-box-shadow: inset 0 1px rgba(255, 255, 255, 0.1), inset 0 -1px 3px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(255, 255, 255, 0.08), 0 1px 2px rgba(0, 0, 0, 0.15); box-shadow: inset 0 1px rgba(255, 255, 255, 0.1), inset 0 -1px 3px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(255, 255, 255, 0.08), 0 1px 2px rgba(0, 0, 0, 0.15); text-shadow: 0 1px rgba(0, 0, 0, 0.8); color: #FFFFFF; display: inline-block; padding: 2px 4px; text-align: center; vertical-align: baseline; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; white-space: nowrap; } span.any-hd { background: #2672B6 repeating-linear-gradient( -45deg, #2672B6, #2672B6 10px, #5B990D 10px, #5B990D 20px ); } span.Custom { background-color: #621993; } span.HD { background-color: #2672B6; } span.HDTV { background-color: #2672B6; } span.HD720p { background-color: #5B990D; } span.HD1080p { background-color: #2672B6; } span.UHD-4K { background-color: #7500FF; } span.UHD-8K { background-color: #410077; } span.RawHD { background-color: #CD7300; } span.RawHDTV { background-color: #CD7300; } span.SD { background-color: #BE2625; } span.SDTV { background-color: #BE2625; } span.SDDVD { background-color: #BE2625; } span.Any { background-color: #666666; } span.Unknown { background-color: #999999; } span.Proper { background-color: #3F7F00; } span.false { color: #993333; /* red */ } span.true { color: #669966; /* green */ } option.flag { padding-left: 35px; background: no-repeat 10px 50%; } div.fansub-picker h4 { margin: 0 auto; } div.fansub-picker select { width: 100% !important; } /* ======================================================================= bootstrap Overrides ========================================================================== */ body { padding-top: 60px; overflow-y: scroll; font-family: roboto, "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; color: #000000; } html * { outline: 0 !important; } input[type="checkbox"] { margin: 2px 0 0; line-height: normal; } input[type="radio"] { margin: 2px 0 0; line-height: normal; } input, textarea, select, .uneditable-input { width: auto; color: #000000; } pre { color: #000000; background-color: #F5F5F5; border-color: #CCCCCC; white-space: pre-line; } .navbar-brand { padding: 0; } /* navbar styling */ .navbar-default { background-color: #333333; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#555555', endColorstr='#333333'); background: -webkit-gradient(linear, left top, left bottom, from(#555555), to(#333333)); background: -moz-linear-gradient(top, #555555, #333333); border-color: #3E3F3A; } .navbar-default .navbar-collapse, .navbar-default .navbar-form { border-color: #3E3F3A; } .navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus { background-color: #333333; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { color: #FFFFFF; text-decoration: none; background-color: #333333; } .navbar-default .navbar-brand { color: #FFFFFF; } .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus { color: #FFFFFF; background-color: transparent; } .navbar-default .navbar-text { color: #DDDDDD; } .navbar-default .navbar-nav > li > a { color: #DDDDDD; } .navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus { color: #FFFFFF; } .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus { color: #FFFFFF; background-color: #333333; } .navbar-default .navbar-nav > .disabled > a, .navbar-default .navbar-nav > .disabled > a:hover, .navbar-default .navbar-nav > .disabled > a:focus { color: #CCCCCC; background-color: transparent; } .navbar-default .navbar-toggle { border-color: #CCCCCC; } .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus { background-color: #333333; } .navbar-default .navbar-toggle .icon-bar { background-color: #333333; } .navbar-default .navbar-toggle:hover .icon-bar, .navbar-default .navbar-toggle:focus .icon-bar { background-color: #15528F; } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus { background-color: #333333; color: #FFFFFF; } .navbar-default .navbar-nav > li.navbar-split > a { display: inline-block; float: left; } .navbar-default .navbar-nav > li.navbar-split > a:first-child { padding-right: 8px; } .navbar-default .navbar-nav > li.navbar-split > a:nth-child(2) { padding-left: 8px; } @media (max-width: 767px) { .navbar-default .navbar-nav .open .dropdown-menu > li > a { color: #DDDDDD; } .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus { color: #FFFFFF; background-color: transparent; } .navbar-default .navbar-nav .open .dropdown-menu > .active > a, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus { color: #FFFFFF; background-color: #333333; } .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a, .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus { color: #CCCCCC; background-color: transparent; } } .navbar-default .navbar-link { color: #DDDDDD; } .navbar-default .navbar-link:hover { color: #FFFFFF; } .navbar-default .btn-link { color: #98978B; } .navbar-default .btn-link:hover, .navbar-default .btn-link:focus { color: #DDDDDD; } .navbar-default .btn-link[disabled]:hover, fieldset[disabled] .navbar-default .btn-link:hover, .navbar-default .btn-link[disabled]:focus, fieldset[disabled] .navbar-default .btn-link:focus { color: #CCCCCC; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { color: #262626; text-decoration: none; background-color: #F5F5F5; } .dropdown-menu > li > a { padding: 4px 36px 4px 20px; } .dropdown-menu { background-color: #F5F1E4; border: 1px solid rgba(0, 0, 0, 0.15); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176); } .form-control { color: #000000; } .form-control-inline { min-width: 0; width: auto; display: inline; } .btn { display: inline-block; *display: inline; padding: 4px 10px 4px; margin-bottom: 0; *margin-left: .3em; font-size: 12px; line-height: 16px; *line-height: 20px; color: #333333; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; cursor: pointer; background-color: #F5F5F5; *background-color: #E6E6E6; background-image: -ms-linear-gradient(top, #FFFFFF, #E6E6E6); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#FFFFFF), to(#E6E6E6)); background-image: -webkit-linear-gradient(top, #FFFFFF, #E6E6E6); background-image: -o-linear-gradient(top, #FFFFFF, #E6E6E6); background-image: linear-gradient(top, #FFFFFF, #E6E6E6); background-image: -moz-linear-gradient(top, #FFFFFF, #E6E6E6); background-repeat: repeat-x; border: 1px solid #CCCCCC; *border: 0; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); border-color: #E6E6E6 #E6E6E6 #BFBFBF; border-bottom-color: #B3B3B3; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); *zoom: 1; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); } .modal-header { padding: 9px 15px; border-bottom: 1px solid #EEEEEE; background-color: #F5F1E4; -webkit-border-top-left-radius: 5px; -webkit-border-top-right-radius: 5px; -moz-border-radius-topleft: 5px; -moz-border-radius-topright: 5px; border-top-left-radius: 5px; border-top-right-radius: 5px; } .btn:hover, .btn:active, .btn.active, .btn.disabled, .btn[disabled] { background-color: #E6E6E6; *background-color: #D9D9D9; } .btn:active, .btn.active { background-color: #CCCCCC \9; } .btn:first-child { *margin-left: 0; } .btn:hover { color: #333333; text-decoration: none; *background-color: #D9D9D9; background: #E6E6E6 0 -15px; -webkit-transition: background-position 0.1s linear; -moz-transition: background-position 0.1s linear; -ms-transition: background-position 0.1s linear; -o-transition: background-position 0.1s linear; transition: background-position 0.1s linear; } .btn:focus { outline: thin dotted #333333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .btn.active, .btn:active { background-color: #D9D9D9 \9; background: #E6E6E6 none; outline: 0; -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); } .btn.disabled, .btn[disabled] { cursor: default; background: #E6E6E6 none; opacity: 0.65; filter: alpha(opacity=65); -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .btn-large { padding: 9px 14px; font-size: 15px; line-height: normal; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .btn-large [class^="icon-"] { margin-top: 1px; } .btn-small { padding: 5px 9px; font-size: 11px; line-height: 16px; } .btn-small [class^="icon-"] { margin-top: -1px; } .btn-mini { padding: 2px 6px; font-size: 11px; line-height: 14px; } .btn-primary, .btn-primary:hover, .btn-warning, .btn-warning:hover, .btn-danger, .btn-danger:hover, .btn-success, .btn-success:hover, .btn-info, .btn-info:hover, .btn-inverse, .btn-inverse:hover { color: #FFFFFF; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .btn-primary.active, .btn-warning.active, .btn-danger.active, .btn-success.active, .btn-info.active, .btn-inverse.active { color: rgba(255, 255, 255, 0.75); } .btn-primary { background-color: #0074CC; *background-color: #0055CC; background-image: -ms-linear-gradient(top, #0088CC, #0055CC); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088CC), to(#0055CC)); background-image: -webkit-linear-gradient(top, #0088CC, #0055CC); background-image: -o-linear-gradient(top, #0088CC, #0055CC); background-image: -moz-linear-gradient(top, #0088CC, #0055CC); background-image: linear-gradient(top, #0088CC, #0055CC); background-repeat: repeat-x; border-color: #0055CC #0055CC #003580; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:dximagetransform.microsoft.gradient(startColorstr='#0088cc', endColorstr='#0055cc', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); } .btn-primary:hover, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { background-color: #0055CC; *background-color: #004AB3; } .btn-primary:active, .btn-primary.active { background-color: #004099 \9; } .btn-warning { background-color: #FAA732; *background-color: #F89406; background-image: -ms-linear-gradient(top, #FBB450, #F89406); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#FBB450), to(#F89406)); background-image: -webkit-linear-gradient(top, #FBB450, #F89406); background-image: -o-linear-gradient(top, #FBB450, #F89406); background-image: -moz-linear-gradient(top, #FBB450, #F89406); background-image: linear-gradient(top, #FBB450, #F89406); background-repeat: repeat-x; border-color: #F89406 #F89406 #AD6704; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fbb450', endColorstr='#f89406', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); } .btn-warning:hover, .btn-warning:active, .btn-warning.active, .btn-warning.disabled, .btn-warning[disabled] { background-color: #F89406; *background-color: #DF8505; } .btn-warning:active, .btn-warning.active { background-color: #C67605 \9; } .btn-danger { background-color: #DA4F49; *background-color: #BD362F; background-image: -ms-linear-gradient(top, #EE5F5B, #BD362F); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#EE5F5B), to(#BD362F)); background-image: -webkit-linear-gradient(top, #EE5F5B, #BD362F); background-image: -o-linear-gradient(top, #EE5F5B, #BD362F); background-image: -moz-linear-gradient(top, #EE5F5B, #BD362F); background-image: linear-gradient(top, #EE5F5B, #BD362F); background-repeat: repeat-x; border-color: #BD362F #BD362F #802420; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#bd362f', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); } .btn-danger:hover, .btn-danger:active, .btn-danger.active, .btn-danger.disabled, .btn-danger[disabled] { background-color: #BD362F; *background-color: #A9302A; } .btn-danger:active, .btn-danger.active { background-color: #942A25 \9; } .btn-success { background-color: #5BB75B; *background-color: #51A351; background-image: -ms-linear-gradient(top, #62C462, #51A351); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62C462), to(#51A351)); background-image: -webkit-linear-gradient(top, #62C462, #51A351); background-image: -o-linear-gradient(top, #62C462, #51A351); background-image: -moz-linear-gradient(top, #62C462, #51A351); background-image: linear-gradient(top, #62C462, #51A351); background-repeat: repeat-x; border-color: #51A351 #51A351 #387038; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:dximagetransform.microsoft.gradient(startColorstr='#62c462', endColorstr='#51a351', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); } .btn-success:hover, .btn-success:active, .btn-success.active, .btn-success.disabled, .btn-success[disabled] { background-color: #51A351; *background-color: #499249; } .btn-success:active, .btn-success.active { background-color: #408140 \9; } .btn-info { background-color: #49AFCD; *background-color: #2F96B4; background-image: -ms-linear-gradient(top, #5BC0DE, #2F96B4); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5BC0DE), to(#2F96B4)); background-image: -webkit-linear-gradient(top, #5BC0DE, #2F96B4); background-image: -o-linear-gradient(top, #5BC0DE, #2F96B4); background-image: -moz-linear-gradient(top, #5BC0DE, #2F96B4); background-image: linear-gradient(top, #5BC0DE, #2F96B4); background-repeat: repeat-x; border-color: #2F96B4 #2F96B4 #1F6377; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:dximagetransform.microsoft.gradient(startColorstr='#5bc0de', endColorstr='#2f96b4', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); } .btn-info:hover, .btn-info:active, .btn-info.active, .btn-info.disabled, .btn-info[disabled] { background-color: #2F96B4; *background-color: #2A85A0; } .btn-info:active, .btn-info.active { background-color: #24748C \9; } .btn-inverse { background-color: #414141; *background-color: #222222; background-image: -ms-linear-gradient(top, #555555, #222222); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#555555), to(#222222)); background-image: -webkit-linear-gradient(top, #555555, #222222); background-image: -o-linear-gradient(top, #555555, #222222); background-image: -moz-linear-gradient(top, #555555, #222222); background-image: linear-gradient(top, #555555, #222222); background-repeat: repeat-x; border-color: #222222 #222222 #000000; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:dximagetransform.microsoft.gradient(startColorstr='#555555', endColorstr='#222222', GradientType=0); filter: progid:dximagetransform.microsoft.gradient(enabled=false); } .btn-inverse:hover, .btn-inverse:active, .btn-inverse.active, .btn-inverse.disabled, .btn-inverse[disabled] { background-color: #222222; *background-color: #151515; } .btn-inverse:active, .btn-inverse.active { background-color: #080808 \9; } .btn-xs { padding: 1px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; } @media (min-width: 768px) { .navbar .nav > li > .dropdown-menu:after { position: absolute; top: -6px; right: 12px; display: inline-block; border-right: 6px solid transparent; border-bottom: 6px solid #F5F1E4; border-left: 6px solid transparent; content: ""; } } label { font-weight: normal; } pre { border: 1px solid; } .alert { padding: 10px; text-align: center; } /* ======================================================================= input sizing (for config pages) ========================================================================== */ #config select { min-width: 0; display: inline; } .btn-inline { margin-top: -3px; } .input75 { max-width: 75px; margin-top: -4px; } .input100 { max-width: 100px; margin-top: -4px; } .input150 { max-width: 150px; margin-top: -4px; } .input200 { max-width: 200px; margin-top: -4px; } .input250 { max-width: 250px; margin-top: -4px; } .input300 { max-width: 300px; margin-top: -4px; } .input350 { max-width: 350px; margin-top: -4px; } /* ======================================================================= formWizard.css ========================================================================== */ fieldset.sectionwrap { width: 800px; padding: 5px; text-align: left; border-width: 0; } legend.legendStep { color: #57442B; margin-bottom: 0; } div.stepsguide { margin-bottom: 15px; overflow: hidden; text-align: left; cursor: pointer; } div.stepsguide .step { float: left; width: 33%; font: bold 24px Arial; } div.stepsguide .step p { margin: 12px 0; border-bottom: 4px solid #57442B; } div.stepsguide .disabledstep { color: #C4C4C4; } div.stepsguide .disabledstep p { border-bottom: 4px solid #8A775E; } div.stepsguide .step .smalltext { font-size: 13px; font-weight: normal; } div.formpaginate { padding: 0 20px; margin-top: 1em; overflow: auto; font-weight: bold; text-align: center; } div.formpaginate .prev, div.formpaginate .next { padding: 3px 6px; color: #FFFFFF; cursor: hand; cursor: pointer; background: #57442B; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .stepDiv { padding: 15px 0; } #tabs .nocheck, .stepDiv .nocheck { padding-left: 16px; } #tabs label span.component-title, .stepDiv label span.component-title { padding-bottom: 10px; float: left; width: 172px; margin-right: 10px; font-size: 13px; font-weight: bold; } #tabs label span.component-desc, .stepDiv label span.component-desc { padding-bottom: 10px; font-size: 12px; font-weight: normal; display: block; width: 475px; margin-left: 182px; } div.field-pair select, div.field-pair input { margin: 6px 6px 6px 0; float: left; } /* step 3 related */ #customQuality { display: block; padding: 10px 0; overflow: hidden; clear: both; } #customQualityWrapper div.component-group-desc { float: left; width: 172px; margin-right: 10px; } #customQualityWrapper div.component-group-desc p { width: 85%; margin: .8em 0; font-size: 1.13em; color: #666666; } /* ======================================================================= tablesorter.css ========================================================================== */ .tablesorter { width: 100%; margin-right: auto; margin-left: auto; color: #000000; text-align: left; background-color: #DDDDDD; border-spacing: 0; } .tablesorter th, .tablesorter td { padding: 4px; border-top: #FFFFFF 1px solid; border-left: #FFFFFF 1px solid; vertical-align: middle; } /* remove extra border from left edge */ .tablesorter th:first-child, .tablesorter td:first-child { border-left: none; } .tablesorter th { color: #FFFFFF; text-align: center; text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3); background-color: #333333; border-collapse: collapse; font-weight: normal; } .tablesorter .tablesorter-header { padding: 4px 18px 4px 18px; cursor: pointer; background: inherit url(data:image/gif;base64,R0lGODlhFQAJAIAAAP///////yH5BAEAAAEALAAAAAAVAAkAAAIXjI+AywnaYnhUMoqt3gZXPmVg94yJVQAAOw==) no-repeat center right; } .tablesorter thead .tablesorter-headerDesc { background: #555555 url(data:image/gif;base64,R0lGODlhFQAEAIAAAP///////yH5BAEAAAEALAAAAAAVAAQAAAINjB+gC+jP2ptn0WskLQA7) no-repeat center right; } .tablesorter thead .tablesorter-headerAsc { background: #555555 url(data:image/gif;base64,R0lGODlhFQAEAIAAAP///////yH5BAEAAAEALAAAAAAVAAQAAAINjI8Bya2wnINUMopZAQA7) no-repeat center right; } .tablesorter thead .sorter-false { background-image: none; padding: 4px; cursor: default; } thead.tablesorter-stickyHeader { border-top: 2px solid #FFFFFF; border-bottom: 2px solid #FFFFFF; } /* Zebra Widget - row alternating colors */ .tablesorter tr.odd, .sickbeardTable tr.odd { background-color: #F5F1E4; } .tablesorter tr.even, .sickbeardTable tr.even { background-color: #DFDACF; } /* filter widget */ .tablesorter .filtered { display: none; } .tablesorter input.tablesorter-filter { width: 98%; height: auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .tablesorter tr.tablesorter-filter-row, .tablesorter tr.tablesorter-filter-row td { text-align: center; background: #EEEEEE; border-bottom: 1px solid #DDDDDD; } /* hidden filter row */ .tablesorter-filter-row.hideme td { /*** *********************************************** ***/ /*** change this padding to modify the thickness ***/ /*** of the closed filter row (height = padding x 2) ***/ padding: 2px; /*** *********************************************** ***/ margin: 0; line-height: 0; cursor: pointer; } .tablesorter-filter-row.hideme * { height: 1px; min-height: 0; border: 0; padding: 0; margin: 0; /* don't use visibility: hidden because it disables tabbing */ opacity: 0; filter: alpha(opacity=0); } /* optional disabled input styling */ .tablesorter input.tablesorter-filter-row .disabled { display: none; } .tablesorter-header-inner { padding: 0 2px; text-align: center; } .tablesorter tfoot tr { color: #FFFFFF; text-align: center; text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3); background-color: #333333; border-collapse: collapse; } .tablesorter tfoot a { color: #FFFFFF; text-decoration: none; } /* ======================================================================= token-input.css ========================================================================== */ ul.token-input-list { overflow: hidden; height: auto !important; height: 1%; width: 273px; border: 1px solid #CCCCCC; cursor: text; font-size: 10px; z-index: 999; margin: 0; padding: 0 0 1px 0; background-color: #FFFFFF; list-style-type: none; border-radius: 3px; } ul.token-input-list li { list-style-type: none; } ul.token-input-list li input { border: 0; padding: 3px 4px; background-color: white; } li.token-input-token { overflow: hidden; height: auto !important; height: 1%; margin: 3px; padding: 3px 5px 0 5px; background-color: #D0EFA0; color: #000000; font-weight: bold; cursor: default; display: block; } li.token-input-token img { padding-right: 4px; float: left; } li.token-input-token input { padding-top: 2px !important; padding-right: 4px !important; float: left; } li.token-input-token p { float: left; padding: 0; margin: 0; line-height: 2.0 !important; } li.token-input-token span { float: right; color: #777777; cursor: pointer; } li.token-input-selected-token { background-color: #08844E; color: #FFFFFF; } li.token-input-selected-token span { color: #BBBBBB; } li.token-input-input-token input { margin: 3px 3px 3px 3px !important; } div.token-input-dropdown { position: absolute; width: 273px; overflow: hidden; border-left: 1px solid #CCCCCC; border-right: 1px solid #CCCCCC; border-bottom: 1px solid #CCCCCC; cursor: default; font-size: 11px; z-index: 1; background-color: #FFFFFF; color: #000000; } div.token-input-dropdown p { margin: 0; padding: 3px; font-weight: bold; color: #777777; } div.token-input-dropdown ul { margin: 0; padding: 0; } div.token-input-dropdown ul li { background-color: #FFFFFF; padding: 3px; list-style-type: none; } div.token-input-dropdown ul li.token-input-dropdown-item { background-color: #FAFAFA; } div.token-input-dropdown ul li.token-input-dropdown-item2 { background-color: #FFFFFF; } div.token-input-dropdown ul li em { font-weight: bold; font-style: normal; } div.token-input-dropdown ul li.token-input-selected-dropdown-item { background-color: #6196C2; } span.token-input-delete-token { margin: 0 1px; } .red-text { color: #DD3333 } .clear-left { clear: left } .nextline-block { display: block } .trakt-image { display: block; z-index: 0; background-image: url(../images/poster-dark.jpg) } /* ======================================================================= jquery.confirm.css ========================================================================== */ #confirmOverlay { width: 100%; height: 100%; position: fixed; top: 0; left: 0; background: url('../images/bg.gif'); background: -moz-linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)) repeat-x rgba(0, 0, 0, 0.5); background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0.5))) repeat-x rgba(0, 0, 0, 0.5); z-index: 100000; } #confirmBox { background: #F5F1E4; width: 460px; position: fixed; left: 50%; top: 50%; margin: -130px 0 0 -230px; border: 1px solid #111111; box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.175); } #confirmBox h1, #confirmBox p { padding: 6px 10px; } #confirmBox h1 { background-color: #333333; border-bottom: 1px solid #111111; color: #FFFFFF; margin: 0; font-size: 22px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75); } #confirmBox p { padding-top: 20px; color: #000000; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); } #confirmButtons { padding: 15px 0; text-align: center; } #confirmBox .button { margin-right: 15px; padding: 2px 20px; text-decoration: none; display: inline-block; color: #FFFFFF; text-align: center; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75); background-clip: padding-box; border: 1px solid #111111; border-radius: 3px; cursor: pointer; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 51%, rgba(0, 0, 0, 0.25)); background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 51%, rgba(0, 0, 0, 0.25)); background-image: -o-linear-gradient(top, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 51%, rgba(0, 0, 0, 0.25)); background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0) 51%, rgba(0, 0, 0, 0.25)); -webkit-box-shadow: inset 0 1px rgba(255, 255, 255, 0.1), inset 0 -1px 3px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(255, 255, 255, 0.08), 0 1px 2px rgba(0, 0, 0, 0.15); box-shadow: inset 0 1px rgba(255, 255, 255, 0.1), inset 0 -1px 3px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(255, 255, 255, 0.08), 0 1px 2px rgba(0, 0, 0, 0.15); } #confirmBox .button:last-child { margin-right: 0; } #confirmBox .green { background-color: #3F7636; } #confirmBox .green:hover { background-color: #48873E; } #confirmBox .red { background-color: #8D2D2B; } #confirmBox .red:hover { background-color: #A13331; } /* ======================================================================= pnotify.css ========================================================================== */ .ui-pnotify-sticker { margin-top: -12px; } .ui-pnotify-closer { margin-top: -12px; margin-right: -10px; } /* ======================================================================= login.css ========================================================================== */ .login h1 { font-size: 60px; } /* ======================================================================= IMDB Popular ========================================================================== */ .popularShow { margin-bottom: 30px; } .popularShow h3 { padding: 0; display: inline-block; margin: 0 30px 0 0; } .popularShow .left { float: left; width: 100px; } .popularShow .right { float: left; width: 600px; } .popularShow .year { font-style: italic; opacity: 0.7; } .popularShow .coverImage { width: 80%; padding-left: 20px; margin-top: 4px; } .popularShow .rating { font-size: 90%; display: inline-block; margin-left: 0; } .popularShow p { margin-bottom: 0; } input.tablesorter-filter.disabled { display: none; } /* This fixes bold fon be used */ /* @TODO replace this with proper CSS overrides */ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header { font-weight: normal !important; } @media (max-width: 767px) { .pull-xs-left { float: left; } .pull-xs-right { float: right; } .no-padding-xs { padding: 0; } .nocheck { padding-left: 0 !important; } .tvshowImg { margin-bottom: 10px; } .poster-container { display: inline-block; width: 100%; } .poster-container img { display: block; margin: 0 auto; } .info-container { display: block; width: 100%; } .col-md-12 > .horizontal-scroll { margin: 0 -13px; } .pick-show-group { width: 100%; margin: 0 auto; } } @media (min-width: 768px) and (max-width: 991px) { .pull-sm-left { float: left; } .pull-sm-right { float: right; } .no-padding-sm { padding: 0; } .tvshowImg { max-height: 245px; } .poster-container { float:left; display: inline-block; width: 100%; } .poster-container img { display: block; margin: 0 auto; } .info-container { display: block; width: 100%; } .pick-show-group { width: 100%; margin: 0 auto; } } @media (min-width: 992px) and (max-width: 1199px) { .pull-md-left { float: left; } .pull-md-right { float: right; } .tvshowImg { max-height: 269px; } } @media (min-width: 1200px) { .pull-lg-left { float: left; } .pull-lg-right { float: right; } .tvshowImg { max-height: 269px; } } .horizontal-scroll { overflow-x: auto; } #episodeDir { width: 100%; }
jackkiej/SickRage
gui/slick/css/style.css
CSS
gpl-3.0
73,545
/*Copyright (C) 2012-2014 Carsten Paproth This file is part of Skat-Konferenz. Skat-Konferenz is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Skat-Konferenz 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 Skat-Konferenz. If not, see <http://www.gnu.org/licenses/>.*/ #ifndef SK_BIDBUTTON_H #define SK_BIDBUTTON_H #include <FL/Fl_Button.H> #include <set> namespace SK { class BidButton : public Fl_Button { std::set<unsigned> bidorder; std::set<unsigned>::iterator minbid; std::set<unsigned>::iterator maxbid; std::set<unsigned>::iterator bid; bool bidding; int handle(int); public: BidButton(int, int, int, int, const char* = 0); void reset(unsigned, bool); }; } #endif
cpaproth/sk
src/BidButton.h
C
gpl-3.0
1,131
/* * Copyright (C) 2015-2016 Willi Ye <williye97@gmail.com> * * This file is part of Kernel Adiutor. * * Kernel Adiutor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>. * */ package com.hitman.kernelmanager.views.dialog; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.View; import android.view.WindowManager; /** * Created by willi on 07.11.16. */ public class Dialog extends AlertDialog.Builder { private DialogInterface.OnDismissListener mOnDismissListener; public Dialog(Context context) { super(context); } @Override public Dialog setTitle(CharSequence title) { return (Dialog) super.setTitle(title); } @Override public Dialog setTitle(int titleId) { return (Dialog) super.setTitle(titleId); } @Override public Dialog setMessage(CharSequence message) { return (Dialog) super.setMessage(message); } @Override public Dialog setMessage(int messageId) { return (Dialog) super.setMessage(messageId); } @Override public Dialog setView(int layoutResId) { return (Dialog) super.setView(layoutResId); } @Override public Dialog setView(View view) { return (Dialog) super.setView(view); } @Override public Dialog setItems(CharSequence[] items, DialogInterface.OnClickListener listener) { return (Dialog) super.setItems(items, listener); } @Override public Dialog setItems(int itemsId, DialogInterface.OnClickListener listener) { return (Dialog) super.setItems(itemsId, listener); } @Override public Dialog setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) { return (Dialog) super.setPositiveButton(text, listener); } @Override public Dialog setPositiveButton(int textId, DialogInterface.OnClickListener listener) { return (Dialog) super.setPositiveButton(textId, listener); } @Override public Dialog setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) { return (Dialog) super.setNegativeButton(text, listener); } @Override public Dialog setNegativeButton(int textId, DialogInterface.OnClickListener listener) { return (Dialog) super.setNegativeButton(textId, listener); } public Dialog setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) { mOnDismissListener = onDismissListener; setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { if (mOnDismissListener != null) { mOnDismissListener.onDismiss(dialogInterface); } } }); return this; } @Override public AlertDialog show() { try { AlertDialog dialog = create(); dialog.setOnDismissListener(mOnDismissListener); dialog.show(); return dialog; } catch (WindowManager.BadTokenException ignored) { return create(); } } }
hitman-xda/KernelManager
app/src/main/java/com/hitman/kernelmanager/views/dialog/Dialog.java
Java
gpl-3.0
3,786
#ifndef MONEWPROJECT_H #define MONEWPROJECT_H #include "moDirectorTypes.h" #include "moIDirectorActions.h" //(*Headers(moNewProject) #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/button.h> #include <wx/dialog.h> //*) class moNewProject: public wxDialog { public: moNewProject(wxWindow* parent,wxWindowID id=wxID_ANY); virtual ~moNewProject(); const moProjectDescriptor& GetProjectDescriptor() { return m_ProjectDescriptor; } //(*Declarations(moNewProject) wxTextCtrl* DirTextCtrl; wxStaticText* StaticText2; wxButton* ButtonBrowse; wxStaticText* StaticText1; wxButton* OkButton; wxTextCtrl* ProjectNameTextCtrl; wxButton* CancelButton; //*) protected: //(*Identifiers(moNewProject) static const long ID_DIRTEXTCTRL; static const long ID_STATICTEXT1; static const long ID_NEWPROJECT_BROWSE; static const long ID_STATICTEXT2; static const long ID_NAMETEXTCTRL; static const long ID_NEWPROJECT_OK; static const long ID_NEWPROJECT_CANCEL; //*) private: //(*Handlers(moNewProject) void OnOkClick(wxCommandEvent& event); void OnCancelClick(wxCommandEvent& event); void OnBrowseClick(wxCommandEvent& event); void OnDirTextCtrlText(wxCommandEvent& event); void OnProjectNameTextCtrlText(wxCommandEvent& event); //*) moProjectDescriptor m_ProjectDescriptor; DECLARE_EVENT_TABLE() }; #endif
inaes-tic/tv-moldeo
src/moldeodirector/moNewProject.h
C
gpl-3.0
1,406
define( "dojo/cldr/nls/bs/chinese", //begin v1.x content { "field-second-relative+0": "sada", "field-quarter-relative+-1": "posljednji kvartal", "field-weekday": "dan u sedmici", "field-mon-narrow-relative+0": "ovaj pon.", "field-mon-narrow-relative+1": "sljedeći pon.", "field-weekOfMonth-short": "sed. u mj.", "field-weekday-short": "dan u sed.", "field-wed-relative+0": "ova srijeda", "field-wed-relative+1": "sljedeća srijeda", "field-dayperiod-short": "prijepodne/poslijepodne", "field-week-short": "sed.", "field-tue-relative+-1": "prošli utorak", "field-year-short": "god.", "field-era-narrow": "era", "field-thu-narrow-relative+-1": "prošli čet.", "field-hour-relative+0": "ovaj sat", "field-quarter-narrow": "kv.", "field-fri-relative+-1": "prošli petak", "field-hour-short": "h", "field-wed-relative+-1": "prošla srijeda", "field-dayOfYear": "dan u godini", "field-mon-short-relative+-1": "prošli pon.", "field-thu-relative+-1": "prošli četvrtak", "field-era": "era", "field-sat-narrow-relative+0": "ova sub.", "field-sat-narrow-relative+1": "sljedeća sub.", "field-year": "godina", "field-hour": "sat", "field-sat-relative+0": "ova subota", "field-sat-relative+1": "sljedeća subota", "field-sat-short-relative+-1": "prošla sub.", "field-weekOfMonth-narrow": "s. u mj.", "field-minute-narrow": "min.", "field-day-relative+0": "danas", "field-day-relative+1": "sutra", "field-thu-relative+0": "ovaj četvrtak", "field-mon-narrow-relative+-1": "prošli pon.", "field-day-relative+2": "prekosutra", "field-wed-narrow-relative+0": "ova sri.", "field-thu-relative+1": "sljedeći četvrtak", "field-wed-narrow-relative+1": "sljedeća sri.", "field-mon-short-relative+0": "ovaj pon.", "field-mon-short-relative+1": "sljedeći pon", "field-weekdayOfMonth-short": "dan u mj.", "field-wed-short-relative+-1": "prošla sri.", "field-fri-narrow-relative+-1": "prošli pet.", "field-hour-narrow": "h", "field-tue-short-relative+0": "ovaj uto.", "field-year-narrow": "g.", "field-tue-short-relative+1": "sljedeći uto.", "field-minute-short": "min.", "field-day-narrow": "dan", "field-wed-short-relative+0": "ova sri.", "field-wed-short-relative+1": "sljedeća sri.", "field-sun-relative+0": "ova nedjelja", "field-sun-relative+1": "sljedeća nedjelja", "field-minute": "minuta", "field-month-short": "mj.", "field-dayperiod": "prijepodne/poslijepodne", "field-weekdayOfMonth-narrow": "d. u mj.", "field-day-relative+-1": "jučer", "field-day-relative+-2": "prekjučer", "field-minute-relative+0": "ova minuta", "field-week-narrow": "sed.", "field-wed-narrow-relative+-1": "prošla sri.", "field-day-short": "dan", "field-quarter-relative+0": "ovaj kvartal", "field-dayperiod-narrow": "prijepodne/poslijepodne", "field-quarter-relative+1": "sljedeći kvartal", "field-zone-short": "zona", "field-fri-relative+0": "ovaj petak", "field-fri-relative+1": "sljedeći petak", "field-day": "dan", "field-second-narrow": "s", "field-zone": "vremenska zona", "field-year-relative+-1": "prošle godine", "field-month-relative+-1": "prošli mjesec", "field-thu-short-relative+0": "ovaj čet.", "field-thu-short-relative+1": "sljedeći čet.", "field-weekday-narrow": "dan u sed.", "field-quarter": "kvartal", "field-zone-narrow": "zona", "field-month": "mjesec", "field-weekOfMonth": "sedmica u mjesecu", "field-tue-relative+0": "ovaj utorak", "field-tue-relative+1": "sljedeći utorak", "field-fri-narrow-relative+0": "ovaj pet.", "field-fri-narrow-relative+1": "sljedeći pet.", "field-fri-short-relative+-1": "prošli pet.", "field-sun-narrow-relative+-1": "prošla ned.", "field-dayOfYear-short": "dan u god.", "field-sun-narrow-relative+0": "ova ned.", "field-thu-narrow-relative+0": "ovaj čet.", "field-sun-narrow-relative+1": "sljedeća ned.", "field-thu-narrow-relative+1": "sljedeći čet.", "field-tue-narrow-relative+0": "ovaj uto.", "field-mon-relative+0": "ovaj ponedjeljak", "field-tue-narrow-relative+1": "sljedeći uto.", "field-mon-relative+1": "sljedeći ponedjeljak", "field-tue-narrow-relative+-1": "prošli uto.", "field-second-short": "sek.", "field-second": "sekunda", "field-fri-short-relative+0": "ovaj pet.", "field-sat-relative+-1": "prošla subota", "field-fri-short-relative+1": "sljedeći pet.", "field-sun-relative+-1": "prošla nedjelja", "field-month-relative+0": "ovaj mjesec", "field-weekdayOfMonth": "dan u mjesecu", "field-month-relative+1": "sljedeći mjesec", "field-week": "sedmica", "field-sat-short-relative+0": "ova sub.", "field-sat-short-relative+1": "sljedeća sub.", "field-year-relative+0": "ove godine", "field-week-relative+-1": "prošle sedmice", "field-year-relative+1": "sljedeće godine", "field-era-short": "era", "field-quarter-short": "kv.", "field-dayOfYear-narrow": "dan u g.", "field-sun-short-relative+-1": "prošla ned.", "field-thu-short-relative+-1": "prošli čet.", "field-tue-short-relative+-1": "prošli uto.", "field-mon-relative+-1": "prošli ponedjeljak", "field-sat-narrow-relative+-1": "prošla sub.", "field-month-narrow": "mj.", "field-week-relative+0": "ove sedmice", "field-sun-short-relative+0": "ova ned.", "field-week-relative+1": "sljedeće sedmice", "field-sun-short-relative+1": "sljedeća ned." } //end v1.x content );
ustegrew/ustegrew.github.io
courses/it001/lib/dojo/dojo/cldr/nls/bs/chinese.js.uncompressed.js
JavaScript
gpl-3.0
5,329
# Created By: Virgil Dupras # Created On: 2010-02-05 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog from .details_table import DetailsModel class DetailsDialog(QDialog): def __init__(self, parent, app, **kwargs): super().__init__(parent, Qt.Tool, **kwargs) self.app = app self.model = app.model.details_panel self._setupUi() # To avoid saving uninitialized geometry on appWillSavePrefs, we track whether our dialog # has been shown. If it has, we know that our geometry should be saved. self._shown_once = False self.app.prefs.restoreGeometry('DetailsWindowRect', self) self.tableModel = DetailsModel(self.model) # tableView is defined in subclasses self.tableView.setModel(self.tableModel) self.model.view = self self.app.willSavePrefs.connect(self.appWillSavePrefs) def _setupUi(self): # Virtual pass def show(self): self._shown_once = True super().show() #--- Events def appWillSavePrefs(self): if self._shown_once: self.app.prefs.saveGeometry('DetailsWindowRect', self) #--- model --> view def refresh(self): self.tableModel.beginResetModel() self.tableModel.endResetModel()
stuckj/dupeguru
qt/base/details_dialog.py
Python
gpl-3.0
1,600
Evolution 1.3.6 = 957e4d24c7f4f067ce4ea388517cba4d
gohdan/DFC
known_files/hashes/assets/plugins/tinymce4/tinymce/plugins/youtube/css/style.css
CSS
gpl-3.0
51
<?php return [ /* |-------------------------------------------------------------------------- | PDO Fetch Style |-------------------------------------------------------------------------- | | By default, database results will be returned as instances of the PHP | stdClass object; however, you may desire to retrieve records in an | array format for simplicity. Here you can tweak the fetch style. | */ 'fetch' => PDO::FETCH_CLASS, /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mysql'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'database' => database_path('database.sqlite'), 'prefix' => '', ], 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ], 'mysql_test' => [ 'driver' => 'mysql', 'host' => env('DB_HOST_TEST', 'localhost'), 'port' => env('DB_PORT_TEST', '3306'), 'database' => env('DB_DATABASE_TEST', 'forge'), 'username' => env('DB_USERNAME_TEST', 'forge'), 'password' => env('DB_PASSWORD_TEST', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '5432'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ], ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ];
clothesai/api-clothesai
config/database.php
PHP
gpl-3.0
4,517
#!/usr/bin/env python # -*- coding: utf-8 -*- # # line_follower.py # # Copyright 2011 Manuel Martín Ortiz <mmartinortiz@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 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. # -- Line Follower -- # # Program to follow a black line ober white floor # # Requisite: # * ePuck with Webots' firmware 1.4.2 # * ePuck.py Library (>= 0.9) # * Bluetooth device from ePuck import ePuck import time import sys import re # You can use this dictionary to asociate an ePuck ID with its MAC Address epucks = { '1797' : '10:00:E8:6C:A2:B6', '1903' : '10:00:E8:6C:A1:C7' } def log(text): """ Show @text in standart output with colors """ blue = '\033[1;34m' off = '\033[1;m' print(''.join((blue, '[Log] ', off, str(text)))) def error(text): red = '\033[1;31m' off = '\033[1;m' print(''.join((red, '[Error] ', off, str(text)))) def main(mac): global_speed = 180 fs_speed = 0.6 threshold = 1000 log('Conecting with ePuck') try: # First, create an ePuck object. # If you want debug information: #~ robot = ePuck(mac, debug = True) # else: robot = ePuck(mac) # Second, connect to it robot.connect() # You can enable various sensors at the same time. Take a look to # to DIC_SENSORS for know the name of the sensors robot.enable('floor', 'proximity') leds_on = [0] * 8 log('Conection complete. CTRL+C to stop') log('Library version: ' + robot.version) times_got = [] except Exception, e: error(e) sys.exit(1) try: while True: # Important: when you execute 'step()', al sensors # and actuators are updated. All changes you do on the ePuck # will be effectives after this method, not before robot.step() # Now, we can get updated information from the sensors floor_sensors = robot.get_floor_sensors() prox_sensors = robot.get_proximity() # line_follower delta = floor_sensors[2] - floor_sensors[0] l_speed = global_speed - fs_speed * delta r_speed = global_speed + fs_speed * delta # Now, we set the motor speed. Remember that we need to execute 'step()' # for make this command effective robot.set_motors_speed(l_speed, r_speed) # leds on/off for index, s in enumerate(prox_sensors): if int(s) > threshold and leds_on[index] == 0: # Switch On robot.set_led(index, 1) leds_on[index] = 1 elif int(s) < threshold and leds_on[index] == 1: # Switch Off robot.set_led(index, 0) leds_on[index] = 0 except KeyboardInterrupt: log('Stoping the robot. Bye!') robot.close() sys.exit() except Exception, e: error(e) return 0 if __name__ == '__main__': X = '([a-fA-F0-9]{2}[:|\-]?){6}' if len(sys.argv) < 2: error("Usage: " + sys.argv[0] + " ePuck_ID | MAC Address") sys.exit() robot_id = sys.argv[1] if epucks.has_key(robot_id): main(epucks[robot_id]) elif re.match(X, robot_id) != 0: main(robot_id) else: error('You have to indicate the MAC direction of the robot')
mmartinortiz/pyePuck
examples/line_follower.py
Python
gpl-3.0
3,739
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pt"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Sat Dec 21 07:15:40 GMT-03:00 2013 --> <title>D-Index</title> <meta name="date" content="2013-12-21"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="D-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-3.html">Prev Letter</a></li> <li><a href="index-5.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-4.html" target="_top">Frames</a></li> <li><a href="index-4.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">L</a>&nbsp;<a href="index-10.html">M</a>&nbsp;<a href="index-11.html">P</a>&nbsp;<a href="index-12.html">R</a>&nbsp;<a href="index-13.html">S</a>&nbsp;<a href="index-14.html">T</a>&nbsp;<a href="index-15.html">U</a>&nbsp;<a href="index-16.html">V</a>&nbsp;<a name="_D_"> <!-- --> </a> <h2 class="title">D</h2> <dl> <dt><span class="strong"><a href="../br/com/ambiciousteam/pfbistro/logic/LogicImpl.html#dao">dao</a></span> - Variable in class br.com.ambiciousteam.pfbistro.logic.<a href="../br/com/ambiciousteam/pfbistro/logic/LogicImpl.html" title="class in br.com.ambiciousteam.pfbistro.logic">LogicImpl</a></dt> <dd>&nbsp;</dd> <dt><a href="../br/com/ambiciousteam/pfbistro/dao/DaoIF.html" title="interface in br.com.ambiciousteam.pfbistro.dao"><span class="strong">DaoIF</span></a>&lt;<a href="../br/com/ambiciousteam/pfbistro/dao/DaoIF.html" title="type parameter in DaoIF">Serializable</a>&gt; - Interface in <a href="../br/com/ambiciousteam/pfbistro/dao/package-summary.html">br.com.ambiciousteam.pfbistro.dao</a></dt> <dd>&nbsp;</dd> <dt><a href="../br/com/ambiciousteam/pfbistro/dao/DaoImpl.html" title="class in br.com.ambiciousteam.pfbistro.dao"><span class="strong">DaoImpl</span></a> - Class in <a href="../br/com/ambiciousteam/pfbistro/dao/package-summary.html">br.com.ambiciousteam.pfbistro.dao</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../br/com/ambiciousteam/pfbistro/dao/DaoImpl.html#DaoImpl()">DaoImpl()</a></span> - Constructor for class br.com.ambiciousteam.pfbistro.dao.<a href="../br/com/ambiciousteam/pfbistro/dao/DaoImpl.html" title="class in br.com.ambiciousteam.pfbistro.dao">DaoImpl</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">L</a>&nbsp;<a href="index-10.html">M</a>&nbsp;<a href="index-11.html">P</a>&nbsp;<a href="index-12.html">R</a>&nbsp;<a href="index-13.html">S</a>&nbsp;<a href="index-14.html">T</a>&nbsp;<a href="index-15.html">U</a>&nbsp;<a href="index-16.html">V</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-3.html">Prev Letter</a></li> <li><a href="index-5.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-4.html" target="_top">Frames</a></li> <li><a href="index-4.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
AmbiciousTeam/PFBistro
doc/index-files/index-4.html
HTML
gpl-3.0
6,013
<?php /** * LICENSE: * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * @package Bright Game Panel V2 * @version 0.1 * @category Systems Administration * @author warhawk3407 <warhawk3407@gmail.com> @NOSPAM * @copyright Copyleft 2015, Nikita Rousseau * @license GNU General Public License version 3.0 (GPLv3) * @link http://www.bgpanel.net/ */ /** * Little function that will generate a random password * * Some letters and digits have been removed, as they can be mistaken */ function bgp_create_random_password( $length ) { $chars = "abcdefghijkmnpqrstuvwxyz23456789-#@*!_?ABCDEFGHJKLMNPQRSTUVWXYZ"; // Available chars for the password $string = str_shuffle($chars); $pass = substr($string, 0, $length); // Truncate the password to the specified length return $pass; } /** * bgp_get_net_status * * Test if the specified socket is Online or Offline. * * Return string 'Online' || 'Offline' */ function bgp_get_net_status($ip, $port) { if($socket = @fsockopen($ip, $port, $errno, $errstr, 1)) { fclose($socket); return 'Online'; } else { ### //Uncomment the line above for debugging //echo "$errstr ($errno)<br />\n"; ### return 'Offline'; } } /** * Convert bytes to human readable format * * http://codeaid.net/php/convert-size-in-bytes-to-a-human-readable-format-%28php%29 * * @param integer bytes Size in bytes to convert * @return string */ function bgp_bytes_to_size($bytes, $precision = 2) { $kilobyte = 1024; $megabyte = $kilobyte * 1024; $gigabyte = $megabyte * 1024; $terabyte = $gigabyte * 1024; if (($bytes >= 0) && ($bytes < $kilobyte)) { return $bytes . ' B'; } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) { return round($bytes / $kilobyte, $precision) . ' KB'; } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) { return round($bytes / $megabyte, $precision) . ' MB'; } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) { return round($bytes / $gigabyte, $precision) . ' GB'; } elseif ($bytes >= $terabyte) { return round($bytes / $terabyte, $precision) . ' TB'; } else { return $bytes . ' B'; } } /** * Format the mysql timestamp. */ function bgp_format_date( $timestamp ) { if ($timestamp == '0000-00-00 00:00:00' || $timestamp == 'Never') { return 'Never'; } else { $dateTable = date_parse_from_format('Y-m-d H:i:s', $timestamp); return date('l | F j, Y | H:i', mktime($dateTable['hour'], $dateTable['minute'], $dateTable['second'], $dateTable['month'], $dateTable['day'], $dateTable['year'])); } } function bgp_camel_to_underscore($str) { return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str)); } /** * Normalize a file path string * * @param $path string * The path to normalise. * @param $encoding string * The name of the path iconv() encoding. * @return string * The path, normalised. */ function bgp_normalize_path($path, $separator = DIRECTORY_SEPARATOR, $encoding = "UTF-8") { $path = iconv($encoding, "$encoding//IGNORE//TRANSLIT", $path); $parts = explode('/', $path); $safe = array(); foreach ($parts as $idx => $part) { $part = str_replace($separator, '', $part); if (empty($part) || ('.' == $part)) { continue; } elseif ('..' == $part) { array_pop($safe); continue; } else { $safe[] = $part; } } $path = implode($separator, $safe); if (substr($path, -1) == $separator) { $path = substr($path, 0, -1); } return $path; }
warhawk3407/bgpanelv2
app/core/inc/func.inc.php
PHP
gpl-3.0
4,058
/* eslint-disable object-shorthand */ /* global Chart, CustomTooltips, getStyle, hexToRgba */ import $ from 'jquery' /** * -------------------------------------------------------------------------- * CoreUI Free Boostrap Admin Template (v2.1.14): main.js * Licensed under MIT (https://coreui.io/license) * -------------------------------------------------------------------------- */ /* eslint-disable no-magic-numbers */ // Disable the on-canvas tooltip Chart.defaults.global.pointHitDetectionRadius = 1 Chart.defaults.global.tooltips.enabled = false Chart.defaults.global.tooltips.mode = 'index' Chart.defaults.global.tooltips.position = 'nearest' Chart.defaults.global.tooltips.custom = CustomTooltips Chart.defaults.global.tooltips.intersect = true Chart.defaults.global.tooltips.callbacks.labelColor = function (tooltipItem, chart) { return { backgroundColor: chart.data.datasets[tooltipItem.datasetIndex].borderColor } } // eslint-disable-next-line no-unused-vars const cardChart1 = new Chart($('#card-chart1'), { type: 'line', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', backgroundColor: getStyle('--primary'), borderColor: 'rgba(255,255,255,.55)', data: [65, 59, 84, 84, 51, 55, 40] } ] }, options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent' } }], yAxes: [{ display: false, ticks: { display: false, min: 35, max: 89 } }] }, elements: { line: { borderWidth: 1 }, point: { radius: 4, hitRadius: 10, hoverRadius: 4 } } } }) // eslint-disable-next-line no-unused-vars const cardChart2 = new Chart($('#card-chart2'), { type: 'line', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', backgroundColor: getStyle('--info'), borderColor: 'rgba(255,255,255,.55)', data: [1, 18, 9, 17, 34, 22, 11] } ] }, options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent' } }], yAxes: [{ display: false, ticks: { display: false, min: -4, max: 39 } }] }, elements: { line: { tension: 0.00001, borderWidth: 1 }, point: { radius: 4, hitRadius: 10, hoverRadius: 4 } } } }) // eslint-disable-next-line no-unused-vars const cardChart3 = new Chart($('#card-chart3'), { type: 'line', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.2)', borderColor: 'rgba(255,255,255,.55)', data: [78, 81, 80, 45, 34, 12, 40] } ] }, options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ display: false }], yAxes: [{ display: false }] }, elements: { line: { borderWidth: 2 }, point: { radius: 0, hitRadius: 10, hoverRadius: 4 } } } }) // eslint-disable-next-line no-unused-vars const cardChart4 = new Chart($('#card-chart4'), { type: 'bar', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March', 'April'], datasets: [ { label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.2)', borderColor: 'rgba(255,255,255,.55)', data: [78, 81, 80, 45, 34, 12, 40, 85, 65, 23, 12, 98, 34, 84, 67, 82] } ] }, options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ display: false, barPercentage: 0.6 }], yAxes: [{ display: false }] } } }) // eslint-disable-next-line no-unused-vars const mainChart = new Chart($('#main-chart'), { type: 'line', data: { labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S'], datasets: [ { label: 'My First dataset', backgroundColor: hexToRgba(getStyle('--info'), 10), borderColor: getStyle('--info'), pointHoverBackgroundColor: '#fff', borderWidth: 2, data: [165, 180, 70, 69, 77, 57, 125, 165, 172, 91, 173, 138, 155, 89, 50, 161, 65, 163, 160, 103, 114, 185, 125, 196, 183, 64, 137, 95, 112, 175] }, { label: 'My Second dataset', backgroundColor: 'transparent', borderColor: getStyle('--success'), pointHoverBackgroundColor: '#fff', borderWidth: 2, data: [92, 97, 80, 100, 86, 97, 83, 98, 87, 98, 93, 83, 87, 98, 96, 84, 91, 97, 88, 86, 94, 86, 95, 91, 98, 91, 92, 80, 83, 82] }, { label: 'My Third dataset', backgroundColor: 'transparent', borderColor: getStyle('--danger'), pointHoverBackgroundColor: '#fff', borderWidth: 1, borderDash: [8, 5], data: [65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65] } ] }, options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ gridLines: { drawOnChartArea: false } }], yAxes: [{ ticks: { beginAtZero: true, maxTicksLimit: 5, stepSize: Math.ceil(250 / 5), max: 250 } }] }, elements: { point: { radius: 0, hitRadius: 10, hoverRadius: 4, hoverBorderWidth: 3 } } } }) const brandBoxChartLabels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'] const brandBoxChartOptions = { responsive: true, maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ display:false }], yAxes: [{ display:false }] }, elements: { point: { radius: 0, hitRadius: 10, hoverRadius: 4, hoverBorderWidth: 3 } } } // eslint-disable-next-line no-unused-vars const brandBoxChart1 = new Chart($('#social-box-chart-1'), { type: 'line', data: { labels: brandBoxChartLabels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.1)', borderColor: 'rgba(255,255,255,.55)', pointHoverBackgroundColor: '#fff', borderWidth: 2, data: [65, 59, 84, 84, 51, 55, 40] }] }, options: brandBoxChartOptions }) // eslint-disable-next-line no-unused-vars const brandBoxChart2 = new Chart($('#social-box-chart-2'), { type: 'line', data: { labels: brandBoxChartLabels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.1)', borderColor: 'rgba(255,255,255,.55)', pointHoverBackgroundColor: '#fff', borderWidth: 2, data: [1, 13, 9, 17, 34, 41, 38] }] }, options: brandBoxChartOptions }) // eslint-disable-next-line no-unused-vars const brandBoxChart3 = new Chart($('#social-box-chart-3'), { type: 'line', data: { labels: brandBoxChartLabels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.1)', borderColor: 'rgba(255,255,255,.55)', pointHoverBackgroundColor: '#fff', borderWidth: 2, data: [78, 81, 80, 45, 34, 12, 40] }] }, options: brandBoxChartOptions }) // eslint-disable-next-line no-unused-vars const brandBoxChart4 = new Chart($('#social-box-chart-4'), { type: 'line', data: { labels: brandBoxChartLabels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.1)', borderColor: 'rgba(255,255,255,.55)', pointHoverBackgroundColor: '#fff', borderWidth: 2, data: [35, 23, 56, 22, 97, 23, 64] }] }, options: brandBoxChartOptions })
ItsAGeekThing/openCAD-php
oc-content/themes/default/vendors/coreui/src/js/src/main.js
JavaScript
gpl-3.0
8,755
/* * DA9150 GPADC Driver * * Copyright (c) 2014 Dialog Semiconductor * * Author: Adam Thomson <Adam.Thomson.Opensource@diasemi.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/mutex.h> #include <linux/completion.h> #include <linux/iio/iio.h> #include <linux/iio/machine.h> #include <linux/iio/driver.h> #include <linux/mfd/da9150/core.h> #include <linux/mfd/da9150/registers.h> /* Channels */ enum da9150_gpadc_hw_channel { DA9150_GPADC_HW_CHAN_GPIOA_2V = 0, DA9150_GPADC_HW_CHAN_GPIOA_2V_, DA9150_GPADC_HW_CHAN_GPIOB_2V, DA9150_GPADC_HW_CHAN_GPIOB_2V_, DA9150_GPADC_HW_CHAN_GPIOC_2V, DA9150_GPADC_HW_CHAN_GPIOC_2V_, DA9150_GPADC_HW_CHAN_GPIOD_2V, DA9150_GPADC_HW_CHAN_GPIOD_2V_, DA9150_GPADC_HW_CHAN_IBUS_SENSE, DA9150_GPADC_HW_CHAN_IBUS_SENSE_, DA9150_GPADC_HW_CHAN_VBUS_DIV, DA9150_GPADC_HW_CHAN_VBUS_DIV_, DA9150_GPADC_HW_CHAN_ID, DA9150_GPADC_HW_CHAN_ID_, DA9150_GPADC_HW_CHAN_VSYS, DA9150_GPADC_HW_CHAN_VSYS_, DA9150_GPADC_HW_CHAN_GPIOA_6V, DA9150_GPADC_HW_CHAN_GPIOA_6V_, DA9150_GPADC_HW_CHAN_GPIOB_6V, DA9150_GPADC_HW_CHAN_GPIOB_6V_, DA9150_GPADC_HW_CHAN_GPIOC_6V, DA9150_GPADC_HW_CHAN_GPIOC_6V_, DA9150_GPADC_HW_CHAN_GPIOD_6V, DA9150_GPADC_HW_CHAN_GPIOD_6V_, DA9150_GPADC_HW_CHAN_VBAT, DA9150_GPADC_HW_CHAN_VBAT_, DA9150_GPADC_HW_CHAN_TBAT, DA9150_GPADC_HW_CHAN_TBAT_, DA9150_GPADC_HW_CHAN_TJUNC_CORE, DA9150_GPADC_HW_CHAN_TJUNC_CORE_, DA9150_GPADC_HW_CHAN_TJUNC_OVP, DA9150_GPADC_HW_CHAN_TJUNC_OVP_, }; enum da9150_gpadc_channel { DA9150_GPADC_CHAN_GPIOA = 0, DA9150_GPADC_CHAN_GPIOB, DA9150_GPADC_CHAN_GPIOC, DA9150_GPADC_CHAN_GPIOD, DA9150_GPADC_CHAN_IBUS, DA9150_GPADC_CHAN_VBUS, DA9150_GPADC_CHAN_VSYS, DA9150_GPADC_CHAN_VBAT, DA9150_GPADC_CHAN_TBAT, DA9150_GPADC_CHAN_TJUNC_CORE, DA9150_GPADC_CHAN_TJUNC_OVP, }; /* Private data */ struct da9150_gpadc { struct da9150 *da9150; struct device *dev; struct mutex lock; struct completion complete; }; static irqreturn_t da9150_gpadc_irq(int irq, void *data) { struct da9150_gpadc *gpadc = data; complete(&gpadc->complete); return IRQ_HANDLED; } static int da9150_gpadc_read_adc(struct da9150_gpadc *gpadc, int hw_chan) { u8 result_regs[2]; int result; mutex_lock(&gpadc->lock); /* Set channel & enable measurement */ da9150_reg_write(gpadc->da9150, DA9150_GPADC_MAN, (DA9150_GPADC_EN_MASK | hw_chan << DA9150_GPADC_MUX_SHIFT)); /* Consume left-over completion from a previous timeout */ try_wait_for_completion(&gpadc->complete); /* Check for actual completion */ wait_for_completion_timeout(&gpadc->complete, msecs_to_jiffies(5)); /* Read result and status from device */ da9150_bulk_read(gpadc->da9150, DA9150_GPADC_RES_A, 2, result_regs); mutex_unlock(&gpadc->lock); /* Check to make sure device really has completed reading */ if (result_regs[1] & DA9150_GPADC_RUN_MASK) { dev_err(gpadc->dev, "Timeout on channel %d of GPADC\n", hw_chan); return -ETIMEDOUT; } /* LSBs - 2 bits */ result = (result_regs[1] & DA9150_GPADC_RES_L_MASK) >> DA9150_GPADC_RES_L_SHIFT; /* MSBs - 8 bits */ result |= result_regs[0] << DA9150_GPADC_RES_L_BITS; return result; } static inline int da9150_gpadc_gpio_6v_voltage_now(int raw_val) { /* Convert to mV */ return (6 * ((raw_val * 1000) + 500)) / 1024; } static inline int da9150_gpadc_ibus_current_avg(int raw_val) { /* Convert to mA */ return (4 * ((raw_val * 1000) + 500)) / 2048; } static inline int da9150_gpadc_vbus_21v_voltage_now(int raw_val) { /* Convert to mV */ return (21 * ((raw_val * 1000) + 500)) / 1024; } static inline int da9150_gpadc_vsys_6v_voltage_now(int raw_val) { /* Convert to mV */ return (3 * ((raw_val * 1000) + 500)) / 512; } static int da9150_gpadc_read_processed(struct da9150_gpadc *gpadc, int channel, int hw_chan, int *val) { int raw_val; raw_val = da9150_gpadc_read_adc(gpadc, hw_chan); if (raw_val < 0) { return raw_val; } switch (channel) { case DA9150_GPADC_CHAN_GPIOA: case DA9150_GPADC_CHAN_GPIOB: case DA9150_GPADC_CHAN_GPIOC: case DA9150_GPADC_CHAN_GPIOD: *val = da9150_gpadc_gpio_6v_voltage_now(raw_val); break; case DA9150_GPADC_CHAN_IBUS: *val = da9150_gpadc_ibus_current_avg(raw_val); break; case DA9150_GPADC_CHAN_VBUS: *val = da9150_gpadc_vbus_21v_voltage_now(raw_val); break; case DA9150_GPADC_CHAN_VSYS: *val = da9150_gpadc_vsys_6v_voltage_now(raw_val); break; default: /* No processing for other channels so return raw value */ *val = raw_val; break; } return IIO_VAL_INT; } static int da9150_gpadc_read_scale(int channel, int *val, int *val2) { switch (channel) { case DA9150_GPADC_CHAN_VBAT: *val = 2932; *val2 = 1000; return IIO_VAL_FRACTIONAL; case DA9150_GPADC_CHAN_TJUNC_CORE: case DA9150_GPADC_CHAN_TJUNC_OVP: *val = 1000000; *val2 = 4420; return IIO_VAL_FRACTIONAL; default: return -EINVAL; } } static int da9150_gpadc_read_offset(int channel, int *val) { switch (channel) { case DA9150_GPADC_CHAN_VBAT: *val = 1500000 / 2932; return IIO_VAL_INT; case DA9150_GPADC_CHAN_TJUNC_CORE: case DA9150_GPADC_CHAN_TJUNC_OVP: *val = -144; return IIO_VAL_INT; default: return -EINVAL; } } static int da9150_gpadc_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask) { struct da9150_gpadc *gpadc = iio_priv(indio_dev); if ((chan->channel < DA9150_GPADC_CHAN_GPIOA) || (chan->channel > DA9150_GPADC_CHAN_TJUNC_OVP)) { return -EINVAL; } switch (mask) { case IIO_CHAN_INFO_RAW: case IIO_CHAN_INFO_PROCESSED: return da9150_gpadc_read_processed(gpadc, chan->channel, chan->address, val); case IIO_CHAN_INFO_SCALE: return da9150_gpadc_read_scale(chan->channel, val, val2); case IIO_CHAN_INFO_OFFSET: return da9150_gpadc_read_offset(chan->channel, val); default: return -EINVAL; } } static const struct iio_info da9150_gpadc_info = { .read_raw = &da9150_gpadc_read_raw, .driver_module = THIS_MODULE, }; #define DA9150_GPADC_CHANNEL(_id, _hw_id, _type, chan_info, \ _ext_name) { \ .type = _type, \ .indexed = 1, \ .channel = DA9150_GPADC_CHAN_##_id, \ .address = DA9150_GPADC_HW_CHAN_##_hw_id, \ .info_mask_separate = chan_info, \ .extend_name = _ext_name, \ .datasheet_name = #_id, \ } #define DA9150_GPADC_CHANNEL_RAW(_id, _hw_id, _type, _ext_name) \ DA9150_GPADC_CHANNEL(_id, _hw_id, _type, \ BIT(IIO_CHAN_INFO_RAW), _ext_name) #define DA9150_GPADC_CHANNEL_SCALED(_id, _hw_id, _type, _ext_name) \ DA9150_GPADC_CHANNEL(_id, _hw_id, _type, \ BIT(IIO_CHAN_INFO_RAW) | \ BIT(IIO_CHAN_INFO_SCALE) | \ BIT(IIO_CHAN_INFO_OFFSET), \ _ext_name) #define DA9150_GPADC_CHANNEL_PROCESSED(_id, _hw_id, _type, _ext_name) \ DA9150_GPADC_CHANNEL(_id, _hw_id, _type, \ BIT(IIO_CHAN_INFO_PROCESSED), _ext_name) /* Supported channels */ static const struct iio_chan_spec da9150_gpadc_channels[] = { DA9150_GPADC_CHANNEL_PROCESSED(GPIOA, GPIOA_6V, IIO_VOLTAGE, NULL), DA9150_GPADC_CHANNEL_PROCESSED(GPIOB, GPIOB_6V, IIO_VOLTAGE, NULL), DA9150_GPADC_CHANNEL_PROCESSED(GPIOC, GPIOC_6V, IIO_VOLTAGE, NULL), DA9150_GPADC_CHANNEL_PROCESSED(GPIOD, GPIOD_6V, IIO_VOLTAGE, NULL), DA9150_GPADC_CHANNEL_PROCESSED(IBUS, IBUS_SENSE, IIO_CURRENT, "ibus"), DA9150_GPADC_CHANNEL_PROCESSED(VBUS, VBUS_DIV_, IIO_VOLTAGE, "vbus"), DA9150_GPADC_CHANNEL_PROCESSED(VSYS, VSYS, IIO_VOLTAGE, "vsys"), DA9150_GPADC_CHANNEL_SCALED(VBAT, VBAT, IIO_VOLTAGE, "vbat"), DA9150_GPADC_CHANNEL_RAW(TBAT, TBAT, IIO_VOLTAGE, "tbat"), DA9150_GPADC_CHANNEL_SCALED(TJUNC_CORE, TJUNC_CORE, IIO_TEMP, "tjunc_core"), DA9150_GPADC_CHANNEL_SCALED(TJUNC_OVP, TJUNC_OVP, IIO_TEMP, "tjunc_ovp"), }; /* Default maps used by da9150-charger */ static struct iio_map da9150_gpadc_default_maps[] = { { .consumer_dev_name = "da9150-charger", .consumer_channel = "CHAN_IBUS", .adc_channel_label = "IBUS", }, { .consumer_dev_name = "da9150-charger", .consumer_channel = "CHAN_VBUS", .adc_channel_label = "VBUS", }, { .consumer_dev_name = "da9150-charger", .consumer_channel = "CHAN_TJUNC", .adc_channel_label = "TJUNC_CORE", }, { .consumer_dev_name = "da9150-charger", .consumer_channel = "CHAN_VBAT", .adc_channel_label = "VBAT", }, {}, }; static int da9150_gpadc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct da9150 *da9150 = dev_get_drvdata(dev->parent); struct da9150_gpadc *gpadc; struct iio_dev *indio_dev; int irq, ret; indio_dev = devm_iio_device_alloc(dev, sizeof(*gpadc)); if (!indio_dev) { dev_err(&pdev->dev, "Failed to allocate IIO device\n"); return -ENOMEM; } gpadc = iio_priv(indio_dev); platform_set_drvdata(pdev, indio_dev); gpadc->da9150 = da9150; gpadc->dev = dev; mutex_init(&gpadc->lock); init_completion(&gpadc->complete); irq = platform_get_irq_byname(pdev, "GPADC"); if (irq < 0) { dev_err(dev, "Failed to get IRQ: %d\n", irq); return irq; } ret = devm_request_threaded_irq(dev, irq, NULL, da9150_gpadc_irq, IRQF_ONESHOT, "GPADC", gpadc); if (ret) { dev_err(dev, "Failed to request IRQ %d: %d\n", irq, ret); return ret; } ret = iio_map_array_register(indio_dev, da9150_gpadc_default_maps); if (ret) { dev_err(dev, "Failed to register IIO maps: %d\n", ret); return ret; } indio_dev->name = dev_name(dev); indio_dev->dev.parent = dev; indio_dev->dev.of_node = pdev->dev.of_node; indio_dev->info = &da9150_gpadc_info; indio_dev->modes = INDIO_DIRECT_MODE; indio_dev->channels = da9150_gpadc_channels; indio_dev->num_channels = ARRAY_SIZE(da9150_gpadc_channels); ret = iio_device_register(indio_dev); if (ret) { dev_err(dev, "Failed to register IIO device: %d\n", ret); goto iio_map_unreg; } return 0; iio_map_unreg: iio_map_array_unregister(indio_dev); return ret; } static int da9150_gpadc_remove(struct platform_device *pdev) { struct iio_dev *indio_dev = platform_get_drvdata(pdev); iio_device_unregister(indio_dev); iio_map_array_unregister(indio_dev); return 0; } static struct platform_driver da9150_gpadc_driver = { .driver = { .name = "da9150-gpadc", }, .probe = da9150_gpadc_probe, .remove = da9150_gpadc_remove, }; module_platform_driver(da9150_gpadc_driver); MODULE_DESCRIPTION("GPADC Driver for DA9150"); MODULE_AUTHOR("Adam Thomson <Adam.Thomson.Opensource@diasemi.com>"); MODULE_LICENSE("GPL");
williamfdevine/PrettyLinux
drivers/iio/adc/da9150-gpadc.c
C
gpl-3.0
10,909
CREATE TABLE "2012_census_population_by_citizenship_ward_" ( "ward" text, "citizenship" text, "population" real );
talos/docker4data
data/socrata/data.edmonton.ca/2012_census_population_by_citizenship_ward_/schema.sql
SQL
gpl-3.0
118
/* * $FU-Copyright$ */ #include "omnetpp/EARA.h" #include "omnetpp/OMNeTEARAConfiguration.h" #include "omnetpp/EARAPacketFactory.h" #include "omnetpp/OMNeTEARAPacket.h" #include "omnetpp/traffic/TrafficPacket_m.h" #include "omnetpp/EARARoutingTableWatcher.h" OMNETARA_NAMESPACE_BEGIN // Register the class with the OMNeT++ simulation Define_Module(EARA); simsignal_t EARA::LOOP_DETECTION_SIGNAL = SIMSIGNAL_NULL; simsignal_t EARA::DROP_PACKET_WITH_ZERO_TTL = SIMSIGNAL_NULL; simsignal_t EARA::ROUTE_FAILURE_NO_HOP = SIMSIGNAL_NULL; simsignal_t EARA::NEW_ROUTE_DISCOVERY = SIMSIGNAL_NULL; simsignal_t EARA::ROUTE_FAILURE_NEXT_HOP_IS_SENDER = SIMSIGNAL_NULL; EARA::~EARA() { /* We set the policies to nullptr in order to prevent the AbstractARAClient from deleting those. * This is necessary because the surround omnetpp simulation will attempt to delete those modules * because they are SimpleModules which are owned by other compound modules*/ AbstractARAClient::forwardingPolicy = nullptr; forwardingPolicy = nullptr; evaporationPolicy = nullptr; pathReinforcementPolicy = nullptr; } int EARA::numInitStages() const { return 5; } void EARA::initialize(int stage) { AbstractOMNeTARAClient::initialize(stage); if(stage == 4) { OMNeTEARAConfiguration config = OMNeTEARAConfiguration(this); setLogger(config.getLogger()); AbstractEARAClient::initializeEARA(config); initializeNetworkInterfacesOf(this, config); notificationBoard->subscribe(this, NF_BATTERY_CHANGED); WATCH(nrOfDetectedLoops); WATCH(maximumBatteryCapacityInNetwork); LOOP_DETECTION_SIGNAL = registerSignal("routingLoopDetected"); DROP_PACKET_WITH_ZERO_TTL = registerSignal("dropZeroTTLPacket"); ROUTE_FAILURE_NO_HOP = registerSignal("routeFailureNoHopAvailable"); NEW_ROUTE_DISCOVERY = registerSignal("newRouteDiscovery"); ROUTE_FAILURE_NEXT_HOP_IS_SENDER = registerSignal("routeFailureNextHopIsSender"); new EARARoutingTableWatcher(routingTable); } } void EARA::receivePacket(Packet* packet, NetworkInterface* interface) { AbstractEARAClient::receivePacket(packet, interface); persistRoutingTableData(); } void EARA::handleDuplicateErrorPacket(Packet* packet, NetworkInterface* interface) { AbstractARAClient::handleDuplicateErrorPacket(packet, interface); nrOfDetectedLoops++; emit(LOOP_DETECTION_SIGNAL, 1); } bool EARA::handleBrokenOMNeTLink(Packet* packet, AddressPtr receiverAddress, NetworkInterface* interface) { return AbstractEARAClient::handleBrokenLink(packet, receiverAddress, interface); } void EARA::handlePacketWithZeroTTL(Packet* packet) { if(packet->isDataPacket()) { emit(DROP_PACKET_WITH_ZERO_TTL, 1); } AbstractEARAClient::handlePacketWithZeroTTL(packet); } void EARA::handleNonSourceRouteDiscovery(Packet* packet) { if(routingTable->isDeliverable(packet->getDestination())) { // can not be sent because the only known next hop is the sender of this packet emit(ROUTE_FAILURE_NEXT_HOP_IS_SENDER, 1); } else { // can not be sent because there really is no known next hop emit(ROUTE_FAILURE_NO_HOP, 1); } AbstractEARAClient::handleNonSourceRouteDiscovery(packet); } void EARA::startNewRouteDiscovery(Packet* packet) { emit(NEW_ROUTE_DISCOVERY, 1); AbstractEARAClient::startNewRouteDiscovery(packet); } unsigned int EARA::getCurrentEnergyLevel() { return currentEnergyLevel; } OMNETARA_NAMESPACE_END
des-testbed/libara
omnetpp/EARA.cpp
C++
gpl-3.0
3,561
package visGrid.diagram.part; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.emf.common.util.URI; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.dialogs.WizardNewFileCreationPage; /** * @generated */ public class VisGridCreationWizardPage extends WizardNewFileCreationPage { /** * @generated */ private final String fileExtension; /** * @generated */ public VisGridCreationWizardPage(String pageName, IStructuredSelection selection, String fileExtension) { super(pageName, selection); this.fileExtension = fileExtension; } /** * Override to create files with this extension. * * @generated */ protected String getExtension() { return fileExtension; } /** * @generated */ public URI getURI() { return URI.createPlatformResourceURI(getFilePath().toString(), false); } /** * @generated */ protected IPath getFilePath() { IPath path = getContainerFullPath(); if (path == null) { path = new Path(""); //$NON-NLS-1$ } String fileName = getFileName(); if (fileName != null) { path = path.append(fileName); } return path; } /** * @generated */ public void createControl(Composite parent) { super.createControl(parent); setFileName(visGrid.diagram.part.VisGridDiagramEditorUtil .getUniqueFileName(getContainerFullPath(), getFileName(), getExtension())); setPageComplete(validatePage()); } /** * @generated */ protected boolean validatePage() { if (!super.validatePage()) { return false; } String extension = getExtension(); if (extension != null && !getFilePath().toString().endsWith("." + extension)) { setErrorMessage(NLS .bind(visGrid.diagram.part.Messages.VisGridCreationWizardPageExtensionError, extension)); return false; } return true; } }
mikesligo/visGrid
ie.tcd.gmf.visGrid.diagram/src/visGrid/diagram/part/VisGridCreationWizardPage.java
Java
gpl-3.0
1,941
<?php $cuenta_actual = addslashes($_SESSION['usuario']); /* $suma_factura = "SELECT sum(vlr_total_venta) as vlr_total_venta, sum(vlr_total_compra) as vlr_total_compra, sum(descuento) as descuento, sum(precio_compra_con_descuento) as precio_compra_con_descuento, sum(valor_iva) as valor_iva FROM exportacion_temporal WHERE vendedor = '$cuenta_actual'"; $consulta_suma = mysql_query($suma_factura, $conectar) or die(mysql_error()); $suma = mysql_fetch_assoc($consulta_suma); */ $sql_cod_factura_exportacion = "SELECT MAX(cod_factura) AS cod_factura FROM exportacion"; $consulta_cod_factura = mysql_query($sql_cod_factura_exportacion, $conectar) or die(mysql_error()); $cod_factura_exportacion = mysql_fetch_assoc($consulta_cod_factura); $cod_factura = $cod_factura_exportacion['cod_factura'] + 1; ?> <center> <table id="table" width="100%"> <form method="post" name="formulario" action="../admin/guardar_exportacion_temporal_exportacion_vendedor.php"> <td><strong>FECHA: </strong><input type="text" style="font-size:15px" name="fecha" value="<?php echo date("d/m/Y")?>" size="10" required autofocus> <td><strong>FACTURA: <?php echo $cod_factura ?></strong></td> <input type="hidden" style="font-size:15px" name="cod_factura" value="<?php echo $cod_factura ?>" size="7" required autofocus> <input type="hidden" style="font-size:15px" name="iva" value="0" size="1" required autofocus> <!--</td>--> <input type="hidden" name="verificacion" value="verificacion" size="1"> <!-- <td><label><input type="radio" name="tipo_pago" value="contado" checked> <strong>CONTADO</strong></label> <br> <label><input type="radio" name="tipo_pago" value="credito"> <strong>CREDITO</strong></label></td> <td><div align="right"><strong>V.BRUTO(SN.IVA):</strong><input type="text" style="font-size:15px" name="valor_bruto" value="<?php echo $suma['vlr_total_compra'];?>" size="6" required autofocus></div></td> <td><div align="right"><strong>DESCUENTO:</strong><input type="text" style="font-size:15px" name="descuento_factura" value="<?php echo $suma['descuento'];?>" size="6" required autofocus></div></td> <td><div align="right"><strong>V.NETO:</strong><input type="text" style="font-size:15px" name="valor_neto" value="<?php echo $suma['vlr_total_compra'];?>" size="6" required autofocus></div></td> <td><div align="right"><strong>V.IVA:</strong><input type="text" style="font-size:15px" name="valor_iva" value="<?php echo $suma['valor_iva'];?>" size="6" required autofocus></div></td> <td><div align="right"><strong>TOTAL:</strong><input type="text" style="font-size:15px" name="total" value="<?php echo $suma['precio_compra_con_descuento'];?>" size="6" required autofocus></div></td> --> <td><div align="right"><input type="image" src="../imagenes/guardar.png" name="vender" value="Guardar" /></td> </table> </form>
dataxe/proyectos
ciclofenix/admin/informacion_exportacion_temporal_vendedor.php
PHP
gpl-3.0
2,802
/* Copyright (C) 2015 Adam Yarris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rubbaboy.Listeners; import com.rubbaboy.log.Logger; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryCloseEvent; public class PlayerInvClose implements Listener { @EventHandler public void onInvClose(InventoryCloseEvent event) throws Exception { Location loc = event.getPlayer().getLocation(); Player player = (Player) event.getPlayer(); Logger logger = new Logger(); logger.Log(5, "Closed inventory with player coordinates at X:" + loc.getBlockX() + " Y:" + loc.getBlockY() + " Z:" + loc.getBlockZ() + " inventory name being " + event.getInventory().getName() + " players gamemode was " + event.getPlayer().getGameMode().toString() + " player flying is " + player.isFlying(), player); } }
RubbaBoy/InfinityLogger
src/com/rubbaboy/Listeners/PlayerInvClose.java
Java
gpl-3.0
1,528
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* * ThreadCommunicator.cpp * * Created on: 13.08.2013 * Author: chris */ #ifdef BOOST_THREAD #include "threadCommunicator.h" namespace threading { ThreadCommunicator::ThreadCommunicator() : mReadyRemoteTasks( 0 ), mNeedFinish( false ), mThreadCount( boost::thread::hardware_concurrency() - 1 ) { } ThreadCommunicator::ThreadCommunicator(size_t threadCount) : mReadyRemoteTasks( 0 ), mNeedFinish( false ), mThreadCount( threadCount ) { } ThreadCommunicator::~ThreadCommunicator() { } size_t ThreadCommunicator::GetSystemThreadCount() const { return mThreadCount; } void ThreadCommunicator::RegisterWorker(size_t numberOfWorkers, RemoteTaskExecutionHandler handler) { for(size_t workerID = 0; workerID < numberOfWorkers; ++workerID) mRemoteHandlerVec.push_back(handler); } void ThreadCommunicator::RunThreads() { typedef std::vector<boost::shared_ptr<boost::thread> >::iterator handlerIt_t; size_t totalRemoteThreadCount = mRemoteHandlerVec.size(); mSendBarrier.reset( new boost::barrier( totalRemoteThreadCount + 1 ) ); mRecvBarrier.reset( new boost::barrier( totalRemoteThreadCount + 1 ) ); for(size_t i = 0; i < mRemoteHandlerVec.size(); ++i) { mThreadVec.push_back( boost::shared_ptr<boost::thread>( new boost::thread( mRemoteHandlerVec.at(i), i ) ) ); } } void ThreadCommunicator::SyncBeforeThreadWork() { mRecvBarrier->wait(); } void ThreadCommunicator::SyncAfterThreadWork() { mSendBarrier->wait(); mNeedFinish = false; mReadyRemoteTasks = 0; } void ThreadCommunicator::SetReady() { ++mReadyRemoteTasks; } bool ThreadCommunicator::IsReady() const { return mReadyRemoteTasks == mRemoteHandlerVec.size(); } void ThreadCommunicator::FinishThisCycle() { mNeedFinish = true; } bool ThreadCommunicator::IsCycleFinished() const { return mNeedFinish && IsReady(); } void ThreadCommunicator::StopAllProcesses() { mNeedStop = true; mRecvBarrier->wait(); typedef std::vector<boost::shared_ptr<boost::thread> >::iterator threadit_t; for( threadit_t it = mThreadVec.begin(); it != mThreadVec.end(); ++it) { it->get()->join(); } } bool ThreadCommunicator::IsStop() const { return mNeedStop; } size_t ThreadCommunicator::GetThreadID() const { //Boost does not provide a number as an id. This is not an issue right now, but is not soved yet. // return boost::this_thread::get_id(); return 0; } } /* namespace threading */ #endif /* BOOST_THREAD */
FHust/ISEAFramework
src/threading/communicators/threadCommunicator.cpp
C++
gpl-3.0
3,516
<?php session_start(); if ( ($_SESSION['payment_username']) == ($_POST['txtUsername']) ) { echo "<b><p>Unathorized. Please log-in.</b></p>"; } else { ?> <?php $top = <<< TOP <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Intergrated Information System</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body background="../background.gif" link="#0000CC" vlink="#0000CC" alink="#0000CC"> <table width="95%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td bgcolor="#99CCFF"><div align="center"><img src="../header2.jpg" width="960" height="154"></div></td> </tr> <tr> <td height="251" bgcolor="#DDE6EE"><table width="100%" border="0" cellspacing="2" cellpadding="2"> <tr> <td width="77%" height="354" valign="top" bgcolor="#FFFFFF"><table width="100%" border="0" cellspacing="2" cellpadding="2"> <tr> <td bgcolor="#EEEEDD"><strong>Edit Payment</strong></td> </tr> </table> <p> TOP; $bottom = <<< BOTTOM </p> </td></tr> </table></td> </tr> </table> </body> </html> BOTTOM; $sqlConnect = mysql_connect('localhost', 'root') or die("Can't connect to database"); $sqlDb = mysql_select_db('ssmd') or die("Can't select database"); $sqlQuery = "SELECT * FROM `order`"; $sqlResult = mysql_query($sqlQuery) or die("Can't Make query"); $columnCount = mysql_num_fields($sqlResult); echo $top; echo "<table border = 1 cellspacing = 1 cellpadding = 5>"; echo "<br>"; echo "<tr>"; echo "<td>Id</td>"; echo "<td>Ordered By</td>"; echo "<td>Product/Service</td>"; echo "<td>Quantity</td>"; echo "<td>Description</td>"; echo "<td>Supplier</td>"; echo "<td>Price (RM)</td>"; echo "<td>Paid (RM)</td>"; echo "<td>Action</td>"; echo "</tr>"; while($sqlValues = mysql_fetch_array($sqlResult)) { echo "<tr>"; for($column = 7; $column < $columnCount; $column++) { echo "<td>$sqlValues[0]</td>\n"; echo "<td>$sqlValues[1]</td>\n"; echo "<td>$sqlValues[2]</td>\n"; echo "<td>$sqlValues[3]</td>\n"; echo "<td>$sqlValues[4]</td>\n"; echo "<td>$sqlValues[5]</td>\n"; echo "<td>$sqlValues[6]</td>\n"; echo "<td>$sqlValues[7]</td>\n"; echo "<td> <a href=\"edit_form.php?payid="; echo "$sqlValues[0]\" "; echo ">Edit</a>"; } echo "</tr>"; } echo "</table>"; echo "<p>Go back to <a href=\"main.php\">main menu</a></p>"; echo $bottom; ?> <?php } ?>
azri-azhar/college
php/ssmd/payment/edit_payment.php
PHP
gpl-3.0
2,772
Imports si0n.cSDK Imports si0n.Offsets Imports si0n.cUsefulFuncs Imports si0n.ENUMS Public Class cKnifeChanger ''Credits for this go to Klorik on UC Private Structure tSkinModel Public off1 As Integer Public off2 As Integer End Structure Private SkinModel As New tSkinModel Private NeedIndexes As Boolean = True Private StartPoint As Integer Private KnifeID As Integer Public Sub KnifeChanger(KnifeModel As Integer) Dim WeaponBase As Integer = pLocalPlayer.ActiveWeapon.ptr Dim WeaponDefID As Integer = pLocalPlayer.ActiveWeapon.ID If NeedIndexes Then Dim hWeapon As Integer = mem.rdInt(pLocalPlayer.ptr + m_hViewModel) Dim KnifeBase As Integer = mem.rdInt(mem.ClientDLL + dwEntityList + ((hWeapon And &HFFF) - 1) * &H10) Select Case WeaponDefID Case ItemDefinitionIndex.USP StartPoint = mem.rdInt(KnifeBase + m_nModelIndex) KnifeID = StartPoint + 28 + (3 * KnifeModel - 3) NeedIndexes = False Case ItemDefinitionIndex.GLOCK StartPoint = mem.rdInt(KnifeBase + m_nModelIndex) KnifeID = StartPoint + 273 + (3 * KnifeModel - 3) NeedIndexes = False Case ItemDefinitionIndex.P2000 StartPoint = mem.rdInt(KnifeBase + m_nModelIndex) KnifeID = StartPoint + 128 + (3 * KnifeModel - 3) NeedIndexes = False Case ItemDefinitionIndex.DEAGLE StartPoint = mem.rdInt(KnifeBase + m_nModelIndex) KnifeID = StartPoint + 300 + (3 * KnifeModel - 3) NeedIndexes = False End Select 'Console.WriteLine(KnifeID) ElseIf pLocalPlayer.ActiveWeapon.Clip = -1 And pLocalPlayer.ActiveWeapon.Type = WeaponType.Knife And Not NeedIndexes And WeaponBase >= 1000 Then Dim hWeapon As Integer = mem.rdInt(pLocalPlayer.ptr + m_hViewModel) Dim KnifeBase As Integer = mem.rdInt(mem.ClientDLL + dwEntityList + ((hWeapon And &HFFF) - 1) * &H10) If KnifeBase >= 1000 Then setKnifeData(KnifeID) If pLocalPlayer.ActiveWeapon.Clip = -1 And pLocalPlayer.ActiveWeapon.Type = WeaponType.Knife And mem.rdInt(KnifeBase + m_nModelIndex) <> KnifeID Then mem.WrtInt(KnifeBase + m_nModelIndex, KnifeID) End If Dim tmpSkinModel As tSkinModel = mem.ReadMemory(Of tSkinModel)(WeaponBase + m_iWorldModelIndex) If pLocalPlayer.ActiveWeapon.Clip = -1 And pLocalPlayer.ActiveWeapon.Type = WeaponType.Knife And tmpSkinModel.off1 <> KnifeID + 1 Or tmpSkinModel.off2 <> KnifeID Then mem.WrtInt(WeaponBase + m_nModelIndex, SkinModel.off1) mem.WrtInt(WeaponBase + m_iWorldModelIndex, SkinModel.off1) mem.WrtInt(WeaponBase + m_iWorldModelIndex + &H4, SkinModel.off2) 'mem.WriteStruct(Of tSkinModel)(WeaponBase + m_iWorldModelIndex, tmpSkinModel) End If If pLocalPlayer.ActiveWeapon.Clip = -1 And pLocalPlayer.ActiveWeapon.Type = WeaponType.Knife And mem.rdShort(WeaponBase + m_iItemDefinitionIndex) <> GetKnifeID(KnifeModel) Then mem.WrtShort(WeaponBase + m_iItemDefinitionIndex, GetKnifeID(KnifeModel)) End If End If End If End Sub Public Sub Reset() NeedIndexes = True End Sub Private Sub setKnifeData(knifeID As Integer) SkinModel.off1 = knifeID + 1 SkinModel.off2 = knifeID End Sub Private Function GetKnifeID(ID As Integer) As Integer Select Case ID Case 1 Return 500 Case 2 Return 505 Case 3 Return 506 Case 4 Return 507 Case 5 Return 508 Case 6 Return 509 Case 7 Return 512 Case 8 Return 514 Case 9 Return 515 Case 10 Return 516 Case Else Return 42 End Select '(m_iViewModelIndex, m_iWorldModelIndex, m_iItemDefinitionIndex) '(379, 380, 500), // KNIFE_BAYONET '(382, 383, 505), // KNIFE_FLIP '(385, 386, 506), // KNIFE_GUT '(388, 389, 507), // KNIFE_KARAMBIT '(391, 392, 508), // KNIFE_M9BAYONET '(394, 395, 509), // KNIFE_TACTICAL '(397, 398, 510), // KNIFE_FALCHION '(400, 401, 511), // KNIFE_BOWIE '(403, 404, 515), // KNIFE_BUTTERFLY '(406, 407, 516), // KNIFE_SHADOWDAGGERS End Function End Class
iisp33dii/si0n-Source
si0n Recode/si0n Recode/Features/KnifeChanger.vb
Visual Basic
gpl-3.0
5,003
/* ******************************************************************************* \file belt_lcl.c \brief STB 34.101.31 (belt): local functions \project bee2 [cryptographic library] \author (C) Sergey Agievich [agievich@{bsu.by|gmail.com}] \created 2012.12.18 \version 2020.03.20 \license This program is released under the GNU General Public License version 3. See Copyright Notices in bee2/info.h. ******************************************************************************* */ #include "bee2/core/mem.h" #include "bee2/core/u32.h" #include "bee2/core/util.h" #include "bee2/crypto/belt.h" #include "bee2/math/pp.h" #include "bee2/math/ww.h" #include "belt_lcl.h" /* ******************************************************************************* Арифметика чисел ******************************************************************************* */ void beltBlockAddBitSizeU32(u32 block[4], size_t count) { // block <- block + 8 * count register u32 carry = (u32)count << 3; #if (B_PER_S < 32) carry = (block[0] += carry) < carry; carry = (block[1] += carry) < carry; carry = (block[2] += carry) < carry; block[3] += carry; #else register size_t t = count >> 29; carry = (block[0] += carry) < carry; if ((block[1] += carry) < carry) block[1] = (u32)t; else carry = (block[1] += (u32)t) < (u32)t; t >>= 16, t >>= 16; if ((block[2] += carry) < carry) block[2] = (u32)t; else carry = (block[2] += (u32)t) < (u32)t; t >>= 16, t >>= 16; block[3] += carry; block[3] += (u32)t; t = 0; #endif carry = 0; } void beltHalfBlockAddBitSizeW(word block[W_OF_B(64)], size_t count) { // block <- block + 8 * count register word carry = (word)count << 3; #if (B_PER_W == 16) register size_t t = count >> 13; carry = (block[0] += carry) < carry; if ((block[1] += carry) < carry) block[1] = (word)t; else carry = (block[1] += (word)t) < (word)t; t >>= 8, t >>= 8; if ((block[2] += carry) < carry) block[2] = (word)t; else carry = (block[2] += (word)t) < (word)t; t >>= 8, t >>= 8; block[3] += carry; block[3] += (word)t; #elif (B_PER_W == 32) register size_t t = count; carry = (block[0] += carry) < carry; t >>= 15, t >>= 14; block[1] += carry; block[1] += (u32)t; t = 0; #elif (B_PER_W == 64) block[0] += carry; #else #error "Unsupported word size" #endif // B_PER_W carry = 0; } /* ******************************************************************************* Арифметика многочленов ******************************************************************************* */ void beltPolyMul(word c[], const word a[], const word b[], void* stack) { const size_t n = W_OF_B(128); word* prod = (word*)stack; stack = prod + 2 * n; // умножить ppMul(prod, a, n, b, n, stack); // привести по модулю ppRedBelt(prod); wwCopy(c, prod, n); } size_t beltPolyMul_deep() { const size_t n = W_OF_B(128); return O_OF_W(2 * n) + ppMul_deep(n, n); } /* ******************************************************************************* Умножение на многочлен C(x) = x mod (x^128 + x^7 + x^2 + x + 1) \remark t = (старший бит block ненулевой) ? x^7 + x^2 + x + 1 : 0 [регулярно]. ******************************************************************************* */ void beltBlockMulC(u32 block[4]) { register u32 t = ~((block[3] >> 31) - U32_1) & 0x00000087; block[3] = (block[3] << 1) ^ (block[2] >> 31); block[2] = (block[2] << 1) ^ (block[1] >> 31); block[1] = (block[1] << 1) ^ (block[0] >> 31); block[0] = (block[0] << 1) ^ t; t = 0; }
agievich/bee2
src/crypto/belt/belt_lcl.c
C
gpl-3.0
3,590
#pragma once #include <opencv2/opencv.hpp> #include <QtCore/qmutex.h> #include <libfreenect/libfreenect.hpp> namespace iez_private { class ImageSourceFreenectDevice_private:public Freenect::FreenectDevice { public: ImageSourceFreenectDevice_private(freenect_context *_ctx, int _index); ~ImageSourceFreenectDevice_private(void); // int init(void); bool isInitialized(); cv::Mat getDepthMat() const; cv::Mat getColorMat() const; int getSequence() { return m_sequence; } int streamInit(freenect_resolution resolution); protected: int deviceInit(void); // Do not call directly even in child void VideoCallback(void *video, uint32_t timestamp) { QMutexLocker lock(&color_mutex); m_sequence++; memcpy(m_colorMat.data, video, m_height*m_width*3); } // Do not call directly even in child void DepthCallback(void *depth, uint32_t timestamp) { QMutexLocker lock(&depth_mutex); memcpy(m_depthMat.data, depth, m_width*m_height*2); } cv::Mat m_depthMat; cv::Mat m_colorMat; mutable QMutex depth_mutex; mutable QMutex color_mutex; const int m_fps; int m_sequence; int m_width, m_height; bool m_initialized; // uint16_t m_t_gamma[2048]; }; }
amirhammad/ht-illez
src/ImageSourceFreenect_private.h
C
gpl-3.0
1,276
/* BOMC - Monte Carlo based generator of defect-free amorphous samples of Si and SiO2 If you publish research done using Bomc then you are kindly asked to cite: S. von Alfthan, A. Kuronen, and K. Kaski, Phys. Rev. B 68, 073203 (2003). Copyright Sebastian von Alfthan (galfthan at iki dot fi) 2002, 2003, 2014. This file is part of Bomc. Bomc is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bomc 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 Bomc. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SHARED #define SHARED /*==== MACROS ====*/ /*the PERIODIC macros assume we have par-> */ /*#define MAKEPERIODIC(r,hlength,length) MAKEPERIODIC_DEF_DIM(r,-hlength,hlength,length);*/ /*#define MAKEPERIODIC(r,hlength,length) ( -rint(r/length)*length)*/ /*#define PERIODICXYZ(r,num) if(par->periodic[num]) MAKEPERIODIC(r,par->hBox[num],par->box[num]);*/ #define MAKEPERIODIC_DEF_DIM(r,left,right,delta) (r>right)?r-=delta:( (r<left)?r+=delta:0.0 ); #define MAKEPERIODIC(r,length) (r-=rint(r/length)*length) //#define SYSTEMISPERIODIC //#define PERIODICXYZ(r,num) if(par->periodic[num]) { (r+par->hBox[num])/ } #define PERIODICXYZ(r,num) if(par->periodic[num]) MAKEPERIODIC_DEF_DIM(r,-par->hBox[num],par->hBox[num],par->box[num]); /*#define PERIODICXYZ(r,num) if(par->periodic[num]) MAKEPERIODIC(r,par->box[num]);*/ #define PERIODIC(rx,ry,rz) PERIODICXYZ(rx,0); PERIODICXYZ(ry,1); PERIODICXYZ(rz,2); //#define PERIODIC(rx,ry,rz) PERIODICXYZ(rx,0); PERIODICXYZ(ry,1); PERIODICXYZ(rz,2); #define POW2(x) ((x) * (x)) #define POW3(x) (POW2(x)*(x)) #define POW4(x) (POW2(x)*POW2(x)) #define POW5(x) (POW3(x)*POW2(x)) #define POW6(x) (POW3(x)*POW3(x)) #define POW7(x) (POW3(x)*POW4(x)) #define POW8(x) (POW4(x)*POW4(x)) #define POW9(x) (POW5(x)*POW4(x)) #define POW10(x) (POW5(x)*POW5(x)) #define MAX(x,y) ((x)<(y)?(y):(x)) #define MAX3(x,y,z) (MAX((x),(y))>(z)?MAX((x),(y)):(z)) #define MIN(x,y) ((x)<(y)?(x):(y)) #define MIN3(x,y,z) (MIN((x),(y))<(z)?MIN((x),(y)):(z)) #define LENGTH2(x,y,z) (POW2(x)+POW2(y)+POW2(z)) #define VOLUME (par->box[0]*par->box[1]*par->box[2]) #define DEBUG 0 //#define FLAG(f,i) (( (f) >> (i))&1) //#define ATOM_IN_SI(f) FLAG(f,0) /*======UNITS========*/ /*=1ps, in seconds */ #define UNITTIME 1.0e-12 /*=1Å in meters */ #define UNITDIST 1.0e-10 /*=1u, in kg*/ #define UNITMASS 1.66053873e-27 //#define UNITCHARGE 4.074972637944948e-17 /*in coulomb, =sqrt(mass*length)*length/time */ /*with this unitcharge the energy in the coulomb interactions will be in the correct units*/ //#define ETOUNITCHARGE 3.93175005663e-3 /*ECHARGE/UNITCHARGE*/ /*=1e, in coulomb*/ #define ECHARGE 1.60217739e-19 #define UNITCHARGE ECHARGE #define ETOUNITCHARGE 1.0 #define TOEV 1.036426266132741e-04 /*= mass*(length/time)^2/echarge */ /*this is the value of the energy in EV when the energy is 1 in the UNITS defined above*/ /*based on the UNITS defined above, make sure it is correct!!!*/ #define EV 9.648539724213475e+03 /*TOEV^-1.0 */ /*this is the value EV in the UNITS defined above, */ /*based on the UNITS defined above, make sure it is correct!!!*/ #define PASCAL 6.022141982800968e-08/*=U_time^2*U_dist/U_mass*/ #define TOPASCAL 16.605387e6 #define JOULETOEV 6.2415097e+18 #define EVTOJOULE ECHARGE #define TOJOULE 1.66053873e-23 #define JOULE 6.022141982800966e+22 #define KCALTOEV 2.6131953e+22 /*========CONSTANTS ========*/ #define EPSILON0_SI 8.8541878e-12 /*Vs/Am*/ #define KB_JOULE 1.3806503e-23 /*joule/k */ #define KBEV 8.617342239757910e-05 /*in ev/K */ #define AVOGADRO 6.022142e23 #define AMORPH_FLAG 0 #define FIXED_FLAG 1 #define CRYST_FLAG 2 #define INTERFACE_FLAG 3 #define SI_ATYPE 1 #define O_ATYPE 0 #define FALSE 0 #define TRUE 1 #define NUMOFATYPES 13 /*num of possible atomic types, increase if neccessary*/ /*======= STRUCTS =======*/ struct systemPos { int nAtoms; /*number of atoms in system*/ double *x,*y,*z; /*position of atoms*/ double *prevx,*prevy,*prevz; /*the positions of the atoms after the last accepted step*/ double *xa,*ya,*za; /*force on each atom*/ int *aType; /*number which tells of which material the atom is atypes are: 0 1 O Si */ double *enPot; /*potential energy of each atom*/ double *prevEnPot; /*contains the potentialEnergy of the system after the last accepted step (corresponding to prevxyz*/ long *aFlag; /*addtitional information about each atom, see FLAG macro*/ }; typedef struct partStruct{ int n; int *list; int *table; } sysPart; struct parameters{ int periodic[3]; /*tells if the system is periodic in x,y,z direction */ int varVol[3]; double box[3],hBox[3],minhBox2; /*the size and half the size of the system in A and the min of the hBoxes squared*/ double volume; double skin; /*skin (used by potentials) in A*/ char aName[NUMOFATYPES][4]; /*tells the name of a certain atype*/ double aMass[NUMOFATYPES]; /*tells the mass of a certain atype (in internal units)*/ double kTrand; double kT; double pressure; long *seed; /*seed number for random number generator*/ int interfaceSys; /* tells if we have a system with a interface between si/siO2 . if 1 then bond switches are not performed in Si area and simAnneal is biased towards siO2 */ }; #endif
galfthan/bomc
src/shared.h
C
gpl-3.0
5,892
/* * Copyright (c) 2004-2010, 2013, 2014, 2016, 2017 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Modification History * * August 5, 2004 Allan Nathanson <ajn@apple.com> * - initial revision */ #include "scutil.h" #include "net.h" #include "net_service.h" #include "net_interface.h" #include "net_protocol.h" #include "prefs.h" /* -------------------- */ static SCNetworkServiceRef _find_service(char *match) { Boolean allowIndex = TRUE; CFIndex i; CFIndex n; CFStringRef select_name = NULL; SCNetworkServiceRef selected = NULL; if (services == NULL) { if (net_set == NULL) { SCPrint(TRUE, stdout, CFSTR("set not selected\n")); return NULL; } services = SCNetworkSetCopyServices(net_set); if (services == NULL) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return NULL; } allowIndex = FALSE; } // try to select the service by its serviceID select_name = CFStringCreateWithCString(NULL, match, kCFStringEncodingUTF8); n = CFArrayGetCount(services); for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceID; service = CFArrayGetValueAtIndex(services, i); serviceID = SCNetworkServiceGetServiceID(service); if (CFEqual(select_name, serviceID)) { selected = service; goto done; } } // try to select the service by its name for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceName; service = CFArrayGetValueAtIndex(services, i); serviceName = SCNetworkServiceGetName(service); if ((serviceName != NULL) && CFEqual(select_name, serviceName)) { if (selected == NULL) { selected = service; } else { // if multiple services match selected = NULL; SCPrint(TRUE, stdout, CFSTR("multiple services match\n")); goto done; } } } if (selected != NULL) { goto done; } // try to select the service by its name (case insensitive) for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceName; service = CFArrayGetValueAtIndex(services, i); serviceName = SCNetworkServiceGetName(service); if ((serviceName != NULL) && CFStringCompare(select_name, serviceName, kCFCompareCaseInsensitive) == kCFCompareEqualTo) { if (selected == NULL) { selected = service; } else { // if multiple services match selected = NULL; SCPrint(TRUE, stdout, CFSTR("multiple services match\n")); goto done; } } } if (selected != NULL) { goto done; } // try to select the service by its [BSD] interface name for (i = 0; i < n; i++) { SCNetworkInterfaceRef interface; CFStringRef interfaceName = NULL; SCNetworkServiceRef service; service = CFArrayGetValueAtIndex(services, i); interface = SCNetworkServiceGetInterface(service); while ((interface != NULL) && (interfaceName == NULL)) { interfaceName = SCNetworkInterfaceGetBSDName(interface); if (interfaceName == NULL) { interface = SCNetworkInterfaceGetInterface(interface); } } if (interfaceName == NULL) { continue; } if (CFStringCompare(select_name, interfaceName, kCFCompareCaseInsensitive) == kCFCompareEqualTo) { if (selected == NULL) { selected = service; } else { // if multiple services match selected = NULL; SCPrint(TRUE, stdout, CFSTR("multiple services match\n")); goto done; } } } if (selected != NULL) { goto done; } // try to select the service by its index if (allowIndex) { char *end; char *str = match; long val; errno = 0; val = strtol(str, &end, 10); if ((*str != '\0') && (*end == '\0') && (errno == 0)) { if ((val > 0) && (val <= n)) { selected = CFArrayGetValueAtIndex(services, val - 1); } } } if (selected != NULL) { goto done; } SCPrint(TRUE, stdout, CFSTR("no match, which service?\n")); done : if (select_name != NULL) CFRelease(select_name); return selected; } /* -------------------- */ __private_extern__ void create_service(int argc, char **argv) { SCNetworkInterfaceRef interface; CFStringRef interfaceName; Boolean ok; SCNetworkServiceRef service = NULL; CFStringRef serviceName; CFStringRef setName; CFArrayRef supported; if (prefs == NULL) { SCPrint(TRUE, stdout, CFSTR("network configuration not open\n")); return; } if (net_set == NULL) { SCPrint(TRUE, stdout, CFSTR("set not selected\n")); return; } if (argc < 1) { if (net_interface == NULL) { SCPrint(TRUE, stdout, CFSTR("no network interface selected\n")); return; } interface = net_interface; } else { int nArgs; interface = _find_interface(argc, argv, &nArgs); argv += nArgs; argc -= nArgs; } if (interface == NULL) { return; } supported = SCNetworkInterfaceGetSupportedProtocolTypes(interface); if (supported == NULL) { SCPrint(TRUE, stdout, CFSTR("no network protocols are supported over this interface\n")); return; } service = SCNetworkServiceCreate(prefs, interface); if (service == NULL) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); goto done; } if ((argc > 0) && (strlen(argv[0]) > 0)) { Boolean ok; serviceName = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8); // argv++; // argc--; ok = SCNetworkServiceSetName(service, serviceName); CFRelease(serviceName); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); (void)SCNetworkServiceRemove(service); goto done; } } ok = SCNetworkServiceEstablishDefaultConfiguration(service); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); (void)SCNetworkServiceRemove(service); goto done; } ok = SCNetworkSetAddService(net_set, service); if (!ok) { SCPrint(TRUE, stdout, CFSTR("service not created: %s\n"), SCErrorString(SCError())); (void)SCNetworkServiceRemove(service); goto done; } _prefs_changed = TRUE; if (net_service != NULL) CFRelease(net_service); net_service = CFRetain(service); serviceName = SCNetworkServiceGetName(service); if (serviceName != NULL) { SCPrint(TRUE, stdout, CFSTR("service \"%@\" (%@) created and selected\n"), serviceName, SCNetworkServiceGetServiceID(service)); } else { SCPrint(TRUE, stdout, CFSTR("service ID \"%@\" created and selected\n"), SCNetworkServiceGetServiceID(service)); } setName = SCNetworkSetGetName(net_set); if (setName != NULL) { SCPrint(TRUE, stdout, CFSTR("& added to set \"%@\"\n"), setName); } else { SCPrint(TRUE, stdout, CFSTR("& added to set ID \"%@\"\n"), SCNetworkSetGetSetID(net_set)); } if (net_interface != NULL) CFRelease(net_interface); net_interface = SCNetworkServiceGetInterface(net_service); if (net_interface != NULL) { CFRetain(net_interface); } interfaceName = SCNetworkInterfaceGetLocalizedDisplayName(interface); if (interfaceName == NULL) { interfaceName = SCNetworkInterfaceGetBSDName(interface); } if (interfaceName == NULL) { interfaceName = SCNetworkInterfaceGetInterfaceType(interface); } SCPrint(TRUE, stdout, CFSTR("& interface \"%@\" selected\n"), interfaceName); if (protocols != NULL) { CFRelease(protocols); protocols = NULL; } if (net_protocol != NULL) { CFRelease(net_protocol); net_protocol = NULL; SCPrint(TRUE, stdout, CFSTR("& no protocol selected\n")); } if (services != NULL) { CFRelease(services); services = NULL; } done : if (service != NULL) CFRelease(service); return; } __private_extern__ void disable_service(int argc, char **argv) { SCNetworkServiceRef service; if (argc == 1) { service = _find_service(argv[0]); } else { if (net_service != NULL) { service = net_service; } else { SCPrint(TRUE, stdout, CFSTR("service not selected\n")); return; } } if (service == NULL) { return; } if (!SCNetworkServiceSetEnabled(service, FALSE)) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; return; } __private_extern__ void enable_service(int argc, char **argv) { SCNetworkServiceRef service; if (argc == 1) { service = _find_service(argv[0]); } else { if (net_service != NULL) { service = net_service; } else { SCPrint(TRUE, stdout, CFSTR("service not selected\n")); return; } } if (service == NULL) { return; } if (!SCNetworkServiceSetEnabled(service, TRUE)) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; return; } __private_extern__ void remove_service(int argc, char **argv) { SCNetworkServiceRef service = NULL; CFStringRef serviceName; if (argc == 1) { service = _find_service(argv[0]); } else { if (net_service != NULL) { service = net_service; } } if (service == NULL) { return; } CFRetain(service); if (!SCNetworkServiceRemove(service)) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); goto done; } _prefs_changed = TRUE; serviceName = SCNetworkServiceGetName(service); if (serviceName != NULL) { SCPrint(TRUE, stdout, CFSTR("service \"%@\" removed\n"), serviceName); } else { SCPrint(TRUE, stdout, CFSTR("service ID \"%@\" removed\n"), SCNetworkServiceGetServiceID(service)); } if ((net_service != NULL) && CFEqual(service, net_service)) { CFRelease(net_service); net_service = NULL; SCPrint(TRUE, stdout, CFSTR("& no service selected\n")); if (protocols != NULL) { CFRelease(protocols); protocols = NULL; } if (net_protocol != NULL) { CFRelease(net_protocol); net_protocol = NULL; SCPrint(TRUE, stdout, CFSTR("& no protocol selected\n")); } if (net_interface != NULL) { CFRelease(net_interface); net_interface = NULL; SCPrint(TRUE, stdout, CFSTR("& no interface selected\n")); } } if (services != NULL) { CFRelease(services); services = NULL; } done : CFRelease(service); return; } __private_extern__ void select_service(int argc, char **argv) { #pragma unused(argc) SCNetworkInterfaceRef interface; SCNetworkServiceRef service; CFStringRef serviceName; service = _find_service(argv[0]); if (service == NULL) { return; } if (net_service != NULL) CFRelease(net_service); net_service = CFRetain(service); serviceName = SCNetworkServiceGetName(service); if (serviceName != NULL) { SCPrint(TRUE, stdout, CFSTR("service \"%@\" selected\n"), serviceName); } else { SCPrint(TRUE, stdout, CFSTR("service ID \"%@\" selected\n"), SCNetworkServiceGetServiceID(service)); } interface = SCNetworkServiceGetInterface(service); if (interface != NULL) { CFStringRef interfaceName; if (net_interface != NULL) CFRelease(net_interface); net_interface = CFRetain(interface); interfaceName = SCNetworkInterfaceGetLocalizedDisplayName(interface); if (interfaceName == NULL) { interfaceName = SCNetworkInterfaceGetBSDName(interface); } if (interfaceName == NULL) { interfaceName = SCNetworkInterfaceGetInterfaceType(interface); } SCPrint(TRUE, stdout, CFSTR("& interface \"%@\" selected\n"), interfaceName); } else { if (net_interface != NULL) { CFRelease(net_interface); net_interface = NULL; SCPrint(TRUE, stdout, CFSTR("& no interface selected\n")); } } if (protocols != NULL) { CFRelease(protocols); protocols = NULL; } if (net_protocol != NULL) { CFRelease(net_protocol); net_protocol = NULL; SCPrint(TRUE, stdout, CFSTR("& no protocol selected\n")); } return; } __private_extern__ void set_service(int argc, char **argv) { Boolean ok; if (net_service == NULL) { SCPrint(TRUE, stdout, CFSTR("service not selected\n")); return; } if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("set what?\n")); return; } while (argc > 0) { char *command; command = argv[0]; argv++; argc--; if (strcmp(command, "name") == 0) { CFStringRef serviceName; if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("name not specified\n")); return; } serviceName = (strlen(argv[0]) > 0) ? CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8) : NULL; argv++; argc--; ok = SCNetworkServiceSetName(net_service, serviceName); if (serviceName != NULL) CFRelease(serviceName); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; } else if (strcmp(command, "order") == 0) { char *end; long newIndex; CFIndex nServices; char *str; CFArrayRef services; services = SCNetworkSetCopyServices(net_set); nServices = CFArrayGetCount(services); CFRelease(services); if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("order not specified\n")); return; } if (net_set == NULL) { SCPrint(TRUE, stdout, CFSTR("set not selected\n")); return; } str = argv[0]; argv++; argc--; errno = 0; newIndex = strtol(str, &end, 10); if ((*str != '\0') && (*end == '\0') && (errno == 0)) { if ((newIndex > 0) && (newIndex <= nServices)) { CFIndex curIndex; CFMutableArrayRef newOrder; CFArrayRef order; CFStringRef serviceID = SCNetworkServiceGetServiceID(net_service); order = SCNetworkSetGetServiceOrder(net_set); if (order == NULL) { newOrder = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } else { newOrder = CFArrayCreateMutableCopy(NULL, 0, order); } curIndex = CFArrayGetFirstIndexOfValue(newOrder, CFRangeMake(0, CFArrayGetCount(newOrder)), serviceID); if (curIndex != kCFNotFound) { CFArrayRemoveValueAtIndex(newOrder, curIndex); } if (newIndex <= CFArrayGetCount(newOrder)) { CFArrayInsertValueAtIndex(newOrder, newIndex - 1, serviceID); } else { CFArrayAppendValue(newOrder, serviceID); } ok = SCNetworkSetSetServiceOrder(net_set, newOrder); CFRelease(newOrder); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; } else { SCPrint(TRUE, stdout, CFSTR("set order to what?\n")); return; } } else { SCPrint(TRUE, stdout, CFSTR("set what?\n")); return; } } else if (strcmp(command, "rank") == 0) { SCNetworkServicePrimaryRank rank = kSCNetworkServicePrimaryRankDefault; SCNetworkServiceRef service = (argc < 2) ? net_service : NULL; Boolean useActive = FALSE; if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("rank not specified\n")); return; } if (strlen(argv[0]) > 0) { if (strcasecmp(argv[0], "Never") == 0) { rank = kSCNetworkServicePrimaryRankNever; } else if ((service != net_service) && (strcasecmp(argv[0], "First") == 0)) { rank = kSCNetworkServicePrimaryRankFirst; } else if ((service != net_service) && (strcasecmp(argv[0], "Last") == 0)) { rank = kSCNetworkServicePrimaryRankLast; } else if ((service != net_service) && (strcasecmp(argv[0], "Scoped") == 0)) { rank = kSCNetworkServicePrimaryRankScoped; } else { SCPrint(TRUE, stdout, CFSTR("rank not valid\n")); return; } } argv++; argc--; if (service == NULL) { CFStringRef serviceID; SCDynamicStoreRef store; store = SCDynamicStoreCreate(NULL, CFSTR("scutil (set primary rank)"), NULL, NULL); serviceID = SCNetworkServiceGetServiceID(net_service); service = _SCNetworkServiceCopyActive(store, serviceID); CFRelease(store); useActive = TRUE; argv++; argc--; } ok = SCNetworkServiceSetPrimaryRank(service, rank); if (useActive) { CFRelease(service); } else if (ok) { _prefs_changed = TRUE; } if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } } else if (strcmp(command, "id") == 0) { CFStringRef serviceID; if ((argc < 1) || (strlen(argv[0]) == 0)) { SCPrint(TRUE, stdout, CFSTR("set id not specified\n")); return; } serviceID = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8); argv++; argc--; ok = _SCNetworkServiceSetServiceID(net_service, serviceID); CFRelease(serviceID); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; } else { SCPrint(TRUE, stdout, CFSTR("set what?\n")); } } return; } static void __show_service_interface(SCNetworkServiceRef service, const char *prefix) { CFStringRef description; SCNetworkInterfaceRef interface; interface = SCNetworkServiceGetInterface(service); if (interface == NULL) { return; } description = _interface_description(interface); SCPrint(TRUE, stdout, CFSTR("%s%@\n"), prefix, description); CFRelease(description); return; } static void __show_service_protocols(SCNetworkServiceRef service, const char *prefix, Boolean skipEmpty) { CFIndex i; CFIndex n; CFArrayRef protocols; protocols = SCNetworkServiceCopyProtocols(service); if (protocols == NULL) { return; } n = CFArrayGetCount(protocols); if (n > 1) { CFMutableArrayRef sorted; sorted = CFArrayCreateMutableCopy(NULL, 0, protocols); CFArraySortValues(sorted, CFRangeMake(0, n), _SCNetworkProtocolCompare, NULL); CFRelease(protocols); protocols = sorted; } for (i = 0; i < n; i++) { CFStringRef description; SCNetworkProtocolRef protocol; protocol = CFArrayGetValueAtIndex(protocols, i); description = _protocol_description(protocol, skipEmpty); if (description != NULL) { CFStringRef protocolType; protocolType = SCNetworkProtocolGetProtocolType(protocol); SCPrint(TRUE, stdout, CFSTR("%s%@%*s : %@\n"), prefix, protocolType, (int)(sizeof("Interface") - CFStringGetLength(protocolType) - 1), "", description); CFRelease(description); } } CFRelease(protocols); return; } __private_extern__ void show_service(int argc, char **argv) { SCNetworkInterfaceRef interface; CFArrayRef protocols; SCNetworkServiceRef service; CFStringRef serviceName; SCNetworkServicePrimaryRank serviceRank; if (argc == 1) { service = _find_service(argv[0]); } else { if (net_service != NULL) { service = net_service; } else { SCPrint(TRUE, stdout, CFSTR("service not selected\n")); return; } } if (service == NULL) { return; } SCPrint(TRUE, stdout, CFSTR("service id = %@\n"), SCNetworkServiceGetServiceID(service)); serviceName = SCNetworkServiceGetName(service); SCPrint(TRUE, stdout, CFSTR("name = %@\n"), (serviceName != NULL) ? serviceName : CFSTR("")); serviceRank = SCNetworkServiceGetPrimaryRank(service); switch (serviceRank) { case kSCNetworkServicePrimaryRankDefault : // nothing to report break; case kSCNetworkServicePrimaryRankFirst : SCPrint(TRUE, stdout, CFSTR("primary rank = %@\n"), kSCValNetServicePrimaryRankFirst); break; case kSCNetworkServicePrimaryRankLast : SCPrint(TRUE, stdout, CFSTR("primary rank = %@\n"), kSCValNetServicePrimaryRankLast); break; case kSCNetworkServicePrimaryRankNever : SCPrint(TRUE, stdout, CFSTR("primary rank = %@\n"), kSCValNetServicePrimaryRankNever); break; case kSCNetworkServicePrimaryRankScoped : SCPrint(TRUE, stdout, CFSTR("primary rank = %@\n"), kSCValNetServicePrimaryRankScoped); break; default : SCPrint(TRUE, stdout, CFSTR("primary rank = %d\n"), serviceRank); break; } interface = SCNetworkServiceGetInterface(service); if (interface != NULL) { CFStringRef interfaceName; interfaceName = SCNetworkInterfaceGetLocalizedDisplayName(interface); if (interfaceName != NULL) { CFRetain(interfaceName); } else { interfaceName = _interface_description(interface); } if (interfaceName != NULL) { SCPrint(TRUE, stdout, CFSTR("interface = %@\n"), interfaceName); CFRelease(interfaceName); } } else { SCPrint(TRUE, stdout, CFSTR("\n No interface!\n\n")); } protocols = SCNetworkServiceCopyProtocols(service); if (protocols != NULL) { CFIndex n; n = CFArrayGetCount(protocols); if (n > 1) { CFMutableArrayRef sorted; sorted = CFArrayCreateMutableCopy(NULL, 0, protocols); CFArraySortValues(sorted, CFRangeMake(0, n), _SCNetworkProtocolCompare, NULL); CFRelease(protocols); protocols = sorted; } if (n > 0) { CFIndex i; SCPrint(TRUE, stdout, CFSTR("configured protocols = ")); for (i = 0; i < n; i++) { SCNetworkProtocolRef protocol; protocol = CFArrayGetValueAtIndex(protocols, i); SCPrint(TRUE, stdout, CFSTR("%s%@"), (i == 0) ? "" : ", ", SCNetworkProtocolGetProtocolType(protocol)); } SCPrint(TRUE, stdout, CFSTR("\n")); __show_service_protocols(service, " ", FALSE); } else { SCPrint(TRUE, stdout, CFSTR("no configured protocols\n")); } CFRelease(protocols); } if (_sc_debug) { SCPrint(TRUE, stdout, CFSTR("\n%@\n"), service); } return; } __private_extern__ void show_services(int argc, char **argv) { #pragma unused(argv) CFIndex i; CFIndex n; if (prefs == NULL) { SCPrint(TRUE, stdout, CFSTR("network configuration not open\n")); return; } if (argc == 1) { if (services != NULL) CFRelease(services); services = SCNetworkServiceCopyAll(prefs); } else { if (net_set == NULL) { SCPrint(TRUE, stdout, CFSTR("set not selected\n")); return; } if (services != NULL) CFRelease(services); services = SCNetworkSetCopyServices(net_set); n = (services != NULL) ? CFArrayGetCount(services) : 0; if (n > 1) { CFArrayRef order; CFMutableArrayRef sorted; order = SCNetworkSetGetServiceOrder(net_set); sorted = CFArrayCreateMutableCopy(NULL, 0, services); CFArraySortValues(sorted, CFRangeMake(0, CFArrayGetCount(sorted)), _SCNetworkServiceCompare, (void *)order); CFRelease(services); services = sorted; } } if (services == NULL) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } n = CFArrayGetCount(services); for (i = 0; i < n; i++) { SCNetworkServiceRef service; CFStringRef serviceName; CFStringRef serviceID; service = CFArrayGetValueAtIndex(services, i); serviceID = SCNetworkServiceGetServiceID(service); serviceName = SCNetworkServiceGetName(service); if (serviceName == NULL) serviceName = CFSTR(""); SCPrint(TRUE, stdout, CFSTR("%c%2ld: %@%-*s (%@)%s\n"), ((net_service != NULL) && CFEqual(service, net_service)) ? '>' : ' ', i + 1, serviceName, (int)(30 - CFStringGetLength(serviceName)), " ", serviceID, SCNetworkServiceGetEnabled(service) ? "" : " *DISABLED*"); __show_service_interface(service, " Interface : "); __show_service_protocols(service, " ", TRUE); } return; }
darlinghq/darling
src/configd/scutil.tproj/net_service.c
C
gpl-3.0
23,732
/* * linux/arch/arm/mach-omap2/id.c * * OMAP2 CPU identification code * * Copyright (C) 2005 Nokia Corporation * Written by Tony Lindgren <tony@atomide.com> * * Copyright (C) 2009-11 Texas Instruments * Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/io.h> #include <linux/random.h> #include <linux/slab.h> #ifdef CONFIG_SOC_BUS #include <linux/sys_soc.h> #endif #include <asm/cputype.h> #include "common.h" #include "id.h" #include "soc.h" #include "control.h" #define OMAP4_SILICON_TYPE_STANDARD 0x01 #define OMAP4_SILICON_TYPE_PERFORMANCE 0x02 #define OMAP_SOC_MAX_NAME_LENGTH 16 static unsigned int omap_revision; static char soc_name[OMAP_SOC_MAX_NAME_LENGTH]; static char soc_rev[OMAP_SOC_MAX_NAME_LENGTH]; u32 omap_features; unsigned int omap_rev(void) { return omap_revision; } EXPORT_SYMBOL(omap_rev); int omap_type(void) { static u32 val = OMAP2_DEVICETYPE_MASK; if (val < OMAP2_DEVICETYPE_MASK) { return val; } if (soc_is_omap24xx()) { val = omap_ctrl_readl(OMAP24XX_CONTROL_STATUS); } else if (soc_is_ti81xx()) { val = omap_ctrl_readl(TI81XX_CONTROL_STATUS); } else if (soc_is_am33xx() || soc_is_am43xx()) { val = omap_ctrl_readl(AM33XX_CONTROL_STATUS); } else if (soc_is_omap34xx()) { val = omap_ctrl_readl(OMAP343X_CONTROL_STATUS); } else if (soc_is_omap44xx()) { val = omap_ctrl_readl(OMAP4_CTRL_MODULE_CORE_STATUS); } else if (soc_is_omap54xx() || soc_is_dra7xx()) { val = omap_ctrl_readl(OMAP5XXX_CONTROL_STATUS); val &= OMAP5_DEVICETYPE_MASK; val >>= 6; goto out; } else { pr_err("Cannot detect omap type!\n"); goto out; } val &= OMAP2_DEVICETYPE_MASK; val >>= 8; out: return val; } EXPORT_SYMBOL(omap_type); /*----------------------------------------------------------------------------*/ #define OMAP_TAP_IDCODE 0x0204 #define OMAP_TAP_DIE_ID_0 0x0218 #define OMAP_TAP_DIE_ID_1 0x021C #define OMAP_TAP_DIE_ID_2 0x0220 #define OMAP_TAP_DIE_ID_3 0x0224 #define OMAP_TAP_DIE_ID_44XX_0 0x0200 #define OMAP_TAP_DIE_ID_44XX_1 0x0208 #define OMAP_TAP_DIE_ID_44XX_2 0x020c #define OMAP_TAP_DIE_ID_44XX_3 0x0210 #define read_tap_reg(reg) readl_relaxed(tap_base + (reg)) struct omap_id { u16 hawkeye; /* Silicon type (Hawkeye id) */ u8 dev; /* Device type from production_id reg */ u32 type; /* Combined type id copied to omap_revision */ }; /* Register values to detect the OMAP version */ static struct omap_id omap_ids[] __initdata = { { .hawkeye = 0xb5d9, .dev = 0x0, .type = 0x24200024 }, { .hawkeye = 0xb5d9, .dev = 0x1, .type = 0x24201024 }, { .hawkeye = 0xb5d9, .dev = 0x2, .type = 0x24202024 }, { .hawkeye = 0xb5d9, .dev = 0x4, .type = 0x24220024 }, { .hawkeye = 0xb5d9, .dev = 0x8, .type = 0x24230024 }, { .hawkeye = 0xb68a, .dev = 0x0, .type = 0x24300024 }, }; static void __iomem *tap_base; static u16 tap_prod_id; void omap_get_die_id(struct omap_die_id *odi) { if (soc_is_omap44xx() || soc_is_omap54xx() || soc_is_dra7xx()) { odi->id_0 = read_tap_reg(OMAP_TAP_DIE_ID_44XX_0); odi->id_1 = read_tap_reg(OMAP_TAP_DIE_ID_44XX_1); odi->id_2 = read_tap_reg(OMAP_TAP_DIE_ID_44XX_2); odi->id_3 = read_tap_reg(OMAP_TAP_DIE_ID_44XX_3); return; } odi->id_0 = read_tap_reg(OMAP_TAP_DIE_ID_0); odi->id_1 = read_tap_reg(OMAP_TAP_DIE_ID_1); odi->id_2 = read_tap_reg(OMAP_TAP_DIE_ID_2); odi->id_3 = read_tap_reg(OMAP_TAP_DIE_ID_3); } static int __init omap_feed_randpool(void) { struct omap_die_id odi; /* Throw the die ID into the entropy pool at boot */ omap_get_die_id(&odi); add_device_randomness(&odi, sizeof(odi)); return 0; } omap_device_initcall(omap_feed_randpool); void __init omap2xxx_check_revision(void) { int i, j; u32 idcode, prod_id; u16 hawkeye; u8 dev_type, rev; struct omap_die_id odi; idcode = read_tap_reg(OMAP_TAP_IDCODE); prod_id = read_tap_reg(tap_prod_id); hawkeye = (idcode >> 12) & 0xffff; rev = (idcode >> 28) & 0x0f; dev_type = (prod_id >> 16) & 0x0f; omap_get_die_id(&odi); pr_debug("OMAP_TAP_IDCODE 0x%08x REV %i HAWKEYE 0x%04x MANF %03x\n", idcode, rev, hawkeye, (idcode >> 1) & 0x7ff); pr_debug("OMAP_TAP_DIE_ID_0: 0x%08x\n", odi.id_0); pr_debug("OMAP_TAP_DIE_ID_1: 0x%08x DEV_REV: %i\n", odi.id_1, (odi.id_1 >> 28) & 0xf); pr_debug("OMAP_TAP_DIE_ID_2: 0x%08x\n", odi.id_2); pr_debug("OMAP_TAP_DIE_ID_3: 0x%08x\n", odi.id_3); pr_debug("OMAP_TAP_PROD_ID_0: 0x%08x DEV_TYPE: %i\n", prod_id, dev_type); /* Check hawkeye ids */ for (i = 0; i < ARRAY_SIZE(omap_ids); i++) { if (hawkeye == omap_ids[i].hawkeye) { break; } } if (i == ARRAY_SIZE(omap_ids)) { printk(KERN_ERR "Unknown OMAP CPU id\n"); return; } for (j = i; j < ARRAY_SIZE(omap_ids); j++) { if (dev_type == omap_ids[j].dev) { break; } } if (j == ARRAY_SIZE(omap_ids)) { pr_err("Unknown OMAP device type. Handling it as OMAP%04x\n", omap_ids[i].type >> 16); j = i; } sprintf(soc_name, "OMAP%04x", omap_rev() >> 16); sprintf(soc_rev, "ES%x", (omap_rev() >> 12) & 0xf); pr_info("%s", soc_name); if ((omap_rev() >> 8) & 0x0f) { pr_info("%s", soc_rev); } pr_info("\n"); } #define OMAP3_SHOW_FEATURE(feat) \ if (omap3_has_ ##feat()) \ printk(#feat" "); static void __init omap3_cpuinfo(void) { const char *cpu_name; /* * OMAP3430 and OMAP3530 are assumed to be same. * * OMAP3525, OMAP3515 and OMAP3503 can be detected only based * on available features. Upon detection, update the CPU id * and CPU class bits. */ if (soc_is_omap3630()) { cpu_name = "OMAP3630"; } else if (soc_is_am35xx()) { cpu_name = (omap3_has_sgx()) ? "AM3517" : "AM3505"; } else if (soc_is_ti816x()) { cpu_name = "TI816X"; } else if (soc_is_am335x()) { cpu_name = "AM335X"; } else if (soc_is_am437x()) { cpu_name = "AM437x"; } else if (soc_is_ti814x()) { cpu_name = "TI814X"; } else if (omap3_has_iva() && omap3_has_sgx()) { /* OMAP3430, OMAP3525, OMAP3515, OMAP3503 devices */ cpu_name = "OMAP3430/3530"; } else if (omap3_has_iva()) { cpu_name = "OMAP3525"; } else if (omap3_has_sgx()) { cpu_name = "OMAP3515"; } else { cpu_name = "OMAP3503"; } sprintf(soc_name, "%s", cpu_name); /* Print verbose information */ pr_info("%s %s (", soc_name, soc_rev); OMAP3_SHOW_FEATURE(l2cache); OMAP3_SHOW_FEATURE(iva); OMAP3_SHOW_FEATURE(sgx); OMAP3_SHOW_FEATURE(neon); OMAP3_SHOW_FEATURE(isp); OMAP3_SHOW_FEATURE(192mhz_clk); printk(")\n"); } #define OMAP3_CHECK_FEATURE(status,feat) \ if (((status & OMAP3_ ##feat## _MASK) \ >> OMAP3_ ##feat## _SHIFT) != FEAT_ ##feat## _NONE) { \ omap_features |= OMAP3_HAS_ ##feat; \ } void __init omap3xxx_check_features(void) { u32 status; omap_features = 0; status = omap_ctrl_readl(OMAP3_CONTROL_OMAP_STATUS); OMAP3_CHECK_FEATURE(status, L2CACHE); OMAP3_CHECK_FEATURE(status, IVA); OMAP3_CHECK_FEATURE(status, SGX); OMAP3_CHECK_FEATURE(status, NEON); OMAP3_CHECK_FEATURE(status, ISP); if (soc_is_omap3630()) { omap_features |= OMAP3_HAS_192MHZ_CLK; } if (soc_is_omap3430() || soc_is_omap3630()) { omap_features |= OMAP3_HAS_IO_WAKEUP; } if (soc_is_omap3630() || omap_rev() == OMAP3430_REV_ES3_1 || omap_rev() == OMAP3430_REV_ES3_1_2) { omap_features |= OMAP3_HAS_IO_CHAIN_CTRL; } omap_features |= OMAP3_HAS_SDRC; /* * am35x fixups: * - The am35x Chip ID register has bits 12, 7:5, and 3:2 marked as * reserved and therefore return 0 when read. Unfortunately, * OMAP3_CHECK_FEATURE() will interpret some of those zeroes to * mean that a feature is present even though it isn't so clear * the incorrectly set feature bits. */ if (soc_is_am35xx()) { omap_features &= ~(OMAP3_HAS_IVA | OMAP3_HAS_ISP); } /* * TODO: Get additional info (where applicable) * e.g. Size of L2 cache. */ omap3_cpuinfo(); } void __init omap4xxx_check_features(void) { u32 si_type; si_type = (read_tap_reg(OMAP4_CTRL_MODULE_CORE_STD_FUSE_PROD_ID_1) >> 16) & 0x03; if (si_type == OMAP4_SILICON_TYPE_PERFORMANCE) { omap_features = OMAP4_HAS_PERF_SILICON; } } void __init ti81xx_check_features(void) { omap_features = OMAP3_HAS_NEON; omap3_cpuinfo(); } void __init am33xx_check_features(void) { u32 status; omap_features = OMAP3_HAS_NEON; status = omap_ctrl_readl(AM33XX_DEV_FEATURE); if (status & AM33XX_SGX_MASK) { omap_features |= OMAP3_HAS_SGX; } omap3_cpuinfo(); } void __init omap3xxx_check_revision(void) { const char *cpu_rev; u32 cpuid, idcode; u16 hawkeye; u8 rev; /* * We cannot access revision registers on ES1.0. * If the processor type is Cortex-A8 and the revision is 0x0 * it means its Cortex r0p0 which is 3430 ES1.0. */ cpuid = read_cpuid_id(); if ((((cpuid >> 4) & 0xfff) == 0xc08) && ((cpuid & 0xf) == 0x0)) { omap_revision = OMAP3430_REV_ES1_0; cpu_rev = "1.0"; return; } /* * Detection for 34xx ES2.0 and above can be done with just * hawkeye and rev. See TRM 1.5.2 Device Identification. * Note that rev does not map directly to our defined processor * revision numbers as ES1.0 uses value 0. */ idcode = read_tap_reg(OMAP_TAP_IDCODE); hawkeye = (idcode >> 12) & 0xffff; rev = (idcode >> 28) & 0xff; switch (hawkeye) { case 0xb7ae: /* Handle 34xx/35xx devices */ switch (rev) { case 0: /* Take care of early samples */ case 1: omap_revision = OMAP3430_REV_ES2_0; cpu_rev = "2.0"; break; case 2: omap_revision = OMAP3430_REV_ES2_1; cpu_rev = "2.1"; break; case 3: omap_revision = OMAP3430_REV_ES3_0; cpu_rev = "3.0"; break; case 4: omap_revision = OMAP3430_REV_ES3_1; cpu_rev = "3.1"; break; case 7: /* FALLTHROUGH */ default: /* Use the latest known revision as default */ omap_revision = OMAP3430_REV_ES3_1_2; cpu_rev = "3.1.2"; } break; case 0xb868: /* * Handle OMAP/AM 3505/3517 devices * * Set the device to be OMAP3517 here. Actual device * is identified later based on the features. */ switch (rev) { case 0: omap_revision = AM35XX_REV_ES1_0; cpu_rev = "1.0"; break; case 1: /* FALLTHROUGH */ default: omap_revision = AM35XX_REV_ES1_1; cpu_rev = "1.1"; } break; case 0xb891: /* Handle 36xx devices */ switch (rev) { case 0: /* Take care of early samples */ omap_revision = OMAP3630_REV_ES1_0; cpu_rev = "1.0"; break; case 1: omap_revision = OMAP3630_REV_ES1_1; cpu_rev = "1.1"; break; case 2: /* FALLTHROUGH */ default: omap_revision = OMAP3630_REV_ES1_2; cpu_rev = "1.2"; } break; case 0xb81e: switch (rev) { case 0: omap_revision = TI8168_REV_ES1_0; cpu_rev = "1.0"; break; case 1: omap_revision = TI8168_REV_ES1_1; cpu_rev = "1.1"; break; case 2: omap_revision = TI8168_REV_ES2_0; cpu_rev = "2.0"; break; case 3: /* FALLTHROUGH */ default: omap_revision = TI8168_REV_ES2_1; cpu_rev = "2.1"; } break; case 0xb944: switch (rev) { case 0: omap_revision = AM335X_REV_ES1_0; cpu_rev = "1.0"; break; case 1: omap_revision = AM335X_REV_ES2_0; cpu_rev = "2.0"; break; case 2: /* FALLTHROUGH */ default: omap_revision = AM335X_REV_ES2_1; cpu_rev = "2.1"; break; } break; case 0xb98c: switch (rev) { case 0: omap_revision = AM437X_REV_ES1_0; cpu_rev = "1.0"; break; case 1: omap_revision = AM437X_REV_ES1_1; cpu_rev = "1.1"; break; case 2: /* FALLTHROUGH */ default: omap_revision = AM437X_REV_ES1_2; cpu_rev = "1.2"; break; } break; case 0xb8f2: case 0xb968: switch (rev) { case 0: /* FALLTHROUGH */ case 1: omap_revision = TI8148_REV_ES1_0; cpu_rev = "1.0"; break; case 2: omap_revision = TI8148_REV_ES2_0; cpu_rev = "2.0"; break; case 3: /* FALLTHROUGH */ default: omap_revision = TI8148_REV_ES2_1; cpu_rev = "2.1"; break; } break; default: /* Unknown default to latest silicon rev as default */ omap_revision = OMAP3630_REV_ES1_2; cpu_rev = "1.2"; pr_warn("Warning: unknown chip type: hawkeye %04x, assuming OMAP3630ES1.2\n", hawkeye); } sprintf(soc_rev, "ES%s", cpu_rev); } void __init omap4xxx_check_revision(void) { u32 idcode; u16 hawkeye; u8 rev; /* * The IC rev detection is done with hawkeye and rev. * Note that rev does not map directly to defined processor * revision numbers as ES1.0 uses value 0. */ idcode = read_tap_reg(OMAP_TAP_IDCODE); hawkeye = (idcode >> 12) & 0xffff; rev = (idcode >> 28) & 0xf; /* * Few initial 4430 ES2.0 samples IDCODE is same as ES1.0 * Use ARM register to detect the correct ES version */ if (!rev && (hawkeye != 0xb94e) && (hawkeye != 0xb975)) { idcode = read_cpuid_id(); rev = (idcode & 0xf) - 1; } switch (hawkeye) { case 0xb852: switch (rev) { case 0: omap_revision = OMAP4430_REV_ES1_0; break; case 1: default: omap_revision = OMAP4430_REV_ES2_0; } break; case 0xb95c: switch (rev) { case 3: omap_revision = OMAP4430_REV_ES2_1; break; case 4: omap_revision = OMAP4430_REV_ES2_2; break; case 6: default: omap_revision = OMAP4430_REV_ES2_3; } break; case 0xb94e: switch (rev) { case 0: omap_revision = OMAP4460_REV_ES1_0; break; case 2: default: omap_revision = OMAP4460_REV_ES1_1; break; } break; case 0xb975: switch (rev) { case 0: default: omap_revision = OMAP4470_REV_ES1_0; break; } break; default: /* Unknown default to latest silicon rev as default */ omap_revision = OMAP4430_REV_ES2_3; } sprintf(soc_name, "OMAP%04x", omap_rev() >> 16); sprintf(soc_rev, "ES%d.%d", (omap_rev() >> 12) & 0xf, (omap_rev() >> 8) & 0xf); pr_info("%s %s\n", soc_name, soc_rev); } void __init omap5xxx_check_revision(void) { u32 idcode; u16 hawkeye; u8 rev; idcode = read_tap_reg(OMAP_TAP_IDCODE); hawkeye = (idcode >> 12) & 0xffff; rev = (idcode >> 28) & 0xff; switch (hawkeye) { case 0xb942: switch (rev) { case 0: /* No support for ES1.0 Test chip */ BUG(); case 1: default: omap_revision = OMAP5430_REV_ES2_0; } break; case 0xb998: switch (rev) { case 0: /* No support for ES1.0 Test chip */ BUG(); case 1: default: omap_revision = OMAP5432_REV_ES2_0; } break; default: /* Unknown default to latest silicon rev as default*/ omap_revision = OMAP5430_REV_ES2_0; } sprintf(soc_name, "OMAP%04x", omap_rev() >> 16); sprintf(soc_rev, "ES%d.0", (omap_rev() >> 12) & 0xf); pr_info("%s %s\n", soc_name, soc_rev); } void __init dra7xxx_check_revision(void) { u32 idcode; u16 hawkeye; u8 rev; idcode = read_tap_reg(OMAP_TAP_IDCODE); hawkeye = (idcode >> 12) & 0xffff; rev = (idcode >> 28) & 0xff; switch (hawkeye) { case 0xb990: switch (rev) { case 0: omap_revision = DRA752_REV_ES1_0; break; case 1: omap_revision = DRA752_REV_ES1_1; break; case 2: default: omap_revision = DRA752_REV_ES2_0; break; } break; case 0xb9bc: switch (rev) { case 0: omap_revision = DRA722_REV_ES1_0; break; case 1: default: omap_revision = DRA722_REV_ES2_0; break; } break; default: /* Unknown default to latest silicon rev as default*/ pr_warn("%s: unknown idcode=0x%08x (hawkeye=0x%08x,rev=0x%x)\n", __func__, idcode, hawkeye, rev); omap_revision = DRA752_REV_ES2_0; } sprintf(soc_name, "DRA%03x", omap_rev() >> 16); sprintf(soc_rev, "ES%d.%d", (omap_rev() >> 12) & 0xf, (omap_rev() >> 8) & 0xf); pr_info("%s %s\n", soc_name, soc_rev); } /* * Set up things for map_io and processor detection later on. Gets called * pretty much first thing from board init. For multi-omap, this gets * cpu_is_omapxxxx() working accurately enough for map_io. Then we'll try to * detect the exact revision later on in omap2_detect_revision() once map_io * is done. */ void __init omap2_set_globals_tap(u32 class, void __iomem *tap) { omap_revision = class; tap_base = tap; /* XXX What is this intended to do? */ if (soc_is_omap34xx()) { tap_prod_id = 0x0210; } else { tap_prod_id = 0x0208; } } #ifdef CONFIG_SOC_BUS static const char *const omap_types[] = { [OMAP2_DEVICE_TYPE_TEST] = "TST", [OMAP2_DEVICE_TYPE_EMU] = "EMU", [OMAP2_DEVICE_TYPE_SEC] = "HS", [OMAP2_DEVICE_TYPE_GP] = "GP", [OMAP2_DEVICE_TYPE_BAD] = "BAD", }; static const char *__init omap_get_family(void) { if (soc_is_omap24xx()) { return kasprintf(GFP_KERNEL, "OMAP2"); } else if (soc_is_omap34xx()) { return kasprintf(GFP_KERNEL, "OMAP3"); } else if (soc_is_omap44xx()) { return kasprintf(GFP_KERNEL, "OMAP4"); } else if (soc_is_omap54xx()) { return kasprintf(GFP_KERNEL, "OMAP5"); } else if (soc_is_am33xx() || soc_is_am335x()) { return kasprintf(GFP_KERNEL, "AM33xx"); } else if (soc_is_am43xx()) { return kasprintf(GFP_KERNEL, "AM43xx"); } else if (soc_is_dra7xx()) { return kasprintf(GFP_KERNEL, "DRA7"); } else { return kasprintf(GFP_KERNEL, "Unknown"); } } static ssize_t omap_get_type(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%s\n", omap_types[omap_type()]); } static struct device_attribute omap_soc_attr = __ATTR(type, S_IRUGO, omap_get_type, NULL); void __init omap_soc_device_init(void) { struct device *parent; struct soc_device *soc_dev; struct soc_device_attribute *soc_dev_attr; soc_dev_attr = kzalloc(sizeof(*soc_dev_attr), GFP_KERNEL); if (!soc_dev_attr) { return; } soc_dev_attr->machine = soc_name; soc_dev_attr->family = omap_get_family(); soc_dev_attr->revision = soc_rev; soc_dev = soc_device_register(soc_dev_attr); if (IS_ERR(soc_dev)) { kfree(soc_dev_attr); return; } parent = soc_device_to_device(soc_dev); device_create_file(parent, &omap_soc_attr); } #endif /* CONFIG_SOC_BUS */
williamfdevine/PrettyLinux
arch/arm/mach-omap2/id.c
C
gpl-3.0
18,591
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Duality.Resources; using Duality.Backend; namespace Duality.Drawing { public class DrawDevice : IDrawDevice, IDisposable { /// <summary> /// Represents a drawing input from <see cref="AddVertices"/> using /// dynamically gathered vertices. /// </summary> private struct VertexDrawItem { /// <summary> /// The offset in the shared vertex buffer where this drawing items vertex data begins. /// </summary> public ushort Offset; /// <summary> /// The number of vertices that are rendered by this drawing item. /// </summary> public ushort Count; /// <summary> /// The index of the vertex buffer that is used by this drawing item. /// </summary> public byte BufferIndex; /// <summary> /// The <see cref="VertexDeclaration"/> type index that describes the vertices used by this drawing item. /// </summary> public byte TypeIndex; /// <summary> /// The <see cref="VertexMode"/> that describes how the vertices are assembled into geometry. /// </summary> public VertexMode Mode; /// <summary> /// The material / <see cref="BatchInfo"/> that describes how the vertices will be rendered. /// </summary> public BatchInfo Material; /// <summary> /// Determines whether this item could share the same <see cref="DrawBatch"/> /// with the specified other item. /// </summary> /// <param name="other"></param> /// <returns></returns> public bool CanShareBatchWith(ref VertexDrawItem other) { return this.Mode == other.Mode && this.TypeIndex == other.TypeIndex && this.BufferIndex == other.BufferIndex && this.Material.Equals(other.Material); } /// <summary> /// Determines whether the specified item could be appended as-is to this item. /// </summary> /// <param name="other"></param> /// <returns></returns> public bool CanAppend(ref VertexDrawItem other) { return this.Offset + this.Count == other.Offset && this.Mode == other.Mode && this.TypeIndex == other.TypeIndex && this.BufferIndex == other.BufferIndex && this.Material.Equals(other.Material); } public override string ToString() { VertexDeclaration declaration = VertexDeclaration.Get(this.TypeIndex); return string.Format( "{0}[{1}@{2}] as {3}, '{4}'", declaration.DataType.Name, this.Count, this.Offset, this.Mode, this.Material); } } /// <summary> /// Represents an item in a sorting queue that is associated with /// a <see cref="VertexDrawItem"/>. This struct is actually a union /// that uses either <see cref="SortDepth"/> or <see cref="SortIndex"/> /// depending on whether sorting is done based on material or depth. /// </summary> [StructLayout(LayoutKind.Explicit)] private struct SortItem { /// <summary> /// A drawing buffer index where the associated <see cref="VertexDrawItem"/> /// can be found. /// </summary> [FieldOffset(0)] public int DrawItemIndex; /// <summary> /// The material sorting index for this item. /// </summary> [FieldOffset(4)] public int SortIndex; /// <summary> /// The depth sorting reference value for this item. /// </summary> [FieldOffset(4)] public float SortDepth; /// <summary> /// Determines whether this item shares roughly the specified reference depth. /// </summary> /// <param name="otherDepth"></param> /// <returns></returns> public bool CanShareDepth(float otherDepth) { return Math.Abs(this.SortDepth - otherDepth) < 0.00001f; } /// <summary> /// Adjusts this items <see cref="SortDepth"/> value to account for a merge /// with another item. /// </summary> /// <param name="otherDepth"></param> /// <param name="count"></param> /// <param name="otherCount"></param> public void MergeDepth(float otherDepth, int count, int otherCount) { this.SortDepth = (float)(count * this.SortDepth + otherCount * otherDepth) / (float)(count + otherCount); } public override string ToString() { return string.Format( "Item {0}, Sort Index {1} / Depth {2:F}", this.DrawItemIndex, this.SortIndex, this.SortDepth); } } /// <summary> /// The default reference distance for perspective rendering. /// </summary> public const float DefaultFocusDist = 500.0f; private bool disposed = false; private float nearZ = 50.0f; private float farZ = 10000.0f; private float focusDist = DefaultFocusDist; private ClearFlag clearFlags = ClearFlag.All; private ColorRgba clearColor = ColorRgba.TransparentBlack; private float clearDepth = 1.0f; private Vector2 targetSize = Vector2.Zero; private Rect viewportRect = Rect.Empty; private Vector3 viewerPos = Vector3.Zero; private float viewerAngle = 0.0f; private ContentRef<RenderTarget> renderTarget = null; private ProjectionMode projection = ProjectionMode.Perspective; private Matrix4 matView = Matrix4.Identity; private Matrix4 matProjection = Matrix4.Identity; private Matrix4 matFinal = Matrix4.Identity; private Matrix4 matFinalInv = Matrix4.Identity; private VisibilityFlag visibilityMask = VisibilityFlag.All; private int pickingIndex = 0; private ShaderParameterCollection shaderParameters = new ShaderParameterCollection(); private RenderOptions renderOptions = new RenderOptions(); private RenderStats renderStats = new RenderStats(); private List<BatchInfo> tempMaterialPool = new List<BatchInfo>(); private int tempMaterialIndex = 0; private VertexBatchStore drawVertices = new VertexBatchStore(ushort.MaxValue); private RawList<VertexDrawItem> drawBuffer = new RawList<VertexDrawItem>(); private RawList<SortItem> sortBufferSolid = new RawList<SortItem>(); private RawList<SortItem> sortBufferBlended = new RawList<SortItem>(); private RawList<SortItem> sortBufferTemp = new RawList<SortItem>(); private RawList<DrawBatch> batchBufferSolid = new RawList<DrawBatch>(); private RawList<DrawBatch> batchBufferBlended = new RawList<DrawBatch>(); private RawListPool<VertexDrawRange> batchIndexPool = new RawListPool<VertexDrawRange>(); private RawList<RawList<VertexBuffer>> vertexBuffers = new RawList<RawList<VertexBuffer>>(); private int numRawBatches = 0; public bool Disposed { get { return this.disposed; } } public Vector3 ViewerPos { get { return this.viewerPos; } set { if (this.viewerPos == value) return; this.viewerPos = value; this.UpdateMatrices(); } } public float ViewerAngle { get { return this.viewerAngle; } set { if (this.viewerAngle == value) return; this.viewerAngle = value; this.UpdateMatrices(); } } public float FocusDist { get { return this.focusDist; } set { if (this.focusDist == value) return; this.focusDist = value; this.UpdateMatrices(); } } public VisibilityFlag VisibilityMask { get { return this.visibilityMask; } set { this.visibilityMask = value; } } public float NearZ { get { return this.nearZ; } set { if (this.nearZ == value) return; this.nearZ = value; this.UpdateMatrices(); } } public float FarZ { get { return this.farZ; } set { if (this.farZ == value) return; this.farZ = value; this.UpdateMatrices(); } } /// <summary> /// [GET / SET] The clear color to apply when clearing the color buffer. /// </summary> public ColorRgba ClearColor { get { return this.clearColor; } set { this.clearColor = value; } } /// <summary> /// [GET / SET] The clear depth to apply when clearing the depth buffer /// </summary> public float ClearDepth { get { return this.clearDepth; } set { this.clearDepth = value; } } /// <summary> /// [GET / SET] Specifies which buffers to clean before rendering with this device. /// </summary> public ClearFlag ClearFlags { get { return this.clearFlags; } set { this.clearFlags = value; } } /// <summary> /// [GET / SET] Specified the projection that is applied when rendering the world. /// </summary> public ProjectionMode Projection { get { return this.projection; } set { if (this.projection == value) return; this.projection = value; this.UpdateMatrices(); } } public ContentRef<RenderTarget> Target { get { return this.renderTarget; } set { this.renderTarget = value; } } public int PickingIndex { get { return this.pickingIndex; } set { this.pickingIndex = value; } } public bool IsPicking { get { return this.pickingIndex != 0; } } public Rect ViewportRect { get { return this.viewportRect; } set { this.viewportRect = value; } } public Vector2 TargetSize { get { return this.targetSize; } set { if (this.targetSize == value) return; this.targetSize = value; this.UpdateMatrices(); } } /// <summary> /// [GET] Provides access to the drawing devices shared <see cref="ShaderParameterCollection"/>, /// which allows to specify a parameter value globally across all materials rendered by this /// <see cref="DrawDevice"/>. /// </summary> public ShaderParameterCollection ShaderParameters { get { return this.shaderParameters; } } public void Dispose() { if (this.disposed) return; this.disposed = true; // Set big object references to null to make // sure they're garbage collected even when keeping // a reference to the disposed DrawDevice around. this.renderOptions = null; this.renderStats = null; this.tempMaterialPool = null; this.drawVertices = null; this.drawBuffer = null; this.sortBufferSolid = null; this.sortBufferBlended = null; this.sortBufferTemp = null; this.batchBufferSolid = null; this.batchBufferBlended = null; this.batchIndexPool = null; } /// <summary> /// Returns the scale factor of objects that are located at the specified world space Z position. /// </summary> /// <param name="z"></param> /// <returns></returns> public float GetScaleAtZ(float z) { if (this.projection == ProjectionMode.Screen) return 1.0f; else if (this.projection == ProjectionMode.Perspective) return this.focusDist / Math.Max(z - this.viewerPos.Z, this.nearZ); else return this.focusDist / DefaultFocusDist; } /// <summary> /// Transforms screen space to world space positions. The screen positions Z coordinate is /// interpreted as the target world Z coordinate. /// </summary> /// <param name="screenPos"></param> /// <returns></returns> public Vector3 GetWorldPos(Vector3 screenPos) { // Determine which clip space depth and divide the target Z corresponds to Vector4 targetWorldPos = new Vector4(0.0f, 0.0f, screenPos.Z, 1.0f); Vector4 targetClipPos; Vector4.Transform(ref targetWorldPos, ref this.matFinal, out targetClipPos); // Calculate the clip space position for the specified screen position Vector4 clipPos; clipPos.X = (2.0f * screenPos.X / this.targetSize.X) - 1.0f; clipPos.Y = -(2.0f * screenPos.Y / this.targetSize.Y) + 1.0f; clipPos.Z = targetClipPos.Z; clipPos.W = targetClipPos.W; // Inverse perspective divide on the normalized screen coordinates clipPos.X *= targetClipPos.W; clipPos.Y *= targetClipPos.W; // Do an inverse transformation with projection and view matrix Vector4 worldPos; Vector4.Transform(ref clipPos, ref this.matFinalInv, out worldPos); return worldPos.Xyz; } /// <summary> /// Transforms world space to screen space positions. /// </summary> /// <param name="worldPos"></param> /// <returns></returns> public Vector2 GetScreenPos(Vector3 worldPos) { // Transform coordinate into clip space Vector4 worldPosFull = new Vector4(worldPos, 1.0f); Vector4 clipPos; Vector4.Transform(ref worldPosFull, ref this.matFinal, out clipPos); // Apply the perspective divide and invert Y float invClipW = 1.0f / MathF.Max(clipPos.W, 0.000001f); clipPos.X *= invClipW; clipPos.Y *= -invClipW; // Transform NDC coordinates to pixel coordinates Vector2 screenPos; screenPos.X = (clipPos.X + 1.0f) * 0.5f * this.targetSize.X; screenPos.Y = (clipPos.Y + 1.0f) * 0.5f * this.targetSize.Y; return screenPos; } /// <summary> /// Determines whether a point or sphere is inside the devices viewing frustum, /// given a world space position and radius. /// </summary> /// <param name="worldPos">The points world space position.</param> /// <param name="radius">A world space radius around the point.</param> /// <returns></returns> public bool IsSphereInView(Vector3 worldPos, float radius) { // Transform coordinate into clip space Vector4 worldPosFull = new Vector4(worldPos, 1.0f); Vector4 clipPos; Vector4.Transform(ref worldPosFull, ref this.matFinal, out clipPos); // If the perspective divide near zero or negative, we know it's something behind the camera. Discard. if (clipPos.W < 0.000000001f) return false; // Apply the perspective divide float invClipW = 1.0f / clipPos.W; clipPos.X *= invClipW; clipPos.Y *= invClipW; clipPos.Z *= invClipW; Vector2 clipRadius; clipRadius.X = radius * Math.Abs(this.matProjection.Row0.X) * invClipW; clipRadius.Y = radius * Math.Abs(this.matProjection.Row1.Y) * invClipW; // Check if the result would still be within valid device coordinates return clipPos.Z >= -1.0f && clipPos.Z <= 1.0f && clipPos.X >= -1.0f - clipRadius.X && clipPos.X <= 1.0f + clipRadius.X && clipPos.Y >= -1.0f - clipRadius.Y && clipPos.Y <= 1.0f + clipRadius.Y; } /// <summary> /// Rents a temporary material instance which can be used for rendering. The instance /// is returned implicitly when the device is done with the current rendering operation. /// </summary> /// <returns></returns> public BatchInfo RentMaterial() { int index = this.tempMaterialIndex++; if (index >= this.tempMaterialPool.Count) this.tempMaterialPool.Add(new BatchInfo()); return this.tempMaterialPool[index]; } /// <summary> /// Adds a parameterized set of vertices to the drawing devices rendering schedule. /// </summary> /// <typeparam name="T">The type of vertex data to add.</typeparam> /// <param name="material">The <see cref="Duality.Drawing.BatchInfo"/> to use for rendering the vertices.</param> /// <param name="vertexMode">The vertices drawing mode.</param> /// <param name="vertexBuffer"> /// A vertex data buffer that stores the vertices to add. Ownership of the buffer /// remains at the callsite, while the <see cref="IDrawDevice"/> copies the required /// data into internal storage. /// </param> /// <param name="vertexCount">The number of vertices to add, from the beginning of the buffer.</param> public void AddVertices<T>(BatchInfo material, VertexMode vertexMode, T[] vertexBuffer, int vertexOffset, int vertexCount) where T : struct, IVertexData { if (vertexCount == 0) return; if (vertexBuffer == null || vertexBuffer.Length == 0) return; if (vertexCount > vertexBuffer.Length) vertexCount = vertexBuffer.Length; if (material == null) material = Material.SolidWhite.Res.Info; // In picking mode, override incoming vertices material and vertex colors // to generate a lookup texture by which we can retrieve each pixels object. if (this.pickingIndex != 0) { ColorRgba clr = new ColorRgba((this.pickingIndex << 8) | 0xFF); for (int i = 0; i < vertexCount; ++i) vertexBuffer[i].Color = clr; material = this.RentMaterial(material); material.Technique = DrawTechnique.Picking; material.MainColor = ColorRgba.White; } else if (material.Technique == null || !material.Technique.IsAvailable) { material = this.RentMaterial(material); material.Technique = DrawTechnique.Solid; } // Move the added vertices to an internal shared buffer VertexSlice<T> slice = this.drawVertices.Rent<T>(vertexCount); Array.Copy(vertexBuffer, vertexOffset, slice.Data, slice.Offset, slice.Length); // Aggregate all info we have about our incoming vertices VertexDrawItem drawItem = new VertexDrawItem { Offset = (ushort)slice.Offset, Count = (ushort)slice.Length, BufferIndex = (byte)(this.drawVertices.GetBatchCount<T>() - 1), TypeIndex = (byte)VertexDeclaration.Get<T>().TypeIndex, Mode = vertexMode, Material = material }; // Determine whether we need depth sorting and calculate a reference depth bool sortByDepth = (this.projection == ProjectionMode.Screen) || material.Technique.Res.NeedsZSort; RawList<SortItem> sortBuffer = sortByDepth ? this.sortBufferBlended : this.sortBufferSolid; SortItem sortItem = new SortItem(); if (sortByDepth) { sortItem.SortDepth = this.CalcZSortIndex<T>(vertexBuffer, vertexOffset, vertexCount); } // Determine whether we can batch the new vertex item with the previous one int prevDrawIndex = -1; if (vertexMode.IsBatchableMode() && sortBuffer.Count > 0) { // Since we require a complete material match to append items, we can // assume that the previous items sortByDepth value is the same as ours. SortItem prevSortItem = sortBuffer.Data[sortBuffer.Count - 1]; // Compare the previously added item with the new one. If everything // except the vertices themselves is the same, we can append them directly. if (this.drawBuffer.Data[prevSortItem.DrawItemIndex].CanAppend(ref drawItem) && (!sortByDepth || sortItem.CanShareDepth(prevSortItem.SortDepth))) { prevDrawIndex = prevSortItem.DrawItemIndex; } } // Append the new item directly to the previous one, or add it as a new one if (prevDrawIndex != -1) { if (sortByDepth) { sortBuffer.Data[sortBuffer.Count - 1].MergeDepth( sortItem.SortDepth, this.drawBuffer.Data[prevDrawIndex].Count, drawItem.Count); } this.drawBuffer.Data[prevDrawIndex].Count += drawItem.Count; } else { sortItem.DrawItemIndex = this.drawBuffer.Count; sortBuffer.Add(sortItem); this.drawBuffer.Add(drawItem); } ++this.numRawBatches; } /// <summary> /// Adds an already prepared batch to the drawing devices rendering schedule. /// </summary> /// <param name="batch"></param> public void AddBatch(DrawBatch batch) { bool sortByDepth = (this.projection == ProjectionMode.Screen) || batch.Material.Technique.Res.NeedsZSort; RawList<DrawBatch> batchBuffer = sortByDepth ? this.batchBufferBlended : this.batchBufferSolid; batchBuffer.Add(batch); ++this.numRawBatches; } /// <summary> /// Generates a single drawcall that renders a fullscreen quad using the specified material. /// Assumes that the <see cref="DrawDevice"/> is set up to render in screen space. /// </summary> /// <param name="material"></param> /// <param name="resizeMode"></param> public void AddFullscreenQuad(BatchInfo material, TargetResize resizeMode) { Texture tex = material.MainTexture.Res; Vector2 uvRatio = tex != null ? tex.UVRatio : Vector2.One; Point2 inputSize = tex != null ? tex.ContentSize : Point2.Zero; // Fit the input material rect to the output size according to rendering step config Vector2 targetSize = resizeMode.Apply(inputSize, this.TargetSize); Rect targetRect = Rect.Align( Alignment.Center, this.TargetSize.X * 0.5f, this.TargetSize.Y * 0.5f, targetSize.X, targetSize.Y); // Fit the target rect to actual pixel coordinates to avoid unnecessary filtering offsets targetRect.X = (int)targetRect.X; targetRect.Y = (int)targetRect.Y; targetRect.W = MathF.Ceiling(targetRect.W); targetRect.H = MathF.Ceiling(targetRect.H); VertexC1P3T2[] vertices = new VertexC1P3T2[4]; vertices[0].Pos = new Vector3(targetRect.LeftX, targetRect.TopY, 0.0f); vertices[1].Pos = new Vector3(targetRect.RightX, targetRect.TopY, 0.0f); vertices[2].Pos = new Vector3(targetRect.RightX, targetRect.BottomY, 0.0f); vertices[3].Pos = new Vector3(targetRect.LeftX, targetRect.BottomY, 0.0f); vertices[0].TexCoord = new Vector2(0.0f, 0.0f); vertices[1].TexCoord = new Vector2(uvRatio.X, 0.0f); vertices[2].TexCoord = new Vector2(uvRatio.X, uvRatio.Y); vertices[3].TexCoord = new Vector2(0.0f, uvRatio.Y); vertices[0].Color = ColorRgba.White; vertices[1].Color = ColorRgba.White; vertices[2].Color = ColorRgba.White; vertices[3].Color = ColorRgba.White; this.AddVertices(material, VertexMode.Quads, vertices); } public void PrepareForDrawcalls() { // Recalculate matrices according to current mode this.UpdateMatrices(); } public void Render() { if (DualityApp.GraphicsBackend == null) return; // Prepare forwarding the collected data and parameters to the graphics backend this.UploadVertexData(); this.AggregateBatches(); this.UpdateBuiltinShaderParameters(); bool overlayMode = (this.projection == ProjectionMode.Screen); this.renderOptions.ClearFlags = this.clearFlags; this.renderOptions.ClearColor = this.clearColor; this.renderOptions.ClearDepth = this.clearDepth; this.renderOptions.Viewport = this.viewportRect; this.renderOptions.ViewMatrix = this.matView; this.renderOptions.ProjectionMatrix = this.matProjection; this.renderOptions.DepthTest = !overlayMode; this.renderOptions.DepthWrite = !overlayMode; this.renderOptions.Target = this.renderTarget.IsAvailable ? this.renderTarget.Res.Native : null; this.renderOptions.ShaderParameters = this.shaderParameters; this.renderStats.Reset(); // Invoke graphics backend functionality to do the rendering DualityApp.GraphicsBackend.BeginRendering(this, this.renderOptions, this.renderStats); { //Profile.TimeProcessDrawcalls.BeginMeasure(); // Sorted as needed by batch optimizer DualityApp.GraphicsBackend.Render(this.batchBufferSolid); // Z-Sorted, back to Front DualityApp.GraphicsBackend.Render(this.batchBufferBlended); //Profile.TimeProcessDrawcalls.EndMeasure(); } DualityApp.GraphicsBackend.EndRendering(); //Profile.StatNumDrawcalls.Add(this.renderStats.DrawCalls); // Reset all temp materials and return them to the pool for (int i = 0; i < this.tempMaterialIndex; i++) { this.tempMaterialPool[i].Technique = DrawTechnique.Mask; this.tempMaterialPool[i].Reset(); } this.tempMaterialIndex = 0; // Clear all working buffers for vertex and drawcall processing this.drawBuffer.Clear(); this.sortBufferSolid.Clear(); this.sortBufferBlended.Clear(); this.sortBufferTemp.Clear(); this.batchBufferSolid.Clear(); this.batchBufferBlended.Clear(); this.drawVertices.Clear(); this.batchIndexPool.Reset(); } private float CalcZSortIndex<T>(T[] vertices, int offset, int count) where T : struct, IVertexData { // Require double precision, so we don't get "z fighting" issues in our sort. double zSortIndex = 0.0d; for (int i = 0; i < count; i++) { zSortIndex += vertices[offset + i].Pos.Z; } return (float)(zSortIndex / (double)count); } private void UpdateMatrices() { this.UpdateViewMatrix(); this.UpdateProjectionMatrix(); this.matFinal = this.matView * this.matProjection; Matrix4.Invert(ref this.matFinal, out this.matFinalInv); } private void UpdateViewMatrix() { this.matView = Matrix4.Identity; if (this.projection != ProjectionMode.Screen) { // Translate opposite to camera position this.matView *= Matrix4.CreateTranslation(-this.viewerPos); // Rotate opposite to camera angle this.matView *= Matrix4.CreateRotationZ(-this.viewerAngle); } } private void UpdateProjectionMatrix() { Rect targetRect = new Rect(this.targetSize); // Flip Z direction from "out of the screen" to "into the screen". Matrix4 flipZDir; Matrix4.CreateScale(1.0f, 1.0f, -1.0f, out flipZDir); if (this.projection == ProjectionMode.Screen) { // When rendering in screen space, all reasonable positive depth should be valid, // so we'll ignore any of the projection specific near and far plane settings. Matrix4.CreateOrthographicOffCenter( targetRect.X, targetRect.X + targetRect.W, targetRect.Y + targetRect.H, targetRect.Y, // These values give us a linear depth precision of ~0.006 at 24 bit 0.0f, 100000.0f, out this.matProjection); this.matProjection = flipZDir * this.matProjection; } else if (this.projection == ProjectionMode.Orthographic) { Matrix4.CreateOrthographicOffCenter( targetRect.X - targetRect.W * 0.5f, targetRect.X + targetRect.W * 0.5f, targetRect.Y + targetRect.H * 0.5f, targetRect.Y - targetRect.H * 0.5f, this.nearZ, this.farZ, out this.matProjection); // In non-perspective projection, we'll use FocusDist for scaling Matrix4 scaleByFocusDist; Matrix4.CreateScale( this.focusDist / DefaultFocusDist, this.focusDist / DefaultFocusDist, 1.0f, out scaleByFocusDist); this.matProjection = scaleByFocusDist * flipZDir * this.matProjection; } else { // Clamp near plane to above-zero, so we avoid division by zero problems float clampedNear = MathF.Max(this.nearZ, 1.0f); Matrix4.CreatePerspectiveOffCenter( targetRect.X - targetRect.W * 0.5f, targetRect.X + targetRect.W * 0.5f, targetRect.Y + targetRect.H * 0.5f, targetRect.Y - targetRect.H * 0.5f, clampedNear, this.farZ, out this.matProjection); this.matProjection = flipZDir * this.matProjection; // Apply custom "focus distance", where objects appear at 1:1 scale. // Otherwise, that distance would be the near plane. this.matProjection.M33 *= clampedNear / this.focusDist; // Output Z scale this.matProjection.M43 *= clampedNear / this.focusDist; // Output Z offset this.matProjection.M34 *= clampedNear / this.focusDist; // Perspective divide scale } } /// <summary> /// Updates all <see cref="BuiltinShaderFields"/> in the devices shared <see cref="ShaderParameters"/> /// to match its current configuration. /// </summary> private void UpdateBuiltinShaderParameters() { this.shaderParameters.Set(BuiltinShaderFields.RealTime, (float)Time.MainTimer.TotalSeconds); this.shaderParameters.Set(BuiltinShaderFields.GameTime, (float)Time.GameTimer.TotalSeconds); this.shaderParameters.Set(BuiltinShaderFields.DeltaTime, Time.DeltaTime); this.shaderParameters.Set(BuiltinShaderFields.FrameCount, Time.FrameCount); this.shaderParameters.Set(BuiltinShaderFields.CameraPosition, this.viewerPos); this.shaderParameters.Set(BuiltinShaderFields.CameraIsPerspective, this.projection == ProjectionMode.Perspective); this.shaderParameters.Set(BuiltinShaderFields.CameraFocusDist, this.focusDist); this.shaderParameters.Set(BuiltinShaderFields.ViewSize, this.targetSize); } /// <summary> /// Uploads all dynamically gathered vertex data to the GPU using the internal <see cref="vertexBuffers"/> pool. /// </summary> private void UploadVertexData() { // Note that there is a 1:1 mapping between gathered vertex batches and vertex buffers. // We'll keep all buffers around until the drawdevice is disposed, in case we might need // them again later. this.vertexBuffers.Count = Math.Max(this.vertexBuffers.Count, this.drawVertices.TypeIndexCount); for (int typeIndex = 0; typeIndex < this.drawVertices.TypeIndexCount; typeIndex++) { // Filter out unused vertex types IReadOnlyList<IVertexBatch> batches = this.drawVertices.GetBatches(typeIndex); if (batches == null) continue; if (batches.Count == 0) continue; // Upload all vertex batches for this vertex type if (this.vertexBuffers[typeIndex] == null) this.vertexBuffers[typeIndex] = new RawList<VertexBuffer>(); this.vertexBuffers[typeIndex].Count = Math.Max(this.vertexBuffers[typeIndex].Count, batches.Count); for (int batchIndex = 0; batchIndex < batches.Count; batchIndex++) { IVertexBatch vertexBatch = batches[batchIndex]; // Generate a VertexBuffer for this vertex type and batch index, if it didn't exist yet if (this.vertexBuffers[typeIndex][batchIndex] == null) this.vertexBuffers[typeIndex][batchIndex] = new VertexBuffer(); // Upload the vertex batch to using (PinnedArrayHandle pinned = vertexBatch.Lock()) { this.vertexBuffers[typeIndex][batchIndex].LoadVertexData( vertexBatch.Declaration, pinned.Address, vertexBatch.Count); } } } } private static int MaterialSortComparison(SortItem first, SortItem second) { return first.SortIndex - second.SortIndex; } private static int DepthSortComparison(SortItem first, SortItem second) { if (second.SortDepth < first.SortDepth) return -1; if (second.SortDepth > first.SortDepth) return 1; if (second.SortDepth == first.SortDepth) return 0; if (float.IsNaN(second.SortDepth)) return (float.IsNaN(first.SortDepth) ? 0 : -1); else return 1; } private void AggregateBatches() { // Material-sorted (solid) batches if (this.sortBufferSolid.Count > 0) { // Assign material and vertex type based sort indices to each item this.AssignMaterialSortIDs(this.sortBufferSolid, this.drawBuffer); // Stable sort assures maintaining draw order for batches of equal material this.sortBufferTemp.Count = this.sortBufferSolid.Count; this.sortBufferSolid.StableSort(this.sortBufferTemp, MaterialSortComparison); this.sortBufferTemp.Clear(); // Sweep over the sorted draws and aggregate as many as possible into a single batch this.AggregateBatches(this.sortBufferSolid, this.drawBuffer, this.batchBufferSolid); } // Depth-sorted (blended) batches if (this.sortBufferBlended.Count > 0) { // Stable sort assures maintaining draw order for batches of equal depth this.sortBufferTemp.Count = this.sortBufferBlended.Count; this.sortBufferBlended.StableSort(this.sortBufferTemp, DepthSortComparison); this.sortBufferTemp.Clear(); // Sweep over the sorted draws and aggregate as many as possible into a single batch this.AggregateBatches(this.sortBufferBlended, this.drawBuffer, this.batchBufferBlended); } this.numRawBatches = 0; } private void AssignMaterialSortIDs(RawList<SortItem> sortItems, RawList<VertexDrawItem> drawItems) { VertexDrawItem[] drawData = drawItems.Data; SortItem[] sortData = sortItems.Data; int count = sortItems.Count; for (int i = 0; i < sortData.Length; i++) { if (i >= count) break; int drawIndex = sortData[i].DrawItemIndex; int vertexTypeIndex = drawData[drawIndex].TypeIndex; VertexMode vertexMode = drawData[drawIndex].Mode; BatchInfo material = drawData[drawIndex].Material; int matHash; unchecked { // Avoid just "cutting off" parts of the original hash, // as this is likely to lead to collisions. matHash = material.GetHashCode(); matHash = (13 * matHash + 17 * (matHash >> 9)) % (1 << 23); } // Bit significance is used to achieve sorting by multiple traits at once. // The higher a traits bit significance, the higher its priority when sorting. sortData[i].SortIndex = (((int)vertexMode & 15) << 0) | // XXXX 4 Bit Vertex Mode Offset 4 ((matHash & 8388607) << 4) | // XXXXXXXXXXXXXXXXXXXXXXXaaaa 23 Bit Material Offset 27 ((vertexTypeIndex & 15) << 27); // XXXbbbbbbbbbbbbbbbbbbbbbbbaaaa 4 Bit Vertex Type Offset 31 } } private void AggregateBatches(RawList<SortItem> sortItems, RawList<VertexDrawItem> drawItems, RawList<DrawBatch> batches) { VertexDrawItem[] drawData = drawItems.Data; SortItem[] sortData = sortItems.Data; SortItem activeSortItem = sortData[0]; VertexDrawItem activeItem = drawData[activeSortItem.DrawItemIndex]; int beginBatchIndex = 0; // Find sequences of draw items that can be batched together int count = sortItems.Count; for (int sortIndex = 1; sortIndex <= count; sortIndex++) { // Skip items until we can no longer put the next one into the same batch if (sortIndex < count) { SortItem sortItem = sortData[sortIndex]; if (activeItem.CanShareBatchWith(ref drawData[sortItem.DrawItemIndex])) continue; } // Create a batch for all previous items VertexBuffer vertexBuffer = this.vertexBuffers[activeItem.TypeIndex][activeItem.BufferIndex]; DrawBatch batch = new DrawBatch( vertexBuffer, this.batchIndexPool.Rent(sortIndex - beginBatchIndex), activeItem.Mode, activeItem.Material); for (int i = beginBatchIndex; i < sortIndex; i++) { batch.VertexRanges.Add(new VertexDrawRange { Index = drawData[sortData[i].DrawItemIndex].Offset, Count = drawData[sortData[i].DrawItemIndex].Count }); } batches.Add(batch); // Proceed with the current item being the new sharing reference if (sortIndex < count) { beginBatchIndex = sortIndex; activeSortItem = sortData[sortIndex]; activeItem = drawData[activeSortItem.DrawItemIndex]; } } } public static void RenderVoid(Rect viewportRect) { RenderVoid(viewportRect, ColorRgba.TransparentBlack); } public static void RenderVoid(Rect viewportRect, ColorRgba color) { if (DualityApp.GraphicsBackend == null) return; RenderOptions options = new RenderOptions { ClearFlags = ClearFlag.All, ClearColor = color, ClearDepth = 1.0f, Viewport = viewportRect }; DualityApp.GraphicsBackend.BeginRendering(null, options); DualityApp.GraphicsBackend.EndRendering(); } } }
deathkiller/jazz2
Shared/Duality/Drawing/DrawDevice.cs
C#
gpl-3.0
34,706
/* * Synopsys AXS10X SDP I2S PLL clock driver * * Copyright (C) 2016 Synopsys * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/platform_device.h> #include <linux/module.h> #include <linux/clk-provider.h> #include <linux/err.h> #include <linux/device.h> #include <linux/of_address.h> #include <linux/slab.h> #include <linux/of.h> /* PLL registers addresses */ #define PLL_IDIV_REG 0x0 #define PLL_FBDIV_REG 0x4 #define PLL_ODIV0_REG 0x8 #define PLL_ODIV1_REG 0xC struct i2s_pll_cfg { unsigned int rate; unsigned int idiv; unsigned int fbdiv; unsigned int odiv0; unsigned int odiv1; }; static const struct i2s_pll_cfg i2s_pll_cfg_27m[] = { /* 27 Mhz */ { 1024000, 0x104, 0x451, 0x10E38, 0x2000 }, { 1411200, 0x104, 0x596, 0x10D35, 0x2000 }, { 1536000, 0x208, 0xA28, 0x10B2C, 0x2000 }, { 2048000, 0x82, 0x451, 0x10E38, 0x2000 }, { 2822400, 0x82, 0x596, 0x10D35, 0x2000 }, { 3072000, 0x104, 0xA28, 0x10B2C, 0x2000 }, { 2116800, 0x82, 0x3CF, 0x10C30, 0x2000 }, { 2304000, 0x104, 0x79E, 0x10B2C, 0x2000 }, { 0, 0, 0, 0, 0 }, }; static const struct i2s_pll_cfg i2s_pll_cfg_28m[] = { /* 28.224 Mhz */ { 1024000, 0x82, 0x105, 0x107DF, 0x2000 }, { 1411200, 0x28A, 0x1, 0x10001, 0x2000 }, { 1536000, 0xA28, 0x187, 0x10042, 0x2000 }, { 2048000, 0x41, 0x105, 0x107DF, 0x2000 }, { 2822400, 0x145, 0x1, 0x10001, 0x2000 }, { 3072000, 0x514, 0x187, 0x10042, 0x2000 }, { 2116800, 0x514, 0x42, 0x10001, 0x2000 }, { 2304000, 0x619, 0x82, 0x10001, 0x2000 }, { 0, 0, 0, 0, 0 }, }; struct i2s_pll_clk { void __iomem *base; struct clk_hw hw; struct device *dev; }; static inline void i2s_pll_write(struct i2s_pll_clk *clk, unsigned int reg, unsigned int val) { writel_relaxed(val, clk->base + reg); } static inline unsigned int i2s_pll_read(struct i2s_pll_clk *clk, unsigned int reg) { return readl_relaxed(clk->base + reg); } static inline struct i2s_pll_clk *to_i2s_pll_clk(struct clk_hw *hw) { return container_of(hw, struct i2s_pll_clk, hw); } static inline unsigned int i2s_pll_get_value(unsigned int val) { return (val & 0x3F) + ((val >> 6) & 0x3F); } static const struct i2s_pll_cfg *i2s_pll_get_cfg(unsigned long prate) { switch (prate) { case 27000000: return i2s_pll_cfg_27m; case 28224000: return i2s_pll_cfg_28m; default: return NULL; } } static unsigned long i2s_pll_recalc_rate(struct clk_hw *hw, unsigned long parent_rate) { struct i2s_pll_clk *clk = to_i2s_pll_clk(hw); unsigned int idiv, fbdiv, odiv; idiv = i2s_pll_get_value(i2s_pll_read(clk, PLL_IDIV_REG)); fbdiv = i2s_pll_get_value(i2s_pll_read(clk, PLL_FBDIV_REG)); odiv = i2s_pll_get_value(i2s_pll_read(clk, PLL_ODIV0_REG)); return ((parent_rate / idiv) * fbdiv) / odiv; } static long i2s_pll_round_rate(struct clk_hw *hw, unsigned long rate, unsigned long *prate) { struct i2s_pll_clk *clk = to_i2s_pll_clk(hw); const struct i2s_pll_cfg *pll_cfg = i2s_pll_get_cfg(*prate); int i; if (!pll_cfg) { dev_err(clk->dev, "invalid parent rate=%ld\n", *prate); return -EINVAL; } for (i = 0; pll_cfg[i].rate != 0; i++) if (pll_cfg[i].rate == rate) { return rate; } return -EINVAL; } static int i2s_pll_set_rate(struct clk_hw *hw, unsigned long rate, unsigned long parent_rate) { struct i2s_pll_clk *clk = to_i2s_pll_clk(hw); const struct i2s_pll_cfg *pll_cfg = i2s_pll_get_cfg(parent_rate); int i; if (!pll_cfg) { dev_err(clk->dev, "invalid parent rate=%ld\n", parent_rate); return -EINVAL; } for (i = 0; pll_cfg[i].rate != 0; i++) { if (pll_cfg[i].rate == rate) { i2s_pll_write(clk, PLL_IDIV_REG, pll_cfg[i].idiv); i2s_pll_write(clk, PLL_FBDIV_REG, pll_cfg[i].fbdiv); i2s_pll_write(clk, PLL_ODIV0_REG, pll_cfg[i].odiv0); i2s_pll_write(clk, PLL_ODIV1_REG, pll_cfg[i].odiv1); return 0; } } dev_err(clk->dev, "invalid rate=%ld, parent_rate=%ld\n", rate, parent_rate); return -EINVAL; } static const struct clk_ops i2s_pll_ops = { .recalc_rate = i2s_pll_recalc_rate, .round_rate = i2s_pll_round_rate, .set_rate = i2s_pll_set_rate, }; static int i2s_pll_clk_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *node = dev->of_node; const char *clk_name; const char *parent_name; struct clk *clk; struct i2s_pll_clk *pll_clk; struct clk_init_data init; struct resource *mem; pll_clk = devm_kzalloc(dev, sizeof(*pll_clk), GFP_KERNEL); if (!pll_clk) { return -ENOMEM; } mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); pll_clk->base = devm_ioremap_resource(dev, mem); if (IS_ERR(pll_clk->base)) { return PTR_ERR(pll_clk->base); } clk_name = node->name; init.name = clk_name; init.ops = &i2s_pll_ops; parent_name = of_clk_get_parent_name(node, 0); init.parent_names = &parent_name; init.num_parents = 1; pll_clk->hw.init = &init; pll_clk->dev = dev; clk = devm_clk_register(dev, &pll_clk->hw); if (IS_ERR(clk)) { dev_err(dev, "failed to register %s clock (%ld)\n", clk_name, PTR_ERR(clk)); return PTR_ERR(clk); } return of_clk_add_provider(node, of_clk_src_simple_get, clk); } static int i2s_pll_clk_remove(struct platform_device *pdev) { of_clk_del_provider(pdev->dev.of_node); return 0; } static const struct of_device_id i2s_pll_clk_id[] = { { .compatible = "snps,axs10x-i2s-pll-clock", }, { }, }; MODULE_DEVICE_TABLE(of, i2s_pll_clk_id); static struct platform_driver i2s_pll_clk_driver = { .driver = { .name = "axs10x-i2s-pll-clock", .of_match_table = i2s_pll_clk_id, }, .probe = i2s_pll_clk_probe, .remove = i2s_pll_clk_remove, }; module_platform_driver(i2s_pll_clk_driver); MODULE_AUTHOR("Jose Abreu <joabreu@synopsys.com>"); MODULE_DESCRIPTION("Synopsys AXS10X SDP I2S PLL Clock Driver"); MODULE_LICENSE("GPL v2");
williamfdevine/PrettyLinux
drivers/clk/axs10x/i2s_pll_clock.c
C
gpl-3.0
5,911
package nl.mpi.metadatabrowser.wicket; import java.io.Serializable; import java.util.Collection; import java.util.Collections; /** * * @author Twan Goosen <twan.goosen@mpi.nl> */ public class HighlightSearchTermScriptFactory implements Serializable { public static final String HIGHLIGHT_FUNCTION = "$('%s').highlight(%s, {className:'%s', wordsOnly: %s})"; public static final Collection<String> DEFAULT_EXCLUDE_WORDS = Collections.emptySet(); //ImmutableSet.of("and", "or", "not", "to"); public static final String DEFAULT_CSS_CLASS = "searchword"; public String createScript(String componentSelector, final String words) { return createScript(componentSelector, words, DEFAULT_CSS_CLASS); } public String createScript(String componentSelector, final String words, String cssClass) { return String.format(HIGHLIGHT_FUNCTION, componentSelector, makeWordListArray(words), cssClass, matchWordsOnly(words) ); } protected boolean matchWordsOnly(String query) { // string with asterixes or question marks should match by character return !query.matches(".*[\\*\\?].*"); } /** * * @param wordList string of whitespace separated words * @return a string representing a sanitised javascript array of words */ private CharSequence makeWordListArray(String wordList) { final StringBuilder sb = new StringBuilder("["); final String[] words = wordList.split("\\s"); for (int i = 0; i < words.length; i++) { final String word = sanitise(words[i]); //remove white space and quotes at beginning or end // is on exclude list? if (!getExcludeWords().contains(word.toLowerCase())) { // wrap in quotes sb.append("'").append(word).append("'"); if (i + 1 < words.length) { // prepare to append next sb.append(","); } } } return sb.append("]"); } private String sanitise(String word) { //remove everything up to first colon and strip off quotation marks and white space return word.replaceAll( //match beginning "^(" //case with colon (also strip quotes + optional whitespace after quotes) + "[^:\"']+:(['\"])?" //or case without colon (strip quotes and white space) + "|['\"]+" + ")" //match end + "|(" //quotes + "['\"]+" //or boosting values + "|['\"]?\\^.*" + ")$|[\\?\\*]", //replace with empty string ""); } /** * * @return Words not to highlight */ protected Collection<String> getExcludeWords() { return DEFAULT_EXCLUDE_WORDS; } }
TheLanguageArchive/ASV
metadata-browser-pages/src/main/java/nl/mpi/metadatabrowser/wicket/HighlightSearchTermScriptFactory.java
Java
gpl-3.0
3,027
#include "Functions.h" #include "LevelInfoRender.h" LevelInfoRender::LevelInfoRender(ImageManager &imageManager, SDL_Renderer &renderer, const std::string& dataPath, TTF_Font &font, SDL_Color textColor) { playButton=imageManager.loadTexture(dataPath+"gfx/playbutton.png",renderer); timeIcon=imageManager.loadTexture(dataPath+"gfx/time.png",renderer); recordingsIcon=imageManager.loadTexture(dataPath+"gfx/recordings.png",renderer); //Skip doing this here as it will be called LevelPlaySelect::refresh which is called by it's constructor anyhow. //resetText(renderer, font, textColor); } void LevelInfoRender::resetText(SDL_Renderer &renderer, TTF_Font &font, SDL_Color textColor) { auto tex = [&](const char* text){ return textureFromText(renderer,font,text,textColor); }; levelDescription=tex(_("Choose a level")); timeText=tex(_("Time:")); recordingsText=tex(_("Recordings:")); levelTime=tex("- / -"); levelRecs=tex("- / -"); } void LevelInfoRender::update(SDL_Renderer &renderer, TTF_Font &font, SDL_Color textColor, const std::string &description, const std::string& time, const std::string& recordings) { auto tex = [&](const std::string& text){ return textureFromText(renderer,font,text.c_str(),textColor); }; if(description.empty()) { levelDescription=nullptr; } else { levelDescription=tex(description); } levelTime=tex(time); levelRecs=tex(recordings); } void LevelInfoRender::render(SDL_Renderer &renderer) { //Avoid crashing if this is somehow not initialized. if(!timeText) { return; } int w=0,h=0; SDL_GetRendererOutputSize(&renderer,&w,&h); if(levelDescription) { applyTexture(100,h-130+(50-textureHeight(*levelDescription))/2,levelDescription, renderer); } //Draw time the icon. applyTexture(w-405,h-130+3,timeIcon,renderer); //Now draw the text (title). applyTexture(w-380,h-130+3,timeText,renderer); //Now draw the second text (value). applyTexture(w-textureWidth(*levelTime)-80,h-130+3,levelTime,renderer); //Draw the icon. applyTexture(w-405,h-98+(6)/2,recordingsIcon,renderer); //Now draw the text (title). applyTexture(w-380,h-98+(32-textureHeight(*recordingsText))/2, recordingsText,renderer); //Now draw the second text (value). applyTexture(w-textureWidth(*levelRecs)-80,h-98+(30-textureHeight(*levelRecs))/2,levelRecs,renderer); }
oyvindln/meandmyshadow
src/LevelInfoRender.cpp
C++
gpl-3.0
2,549
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace VideoChatClient { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
RahulCh1/VideoChatClient
VideoChatClient/VideoChatClient/Program.cs
C#
gpl-3.0
516
/* * Copyright (c) 2014 aleon GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Note for all commercial users of this library: * Please contact the EnOcean Alliance (http://www.enocean-alliance.org/) * about a possible requirement to become member of the alliance to use the * EnOcean protocol implementations. * * Contributors: * Markus Rathgeb - initial API and implementation and/or initial documentation */ package eu.aleon.aleoncean.packet.radio.userdata.eepd201; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Markus Rathgeb {@literal <maggu2810@gmail.com>} */ public enum ErrorLevel { ERROR_LEVEL_0_HARDWARE_OK((byte) 0), ERROR_LEVEL_1_HARDWARE_WARNING((byte) 1), ERROR_LEVEL_2_HARDWARE_FAILURE((byte) 2), ERROR_LEVEL_NOT_SUPPORTED((byte) 3); private final byte value; private static final Logger LOGGER = LoggerFactory.getLogger(ErrorLevel.class); public static ErrorLevel fromByte(final byte value) { switch (value) { case 0: return ErrorLevel.ERROR_LEVEL_0_HARDWARE_OK; case 1: return ErrorLevel.ERROR_LEVEL_1_HARDWARE_WARNING; case 2: return ErrorLevel.ERROR_LEVEL_2_HARDWARE_FAILURE; case 3: return ErrorLevel.ERROR_LEVEL_NOT_SUPPORTED; default: LOGGER.warn("Invalid ErrorLevel: {}", value); return ErrorLevel.ERROR_LEVEL_NOT_SUPPORTED; } } private ErrorLevel(final byte value) { this.value = value; } public byte toByte() { return value; } }
kevoree/kubi
plugins/enocean/org.kubi.driver.enocean/src/main/java/eu/aleon/aleoncean/packet/radio/userdata/eepd201/ErrorLevel.java
Java
gpl-3.0
1,848
/** * @author mpm1 * * Requires jQuery */ function CwrcAnnotion(url, jq){ if (!jq) { jq = $; } // Public Functions this.searchAnnotion = function(searchObject){ // TODO: Should we search on annotations? } this.getAnnotaion = function(pid){ var result = result; jq.ajax({ url : url + '/annotation/' + pid, type : 'GET', async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); return result; } this.newAnnotation = function(data) { var result = result; jq.ajax({ url : url + '/annotation', type : 'POST', data : { method : 'post', data: data }, async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); return jq.parseJSON(result); } this.modifyAnnotation = function(pid, data) { var result = result; jq.ajax({ url : url + '/annotation/' + pid, type : 'POST', data : { method : 'put', data: data }, async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); return jq.parseJSON(result); } this.deleteAnnotation = function(pid) { var result = result; jq.ajax({ url : url + '/annotation/' + pid, type : 'POST', async : false, data: { method: 'delete' }, success : function(data) { result = data; }, error : function(error) { result = error; } }); return jq.parseJSON(result); } } function CwrcEntity(type, url, jq) { if (!jq) { jq = $; } // Public Functions this.searchEntity = function(searchObject){ var limit = searchObject.limit !== undefined ? searchObject.limit : 100; var page = searchObject.page !== undefined ? searchObject.page : 0; var restrictions = searchObject.restrictions !== undefined ? searchObject.restrictions : []; return jq.ajax({ url : url + '/' + type + "/search", type : 'GET', async : true, data: { query: searchObject.query, limit: limit, page: page, restrictions: restrictions }, success : function(data) { result = data === "" ? {} : JSON.parse(data); searchObject.success(result); }, error : function(error) { searchObject.error(error); } }); } this.getEntity = function(pid) { var result = result; jq.ajax({ url : url + '/' + type + "/" + pid, type : 'GET', async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); return result; } this.newEntity = function(data) { var result = result; jq.ajax({ url : url + '/' + type, type : 'POST', data : { method : 'post', data: data }, async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); return jq.parseJSON(result); } this.modifyEntity = function(pid, data) { var result = result; jq.ajax({ url : url + '/' + type + '/' + pid, type : 'POST', data : { method : 'put', data: data }, async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); return jq.parseJSON(result); } this.deleteEntity = function(pid) { var result = result; jq.ajax({ url : url + '/' + type + "/" + pid, type : 'POST', async : false, data: { method: 'delete' }, success : function(data) { result = data; }, error : function(error) { result = error; } }); return jq.parseJSON(result); } this.listEntity = function(totalPerPage, page){ alert("Page " + page); } } function CwrcApi(url, jq) { if (!jq) { jq = $; } // Class creation if (!url.indexOf("/", this.length - 1) !== -1) { url = url + "/"; } // Private variables var _this = this; // Public variables this.person = new CwrcEntity('person', url, jq); this.organization = new CwrcEntity('organization', url, jq); this.title = new CwrcEntity('title', url, jq); //this.event = new CwrcEntity('event', url, jq); <- Can we use event or is that a javascript keyword? this.place = new CwrcEntity('place', url, jq); this.annotation = new CwrcAnnotion(url, jq); this.isInitialized = false; // Private functions this.updateIsInitialized = function(){ jq.ajax({ url : url + "is_initialized", type : 'POST', data : { name : name }, success : function(data) { _this.isInitialized = JSON.parse(data).result; }, error : function(error) { result = error; _this.isInitialized = false; } }); } // Public functions /** * Initialize the data using a set of existing cookies. * var name The cookie to obtaine the information from */ this.initializeWithCookieData = function(data) { var result = result; jq.ajax({ url : url + "initialize_cookie", type : 'POST', async : false, data : { data: data }, success : function(data) { result = data; _this.isInitialized = true; }, error : function(error) { result = error; } }); return result; } this.initializeWithLogin = function(username, password) { var result = result; jq.ajax({ url : url + "initialize_user", type : 'POST', async : false, data : { username : username, password : password }, success : function(data) { result = data; _this.isInitialized = true; }, error : function(error) { result = error; } }); return result; } this.logout = function() { var result = result; if (!_this.isInitialized()) { jq.ajax({ url : url + "logout", type : 'POST', async : false, success : function(data) { result = data; }, error : function(error) { result = error; } }); } _this.isInitialized = false; return result; } this.updateIsInitialized(); return this; }
cwrc/CWRC-ccm-rest-api
scripts/cwrc-api.js
JavaScript
gpl-3.0
5,969
// // Created by Lorenzo Nuti and Paolo Valcepina on 11/07/17. // #ifndef CATULA_BADGESTARSKULL_H #define CATULA_BADGESTARSKULL_H #include "ModelGame.h" #include "MainCharacter.h" #include "Badge.h" class BadgeStarSkull : public Badge { public: BadgeStarSkull(const std::string &className, const std::string &name, const std::string &description, float goal, bool memorize); virtual void update() override; virtual void detach() override; private: virtual void attach() override; int previousScore; }; #endif //CATULA_BADGESTARSKULL_H
walnut42/Catula
BadgeStarSkull.h
C
gpl-3.0
584
# baidu.sh --- # # Filename: baidu.sh # Description: a parser fo weathercatch # Author: Xu FaSheng # Created: 2012.11.06 # Keywords: weathercatch parser baidu # This file is a part of weathercatch # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3, 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; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth # Floor, Boston, MA 02110-1301, USA. # # # Code: parser_name="baidu" default_arg="天气" debug "parser_name: $parser_name" update_weather_data () { if [ ! "$arg" ]; then arg="$default_arg"; fi URL="www.baidu.com/s?wd=$arg" URL=`convert_url_space "$URL"` # dump web page debug "dumping url: $URL" web_content=`retry_cmd 3 timeout_cmd 15s w3m -dump -no-cookie "$URL"` if [ -n "$web_content" ]; then echo "$web_content">$weather_tmp_file parse_data fi } parse_data () { # get valid AQI info section in the page aqi_block=`get_section_file $weather_tmp_file "空气质量指数" "空气质量细分数据"` debug_lines "AQI block:" "$aqi_block" # get AQI value # remove first line and empty lines aqi_block=`echo "$aqi_block" | sed -e '1d' -e '/^$/d'` AQI=`echo "$aqi_block" | head -1 | sed 's/^\([0-9]\+\)$/\1/'` # get AQI description AQID=`echo "$aqi_block" | head -2 | tail -1` # get AQI tips AQIT=`echo "$aqi_block" | grep '温馨提示' | sed 's/温馨提示:\(.*\)。/\1/'` # get valid weather info section in the page weather_block=`get_section_file $weather_tmp_file "一周天气预报" "中国气象局"` debug_lines "weather block:" "$weather_block" # get location name LN=`echo "$weather_block" | head -1 | sed 's/天气预报.*$//'` # get other weather data weather_block=`echo "$weather_block" | sed -e '1d' -e '$d' | awk 'NF>1'` weather_block=`clear_w3m_target_block "$weather_block" "[neverfill]"` weather_block=`clear_w3m_target_block "$weather_block" "[u]"` debug_lines "weather block[fixed]" "$weather_block" weather_block=`reverse_table "$weather_block"` i=0 while read line; do debug "future_day_$i" set_data_type "LN" $LN # temperature temp_data=`echo $line | awk '{print $2}'` temp_left=`echo $temp_data | awk -F~ '{print $1}' | sed 's/\(-\?[0-9]\+\).*/\1/'` temp_right=`echo $temp_data | awk -F~ '{print $2}' | sed 's/\(-\?[0-9]\+\).*/\1/'` # there is only low temp in tonight if [ -n $temp_right ]; then HT=$temp_left LT=$temp_right else HT= LT=$temp_left fi set_data_type "LT" $LT set_data_type "HT" $HT # weather text WT=`echo $line | awk '{print $3}'` set_data_type "WT" $WT # weather font WF=`general_weather_text2font_cn "$WT"` set_data_type "WF" $WF # wind speed text WST=`echo $line | awk '{print $4}'` set_data_type "WST" $WST # AQI info only exists today if [ $i -eq 0 ]; then set_data_type "AQI" $AQI set_data_type "AQID" $AQID set_data_type "AQIT" $AQIT fi write_data_types $i i=$(($i+1)) done <<< "$weather_block" } parser_help () { cat <<EOF Homepage: www.baidu.com Argument meaning: The keyword to search which results will own weather info you expect, in fact, it just could be a city name. [default: "$default_arg"] Support data types: WF: weather font output [effect by --night-mode] WT: weather text LT: low temperature [default unit: celsius] [effect by --temp-unit] HT: high temperature [default unit: celsius] [effect by --temp-unit] WST: wind speed text LN: location name AQI: AQI(air quality index) value AQID:AQI description AQIT:AQI tips Support max future days: 2 Depends: w3m v0.5.3+ Compatibility: works well on weathercatch_v0.2 May work on older versions but this is not guaranteed. Limits: Should only work for Chinese friends. EOF } parser_version () { echo "build 20130411" } debug "parser load success" # # baidu.sh ends here
fasheng/weathercatch
parser/baidu.sh
Shell
gpl-3.0
4,750
<?php /** * Licensed under The GPL-3.0 License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @since 2.0.0 * @author Christopher Castro <chris@quickapps.es> * @link http://www.quickappscms.org * @license http://opensource.org/licenses/gpl-3.0.html GPL-3.0 License */ namespace Content\Model\Entity; use Cake\ORM\Entity; /** * Represents a single "content_revision" within "content_revisions" table. * */ class ContentRevision extends Entity { }
quickapps/cms
plugins/Content/src/Model/Entity/ContentRevision.php
PHP
gpl-3.0
566
Imports System.Web Imports System.Web.Mvc Public Class FilterConfig Public Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection) filters.Add(New HandleCustomErrorAttribute With {.View = "Uups"}) End Sub End Class
kristofzerbe/OpenAntrag
OpenAntrag/App_Start/FilterConfig.vb
Visual Basic
gpl-3.0
256
/*** * Copyright (c) 2008, Endless Loop Software, Inc. * * This file is part of EgoNet. * * EgoNet is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * EgoNet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.egonet.gui.author; import javax.swing.JPanel; import org.egonet.model.Shared.QuestionType; public abstract class EgoQPanel extends JPanel { protected final QuestionType questionType; abstract public void fillPanel(); abstract public void clearPanel(); public EgoQPanel(QuestionType questionType) { this.questionType = questionType; } }
egonet/egonet
src/main/java/org/egonet/gui/author/EgoQPanel.java
Java
gpl-3.0
1,098
Champu_N_Chaandni is a PC Game in which worms size increase on eating food. Copyright (C) 2014 Vivek Mangla Champu_N_Chaandni is free Game: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Champu_N_Chaandni ================= A MultiPlayer Portable Computer Worm Game. A maximum of 2 Players can play on same Keyboard. 6 different Levels, 2 types of Chaandni's Pos. Download source code. Extract it and move inside directory on cmd. Now Type::<br> javac *.java java MainFrame
vivekFuneesh/Champu_N_Chaandni
README.md
Markdown
gpl-3.0
1,070