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
<!-- enter pwd reset code --> <p><span class="errorMessage"><?=$error_message?></span></p> <h3>Recover Password</h3> <p>Please enter the 10 character reset code we emailed to you.</p> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> <table border="0"> <tr> <td>Reset Code</td> <td> <input type="text" name="reset-code" maxlength="10"> </td> </tr> <tr> <td colspan=2 class="form_buttons"> <input type="submit" name="submit-code" value="Submit Code"> </td> </tr> </table> </form>
pietrosperoni/Vilfredo
recover__enter_reset_code_from_link_form.php
PHP
agpl-3.0
535
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH package ims.hl7.domain.mapping; import org.apache.log4j.Logger; import ims.core.vo.Patient; import ims.core.vo.TaxonomyMap; import ims.core.vo.ifInpatientEpisodeVo; import ims.domain.exceptions.StaleObjectException; import ims.framework.utils.DateTimeFormat; import ims.hl7.domain.EventResponse; import ims.hl7.domain.HL7EngineApplication; import ims.hl7.utils.EvnCodes; import ims.hl7.utils.HL7Errors; import ims.hl7.utils.HL7Utils; import ims.ocrr.vo.ProviderSystemVo; import ims.ocs_if.vo.InpatientEpisodeQueueVo; import ims.vo.interfaces.IHL7OutboundMessageHandler; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.model.v24.message.ADT_A21; import ca.uhn.hl7v2.model.v24.segment.PD1; import ca.uhn.hl7v2.model.v24.segment.PID; import ca.uhn.hl7v2.model.v24.segment.PV1; import ca.uhn.hl7v2.model.v24.segment.PV2; public class A26VoMapper extends VoMapper { // This event is called when a send on leave event A21 is cancelled, i.e. the patient // is no longer on leave! private static final Logger LOG = Logger.getLogger(A26VoMapper.class); private A01VoMapper a01Vomapper; public Message populateMessage() { // Not required for inbound messages return null; } public Message populateMessage(IHL7OutboundMessageHandler event) throws Exception { LOG.debug("A26VoMapper populateMessage: entry"); ADT_A21 message = new ADT_A21(); PV1 pv1 = message.getPV1(); PV2 pv2 = message.getPV2(); Patient patient=null; //WDEV-22429 populateMSH(event.getProviderSystem(), message.getMSH(), Long.toString( new java.util.Date().getTime()), "ADT", "A26"); message.getEVN().getEventTypeCode().setValue("A26"); if (event instanceof InpatientEpisodeQueueVo) { a01Vomapper = (A01VoMapper)HL7EngineApplication.getVoMapper(EvnCodes.A01); if(a01Vomapper==null) { throw new HL7Exception("A26 mapper requires A01 mapper. A01 mapper not found in list of registered mappers."); } InpatientEpisodeQueueVo feedVo = (InpatientEpisodeQueueVo)event; ifInpatientEpisodeVo inpatientEpisode = adt.getInpatientEpisodeDetails(feedVo); patient = inpatientEpisode.getPatient(); a01Vomapper.populateBasicEpisodeData(event, inpatientEpisode, pv1, pv2); if (inpatientEpisode.getPendingTransfer() != null) { // PV2-1 Prior pending location (PL) // PV2-1-1 Point of care (IS) if (inpatientEpisode.getPendingTransfer().getDestinationWard() != null && inpatientEpisode.getPendingTransfer().getDestinationWard().getCodeMappings() != null) { for (int i=0; i<inpatientEpisode.getPendingTransfer().getDestinationWard().getCodeMappings().size(); i++) { TaxonomyMap codeMapping = inpatientEpisode.getPendingTransfer().getDestinationWard().getCodeMappings().get(i); if(codeMapping.getTaxonomyCode() != null && codeMapping.getTaxonomyCode().length() > 0) { pv2.getPriorPendingLocation().getPointOfCare().setValue(codeMapping.getTaxonomyCode().toString()); } } } // PV2-1-4 Facility (HD) if (inpatientEpisode.getPendingTransfer().getDestinationWard().getParentLocation().getCodeMappings() !=null) { for (int i=0; i<inpatientEpisode.getPendingTransfer().getDestinationWard().getParentLocation().getCodeMappings().size(); i++) { TaxonomyMap codeMapping = inpatientEpisode.getPendingTransfer().getDestinationWard().getParentLocation().getCodeMappings().get(i); if (codeMapping.getTaxonomyCode() != null && codeMapping.getTaxonomyCode().length() > 0 && codeMapping.getTaxonomyName() != null && codeMapping.getTaxonomyName().getText().length() > 0 && inpatientEpisode.getPendingTransfer().getDestinationWard().getParentLocation().getName().length() > 0) { pv2.getPriorPendingLocation().getFacility().getNamespaceID().setValue(inpatientEpisode.getPendingTransfer().getDestinationWard().getParentLocation().getName()); pv2.getPriorPendingLocation().getFacility().getUniversalID().setValue(codeMapping.getTaxonomyCode()); pv2.getPriorPendingLocation().getFacility().getUniversalIDType().setValue(codeMapping.getTaxonomyName().toString()); } } } // PV2-1-9 Location description (ST) if (inpatientEpisode.getPendingTransfer().getDestinationWard() != null && inpatientEpisode.getPendingTransfer().getDestinationWard().getName() != null && inpatientEpisode.getPendingTransfer().getDestinationWard().getName().length() > 0) { pv2.getPriorPendingLocation().getLocationDescription().setValue(inpatientEpisode.getPendingTransfer().getDestinationWard().getName()); } // PV2-4 Transfer reason (CE) if (inpatientEpisode.getPendingTransfer().getTransferReason() !=null) { pv2.getTransferReason().getIdentifier().setValue((svc.getRemoteLookup(inpatientEpisode.getPendingTransfer().getTransferReason().getID(), event.getProviderSystem().getCodeSystem().getText()))); } // WDEV-22429 if (inpatientEpisode.getPendingTransfer() != null && inpatientEpisode.getPendingTransfer().getTransferRequestDateTime() != null) { renderDateTimeVoToTS(inpatientEpisode.getPendingTransfer().getTransferRequestDateTime(), message.getEVN().getRecordedDateTime()); } } //WDEV-22918 if (inpatientEpisode.getAdmissionEventDateTimeIsNotNull()) { renderDateTimeVoToTS(inpatientEpisode.getAdmissionEventDateTime(), message.getEVN().getRecordedDateTime()); } //WDEV-22918 } //WDEV-22429 Move to beginning of method // populateMSH(event.getProviderSystem(), message.getMSH(), Long.toString( new java.util.Date().getTime()), "ADT", "A26"); // message.getEVN().getEventTypeCode().setValue("A26"); if (patient != null) { renderPatientVoToPID(patient, message.getPID(), event.getProviderSystem()); PD1 pd1 = message.getPD1(); //WDEV20993 // renderGPDetailsToPD1(patient, pd1); renderGPDetailsToPD1(patient, pd1, event.getProviderSystem()); renderPatientDetailsToPD1(patient, pd1, event.getProviderSystem()); //WDEV-22624 } return message; } @Override //WDEV-2012 // public Message processEvent(Message msg, ProviderSystemVo providerSystem) throws HL7Exception public EventResponse processEvent(Message msg, ProviderSystemVo providerSystem) throws HL7Exception //WDEV-20112 { EventResponse response = new EventResponse(); PID pid = null; pid = (PID) msg.get("PID"); Patient patVo = getPrimaryIdFromPid(pid, providerSystem); try { Patient patVo2 = getDemog().getPatient(patVo); response.setPatient(patVo2); } catch (StaleObjectException e) { response.setMessage(HL7Utils.buildRejAck(msg.get("MSH"), "Exception: " + e.getMessage(), HL7Errors.APP_INT_ERROR, toConfigItemArray(providerSystem.getConfigItems()))); return response; } String eventCode = HL7Utils.getEventCode(msg); response.setMessage(HL7Utils.buildRejAck(msg.get("MSH"), "Exception: Inbound " + eventCode + " events not currently processed by application!", HL7Errors.APP_INT_ERROR, toConfigItemArray(providerSystem.getConfigItems()))); return response; //WDEV-20112 } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/HL7Engine/src/ims/hl7/domain/mapping/A26VoMapper.java
Java
agpl-3.0
9,225
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo.beans; public class OPDGenNotesShortVoBean extends ims.vo.ValueObjectBean { public OPDGenNotesShortVoBean() { } public OPDGenNotesShortVoBean(ims.generalmedical.vo.OPDGenNotesShortVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.carecontext = vo.getCareContext() == null ? null : (ims.core.vo.beans.CareContextShortVoBean)vo.getCareContext().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.OPDGenNotesShortVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.carecontext = vo.getCareContext() == null ? null : (ims.core.vo.beans.CareContextShortVoBean)vo.getCareContext().getBean(map); } public ims.generalmedical.vo.OPDGenNotesShortVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.generalmedical.vo.OPDGenNotesShortVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.OPDGenNotesShortVo vo = null; if(map != null) vo = (ims.generalmedical.vo.OPDGenNotesShortVo)map.getValueObject(this); if(vo == null) { vo = new ims.generalmedical.vo.OPDGenNotesShortVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.core.vo.beans.CareContextShortVoBean getCareContext() { return this.carecontext; } public void setCareContext(ims.core.vo.beans.CareContextShortVoBean value) { this.carecontext = value; } private Integer id; private int version; private ims.core.vo.beans.CareContextShortVoBean carecontext; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/beans/OPDGenNotesShortVoBean.java
Java
agpl-3.0
3,955
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.forms.patientelectivelistandtciforcancellationdialog; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.RefMan.domain.PatientElectiveListAndTCIForCancellationDialog.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.RefMan.domain.PatientElectiveListAndTCIForCancellationDialog domain) { setContext(engine, form); this.domain = domain; } public final void free() { super.free(); domain = null; } protected ims.RefMan.domain.PatientElectiveListAndTCIForCancellationDialog domain; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/forms/patientelectivelistandtciforcancellationdialog/BaseLogic.java
Java
agpl-3.0
2,763
"use strict"; /** @internalapi @module hooks */ /** */ Object.defineProperty(exports, "__esModule", { value: true }); /** * A [[TransitionHookFn]] that rejects the Transition if it is invalid * * This hook is invoked at the end of the onBefore phase. * If the transition is invalid (for example, param values do not validate) * then the transition is rejected. */ function invalidTransitionHook(trans) { if (!trans.valid()) { throw new Error(trans.error().toString()); } } exports.registerInvalidTransitionHook = function (transitionService) { return transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 }); }; //# sourceMappingURL=invalidTransition.js.map
laclasse-com/service-cahiertextes
public/node_modules/@uirouter/core/lib/hooks/invalidTransition.js
JavaScript
agpl-3.0
702
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Cristian Belciug */ public class TriageForClinicianWorklistVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.TriageForClinicianWorklistVo copy(ims.emergency.vo.TriageForClinicianWorklistVo valueObjectDest, ims.emergency.vo.TriageForClinicianWorklistVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_Triage(valueObjectSrc.getID_Triage()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // Patient valueObjectDest.setPatient(valueObjectSrc.getPatient()); // Episode valueObjectDest.setEpisode(valueObjectSrc.getEpisode()); // Attendance valueObjectDest.setAttendance(valueObjectSrc.getAttendance()); // TrackingArea valueObjectDest.setTrackingArea(valueObjectSrc.getTrackingArea()); // TriageCompletionTime valueObjectDest.setTriageCompletionTime(valueObjectSrc.getTriageCompletionTime()); // CurrentTriageAssessment valueObjectDest.setCurrentTriageAssessment(valueObjectSrc.getCurrentTriageAssessment()); // CurrentTriagePathway valueObjectDest.setCurrentTriagePathway(valueObjectSrc.getCurrentTriagePathway()); // TriagePriorityChange valueObjectDest.setTriagePriorityChange(valueObjectSrc.getTriagePriorityChange()); // OBSScore valueObjectDest.setOBSScore(valueObjectSrc.getOBSScore()); // VitalsTakenDateTime valueObjectDest.setVitalsTakenDateTime(valueObjectSrc.getVitalsTakenDateTime()); // CurrentTriagePriority valueObjectDest.setCurrentTriagePriority(valueObjectSrc.getCurrentTriagePriority()); // MainPresentingProblem valueObjectDest.setMainPresentingProblem(valueObjectSrc.getMainPresentingProblem()); // TriageStartDateTime valueObjectDest.setTriageStartDateTime(valueObjectSrc.getTriageStartDateTime()); // MedicInterventionStartDateTime valueObjectDest.setMedicInterventionStartDateTime(valueObjectSrc.getMedicInterventionStartDateTime()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createTriageForClinicianWorklistVoCollectionFromTriage(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.Triage objects. */ public static ims.emergency.vo.TriageForClinicianWorklistVoCollection createTriageForClinicianWorklistVoCollectionFromTriage(java.util.Set domainObjectSet) { return createTriageForClinicianWorklistVoCollectionFromTriage(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.Triage objects. */ public static ims.emergency.vo.TriageForClinicianWorklistVoCollection createTriageForClinicianWorklistVoCollectionFromTriage(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.TriageForClinicianWorklistVoCollection voList = new ims.emergency.vo.TriageForClinicianWorklistVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.Triage domainObject = (ims.emergency.domain.objects.Triage) iterator.next(); ims.emergency.vo.TriageForClinicianWorklistVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.Triage objects. */ public static ims.emergency.vo.TriageForClinicianWorklistVoCollection createTriageForClinicianWorklistVoCollectionFromTriage(java.util.List domainObjectList) { return createTriageForClinicianWorklistVoCollectionFromTriage(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.Triage objects. */ public static ims.emergency.vo.TriageForClinicianWorklistVoCollection createTriageForClinicianWorklistVoCollectionFromTriage(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.TriageForClinicianWorklistVoCollection voList = new ims.emergency.vo.TriageForClinicianWorklistVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.Triage domainObject = (ims.emergency.domain.objects.Triage) domainObjectList.get(i); ims.emergency.vo.TriageForClinicianWorklistVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.Triage set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractTriageSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TriageForClinicianWorklistVoCollection voCollection) { return extractTriageSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractTriageSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TriageForClinicianWorklistVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.TriageForClinicianWorklistVo vo = voCollection.get(i); ims.emergency.domain.objects.Triage domainObject = TriageForClinicianWorklistVoAssembler.extractTriage(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.Triage list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractTriageList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TriageForClinicianWorklistVoCollection voCollection) { return extractTriageList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractTriageList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TriageForClinicianWorklistVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.TriageForClinicianWorklistVo vo = voCollection.get(i); ims.emergency.domain.objects.Triage domainObject = TriageForClinicianWorklistVoAssembler.extractTriage(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.Triage object. * @param domainObject ims.emergency.domain.objects.Triage */ public static ims.emergency.vo.TriageForClinicianWorklistVo create(ims.emergency.domain.objects.Triage domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.Triage object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.TriageForClinicianWorklistVo create(DomainObjectMap map, ims.emergency.domain.objects.Triage domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.TriageForClinicianWorklistVo valueObject = (ims.emergency.vo.TriageForClinicianWorklistVo) map.getValueObject(domainObject, ims.emergency.vo.TriageForClinicianWorklistVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.TriageForClinicianWorklistVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.Triage */ public static ims.emergency.vo.TriageForClinicianWorklistVo insert(ims.emergency.vo.TriageForClinicianWorklistVo valueObject, ims.emergency.domain.objects.Triage domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.Triage */ public static ims.emergency.vo.TriageForClinicianWorklistVo insert(DomainObjectMap map, ims.emergency.vo.TriageForClinicianWorklistVo valueObject, ims.emergency.domain.objects.Triage domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_Triage(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // Patient if (domainObject.getPatient() != null) { if(domainObject.getPatient() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getPatient(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setPatient(new ims.core.patient.vo.PatientRefVo(id, -1)); } else { valueObject.setPatient(new ims.core.patient.vo.PatientRefVo(domainObject.getPatient().getId(), domainObject.getPatient().getVersion())); } } // Episode if (domainObject.getEpisode() != null) { if(domainObject.getEpisode() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getEpisode(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setEpisode(new ims.core.admin.vo.EpisodeOfCareRefVo(id, -1)); } else { valueObject.setEpisode(new ims.core.admin.vo.EpisodeOfCareRefVo(domainObject.getEpisode().getId(), domainObject.getEpisode().getVersion())); } } // Attendance if (domainObject.getAttendance() != null) { if(domainObject.getAttendance() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getAttendance(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setAttendance(new ims.core.admin.vo.CareContextRefVo(id, -1)); } else { valueObject.setAttendance(new ims.core.admin.vo.CareContextRefVo(domainObject.getAttendance().getId(), domainObject.getAttendance().getVersion())); } } // TrackingArea if (domainObject.getTrackingArea() != null) { if(domainObject.getTrackingArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getTrackingArea(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setTrackingArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1)); } else { valueObject.setTrackingArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getTrackingArea().getId(), domainObject.getTrackingArea().getVersion())); } } // TriageCompletionTime java.util.Date TriageCompletionTime = domainObject.getTriageCompletionTime(); if ( null != TriageCompletionTime ) { valueObject.setTriageCompletionTime(new ims.framework.utils.DateTime(TriageCompletionTime) ); } // CurrentTriageAssessment valueObject.setCurrentTriageAssessment(ims.emergency.vo.domain.TriageProtocolAssessmentForTriageVoAssembler.create(map, domainObject.getCurrentTriageAssessment()) ); // CurrentTriagePathway if (domainObject.getCurrentTriagePathway() != null) { if(domainObject.getCurrentTriagePathway() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCurrentTriagePathway(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCurrentTriagePathway(new ims.icps.instantiation.vo.PatientICPRefVo(id, -1)); } else { valueObject.setCurrentTriagePathway(new ims.icps.instantiation.vo.PatientICPRefVo(domainObject.getCurrentTriagePathway().getId(), domainObject.getCurrentTriagePathway().getVersion())); } } // TriagePriorityChange ims.domain.lookups.LookupInstance instance8 = domainObject.getTriagePriorityChange(); if ( null != instance8 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance8.getImage() != null) { img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath()); } color = instance8.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.TriagePriorityChange voLookup8 = new ims.emergency.vo.lookups.TriagePriorityChange(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color); ims.emergency.vo.lookups.TriagePriorityChange parentVoLookup8 = voLookup8; ims.domain.lookups.LookupInstance parent8 = instance8.getParent(); while (parent8 != null) { if (parent8.getImage() != null) { img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() ); } else { img = null; } color = parent8.getColor(); if (color != null) color.getValue(); parentVoLookup8.setParent(new ims.emergency.vo.lookups.TriagePriorityChange(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color)); parentVoLookup8 = parentVoLookup8.getParent(); parent8 = parent8.getParent(); } valueObject.setTriagePriorityChange(voLookup8); } // OBSScore valueObject.setOBSScore(domainObject.getOBSScore()); // VitalsTakenDateTime java.util.Date VitalsTakenDateTime = domainObject.getVitalsTakenDateTime(); if ( null != VitalsTakenDateTime ) { valueObject.setVitalsTakenDateTime(new ims.framework.utils.DateTime(VitalsTakenDateTime) ); } // CurrentTriagePriority ims.domain.lookups.LookupInstance instance11 = domainObject.getCurrentTriagePriority(); if ( null != instance11 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance11.getImage() != null) { img = new ims.framework.utils.ImagePath(instance11.getImage().getImageId(), instance11.getImage().getImagePath()); } color = instance11.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.TriagePriority voLookup11 = new ims.emergency.vo.lookups.TriagePriority(instance11.getId(),instance11.getText(), instance11.isActive(), null, img, color); ims.emergency.vo.lookups.TriagePriority parentVoLookup11 = voLookup11; ims.domain.lookups.LookupInstance parent11 = instance11.getParent(); while (parent11 != null) { if (parent11.getImage() != null) { img = new ims.framework.utils.ImagePath(parent11.getImage().getImageId(), parent11.getImage().getImagePath() ); } else { img = null; } color = parent11.getColor(); if (color != null) color.getValue(); parentVoLookup11.setParent(new ims.emergency.vo.lookups.TriagePriority(parent11.getId(),parent11.getText(), parent11.isActive(), null, img, color)); parentVoLookup11 = parentVoLookup11.getParent(); parent11 = parent11.getParent(); } valueObject.setCurrentTriagePriority(voLookup11); } // MainPresentingProblem valueObject.setMainPresentingProblem(ims.emergency.vo.domain.PatientProblemForClinicianWorklistVoAssembler.create(map, domainObject.getMainPresentingProblem()) ); // TriageStartDateTime java.util.Date TriageStartDateTime = domainObject.getTriageStartDateTime(); if ( null != TriageStartDateTime ) { valueObject.setTriageStartDateTime(new ims.framework.utils.DateTime(TriageStartDateTime) ); } // MedicInterventionStartDateTime java.util.Date MedicInterventionStartDateTime = domainObject.getMedicInterventionStartDateTime(); if ( null != MedicInterventionStartDateTime ) { valueObject.setMedicInterventionStartDateTime(new ims.framework.utils.DateTime(MedicInterventionStartDateTime) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.Triage extractTriage(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TriageForClinicianWorklistVo valueObject) { return extractTriage(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.Triage extractTriage(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TriageForClinicianWorklistVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_Triage(); ims.emergency.domain.objects.Triage domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.Triage)domMap.get(valueObject); } // ims.emergency.vo.TriageForClinicianWorklistVo ID_Triage field is unknown domainObject = new ims.emergency.domain.objects.Triage(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Triage()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.Triage)domMap.get(key); } domainObject = (ims.emergency.domain.objects.Triage) domainFactory.getDomainObject(ims.emergency.domain.objects.Triage.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_Triage()); ims.core.patient.domain.objects.Patient value1 = null; if ( null != valueObject.getPatient() ) { if (valueObject.getPatient().getBoId() == null) { if (domMap.get(valueObject.getPatient()) != null) { value1 = (ims.core.patient.domain.objects.Patient)domMap.get(valueObject.getPatient()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getPatient(); } else { value1 = (ims.core.patient.domain.objects.Patient)domainFactory.getDomainObject(ims.core.patient.domain.objects.Patient.class, valueObject.getPatient().getBoId()); } } domainObject.setPatient(value1); ims.core.admin.domain.objects.EpisodeOfCare value2 = null; if ( null != valueObject.getEpisode() ) { if (valueObject.getEpisode().getBoId() == null) { if (domMap.get(valueObject.getEpisode()) != null) { value2 = (ims.core.admin.domain.objects.EpisodeOfCare)domMap.get(valueObject.getEpisode()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value2 = domainObject.getEpisode(); } else { value2 = (ims.core.admin.domain.objects.EpisodeOfCare)domainFactory.getDomainObject(ims.core.admin.domain.objects.EpisodeOfCare.class, valueObject.getEpisode().getBoId()); } } domainObject.setEpisode(value2); ims.core.admin.domain.objects.CareContext value3 = null; if ( null != valueObject.getAttendance() ) { if (valueObject.getAttendance().getBoId() == null) { if (domMap.get(valueObject.getAttendance()) != null) { value3 = (ims.core.admin.domain.objects.CareContext)domMap.get(valueObject.getAttendance()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value3 = domainObject.getAttendance(); } else { value3 = (ims.core.admin.domain.objects.CareContext)domainFactory.getDomainObject(ims.core.admin.domain.objects.CareContext.class, valueObject.getAttendance().getBoId()); } } domainObject.setAttendance(value3); ims.emergency.configuration.domain.objects.TrackingArea value4 = null; if ( null != valueObject.getTrackingArea() ) { if (valueObject.getTrackingArea().getBoId() == null) { if (domMap.get(valueObject.getTrackingArea()) != null) { value4 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getTrackingArea()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value4 = domainObject.getTrackingArea(); } else { value4 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getTrackingArea().getBoId()); } } domainObject.setTrackingArea(value4); ims.framework.utils.DateTime dateTime5 = valueObject.getTriageCompletionTime(); java.util.Date value5 = null; if ( dateTime5 != null ) { value5 = dateTime5.getJavaDate(); } domainObject.setTriageCompletionTime(value5); // SaveAsRefVO - treated as a refVo in extract methods ims.emergency.domain.objects.TriageProtocolAssessment value6 = null; if ( null != valueObject.getCurrentTriageAssessment() ) { if (valueObject.getCurrentTriageAssessment().getBoId() == null) { if (domMap.get(valueObject.getCurrentTriageAssessment()) != null) { value6 = (ims.emergency.domain.objects.TriageProtocolAssessment)domMap.get(valueObject.getCurrentTriageAssessment()); } } else { value6 = (ims.emergency.domain.objects.TriageProtocolAssessment)domainFactory.getDomainObject(ims.emergency.domain.objects.TriageProtocolAssessment.class, valueObject.getCurrentTriageAssessment().getBoId()); } } domainObject.setCurrentTriageAssessment(value6); ims.icps.instantiation.domain.objects.PatientICP value7 = null; if ( null != valueObject.getCurrentTriagePathway() ) { if (valueObject.getCurrentTriagePathway().getBoId() == null) { if (domMap.get(valueObject.getCurrentTriagePathway()) != null) { value7 = (ims.icps.instantiation.domain.objects.PatientICP)domMap.get(valueObject.getCurrentTriagePathway()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value7 = domainObject.getCurrentTriagePathway(); } else { value7 = (ims.icps.instantiation.domain.objects.PatientICP)domainFactory.getDomainObject(ims.icps.instantiation.domain.objects.PatientICP.class, valueObject.getCurrentTriagePathway().getBoId()); } } domainObject.setCurrentTriagePathway(value7); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value8 = null; if ( null != valueObject.getTriagePriorityChange() ) { value8 = domainFactory.getLookupInstance(valueObject.getTriagePriorityChange().getID()); } domainObject.setTriagePriorityChange(value8); domainObject.setOBSScore(valueObject.getOBSScore()); ims.framework.utils.DateTime dateTime10 = valueObject.getVitalsTakenDateTime(); java.util.Date value10 = null; if ( dateTime10 != null ) { value10 = dateTime10.getJavaDate(); } domainObject.setVitalsTakenDateTime(value10); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value11 = null; if ( null != valueObject.getCurrentTriagePriority() ) { value11 = domainFactory.getLookupInstance(valueObject.getCurrentTriagePriority().getID()); } domainObject.setCurrentTriagePriority(value11); // SaveAsRefVO - treated as a refVo in extract methods ims.core.clinical.domain.objects.PatientProblem value12 = null; if ( null != valueObject.getMainPresentingProblem() ) { if (valueObject.getMainPresentingProblem().getBoId() == null) { if (domMap.get(valueObject.getMainPresentingProblem()) != null) { value12 = (ims.core.clinical.domain.objects.PatientProblem)domMap.get(valueObject.getMainPresentingProblem()); } } else { value12 = (ims.core.clinical.domain.objects.PatientProblem)domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientProblem.class, valueObject.getMainPresentingProblem().getBoId()); } } domainObject.setMainPresentingProblem(value12); ims.framework.utils.DateTime dateTime13 = valueObject.getTriageStartDateTime(); java.util.Date value13 = null; if ( dateTime13 != null ) { value13 = dateTime13.getJavaDate(); } domainObject.setTriageStartDateTime(value13); ims.framework.utils.DateTime dateTime14 = valueObject.getMedicInterventionStartDateTime(); java.util.Date value14 = null; if ( dateTime14 != null ) { value14 = dateTime14.getJavaDate(); } domainObject.setMedicInterventionStartDateTime(value14); return domainObject; } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/TriageForClinicianWorklistVoAssembler.java
Java
agpl-3.0
32,668
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of iotagent project. * * iotagent 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. * * iotagent 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 iotagent. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with iot_support at tid dot es */ #ifndef PUSHCOMMANDSTEST_H #define PUSHCOMMANDSTEST_H #include "MockMosquitto.h" #include "input_mqtt/ESP_Plugin_Input_Mqtt.h" #include <cppunit/extensions/HelperMacros.h> class PushCommandsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(PushCommandsTest); CPPUNIT_TEST(testSendPushCommand); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); protected: void testSendPushCommand(); private: //Stubs: int stubPublish(int* mid, const char* topic, int payloadlen, const void* payload, int qos, bool retain); int stubSubscribeSilent(int* mid, const char* sub, int qos); int stubConnectPub(const char* host, int port, int keepalive); int stubConnectSub(const char* host, int port, int keepalive); MockMosquitto* mosquittoPub; MockMosquitto* mosquittoSub; struct mosquitto_message mqttMsg; }; #endif // PUSHCOMMANDSTEST_H
guerrerocarlos/fiware-IoTAgent-Cplusplus
tests/esp/h/PushCommandsTest.h
C
agpl-3.0
1,813
"""Contain the AskViewTests class""" import unittest import os import tempfile import datetime import json import humanize from shutil import copyfile from pyramid import testing from pyramid.paster import get_appsettings from askomics.libaskomics.ParamManager import ParamManager from askomics.libaskomics.TripleStoreExplorer import TripleStoreExplorer from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher from askomics.libaskomics.EndpointManager import EndpointManager from askomics.ask_view import AskView from SetupTests import SetupTests from interface_tps_db import InterfaceTpsDb class AskViewTests(unittest.TestCase): """Test for Askview Contain all the tests for the askView class """ def setUp(self): """Set up the configuration to access the triplestore Use the config file test.virtuoso.ini to not interfere with production data """ self.settings = get_appsettings('configs/tests.ini', name='main') self.settings['askomics.upload_user_data_method'] = 'insert' self.request = testing.DummyRequest() self.config = testing.setUp(request=self.request) self.config.add_route('load_data_into_graph', '/load_data_into_graph') self.config.scan() self.request.session['user_id'] = 1 self.request.session['username'] = 'jdoe' self.request.session['email'] = 'jdoe@example.com' self.request.session['admin'] = True self.request.session['blocked'] = False self.request.session['graph'] = 'urn:sparql:test_askomics:jdoe' self.request.host_url = 'http://localhost:6543' self.request.json_body = {} SetupTests(self.settings, self.request.session) self.tps = InterfaceTpsDb(self.settings, self.request) self.askview = AskView(self.request) self.askview.settings = self.settings def getKeyNode(self,node): return node['uri'] def test_main(self): import askomics askomics.main(self.config) def test_start_points(self): """Test the start_points method Insert 2 datasets and test the start points """ self.tps.clean_up() # load a test timestamp_people = self.tps.load_people() timestamp_instruments = self.tps.load_instruments() data = self.askview.start_points() # empty tps self.tps.clean_up() expected_result = { 'nodes': { self.settings['askomics.prefix']+'Instruments': { 'uri': self.settings['askomics.prefix']+'Instruments', 'g': 'urn:sparql:test_askomics:jdoe:instruments_tsv_' + timestamp_instruments, 'public': False, 'label': 'Instruments', 'private': True, 'endpoint': 'http://localhost:8890/sparql' }, self.settings['askomics.prefix']+'People': { 'uri': self.settings['askomics.prefix']+'People', 'g': 'urn:sparql:test_askomics:jdoe:people_tsv_' + timestamp_people, 'public': False, 'label': 'People', 'private': True, 'endpoint': 'http://localhost:8890/sparql' } }, 'galaxy': False } assert len(data["nodes"]) == 2 # data["nodes"] = sorted(data["nodes"], key=self.getKeyNode) # expected_result["nodes"] = sorted( # expected_result["nodes"], key=self.getKeyNode) assert expected_result["nodes"] == data["nodes"] def test_statistics(self): # empty tps self.tps.clean_up() # load a test timestamp_people = self.tps.load_public_people() timestamp_instrument = self.tps.load_instruments() self.askview.statistics() def test_add_endpoint(self): # empty tps self.tps.clean_up() try: self.askview.add_endpoint() assert False except Exception as e: assert True self.request.json_body['name'] = 'testendp' try: self.askview.add_endpoint() assert False except Exception as e: assert True self.request.json_body['url'] = 'https://dbpedia.org/sparql' try: self.askview.add_endpoint() assert False except Exception as e: assert True self.request.json_body['auth'] = 'bidon' try: self.askview.add_endpoint() assert False except Exception as e: assert True self.request.json_body['auth'] = 'basic' try: self.askview.add_endpoint() assert True except Exception as e: assert False def test_zenable_endpoint(self): # empty tps self.tps.clean_up() self.request.json_body['name'] = 'testendp' self.request.json_body['url'] = 'https://dbpedia.org/sparql' self.request.json_body['auth'] = 'basic' try: self.askview.add_endpoint() assert True except Exception as e: assert False try: self.askview.enable_endpoints() assert False except Exception as e: assert True self.request.json_body['id'] = 1 try: self.askview.enable_endpoints() assert False except Exception as e: assert True self.request.json_body['enable'] = True try: self.askview.enable_endpoints() assert True except Exception as e: assert False self.request.json_body['enable'] = False try: self.askview.enable_endpoints() assert True except Exception as e: assert False self.tps.clean_up() def test_zdelete_endpoint(self): # empty tps self.tps.clean_up() self.request.json_body['name'] = 'testendp' self.request.json_body['url'] = 'https://dbpedia.org/sparql' self.request.json_body['auth'] = 'basic' try: self.askview.add_endpoint() assert True except Exception as e: assert False try: self.askview.delete_endpoints() assert False except Exception as e: assert True self.request.json_body['endpoints'] = 'testendp' try: self.askview.delete_endpoints() assert True except Exception as e: print(e) assert False def test_list_endpoint(self): # empty tps self.tps.clean_up() self.request.json_body['name'] = 'testendp' self.request.json_body['url'] = 'https://dbpedia.org/sparql' self.request.json_body['auth'] = 'basic' try: self.askview.add_endpoint() assert True except Exception as e: assert False self.askview.list_endpoints() def test_guess_csv_header_type(self): self.tps.clean_up() try: self.askview.guess_csv_header_type() assert False except Exception as e: assert True self.request.json_body['filename'] = 'people.tsv' self.askview.guess_csv_header_type() def test_empty_database(self): """Test the empty_database method Insert data and test empty_database. Also test if start point return no results after deletion """ # empty tps self.tps.clean_up() # load a test timestamp_people = self.tps.load_people() self.tps.load_instruments() data = self.askview.empty_database() assert data == {} # if success, return an empty dict # test if start point return no data askview2 = AskView(self.request) askview2.settings = self.settings data = askview2.start_points() assert data == {'nodes': {}, 'galaxy': False} def test_delete_graph(self): """Test delete_graph method Insert 2 datasets, and test delete_graph on one. Also test if start point return only one datasets """ # empty tps self.tps.clean_up() # load a test timestamp_people = self.tps.load_people() # need the timestamp of people to delete it timestamp_instruments = self.tps.load_instruments() # Delete only the people graph self.request.json_body = { 'named_graph': ['urn:sparql:test_askomics:jdoe:people_tsv_' + timestamp_people] } data = self.askview.delete_graph() assert data is None # test if start point return only one entity askview2 = AskView(self.request) askview2.settings = self.settings data = askview2.start_points() assert len(data["nodes"]) == 1 # test if startpoint return only instruments expected_result = { 'nodes': { self.settings['askomics.prefix']+'Instruments': { 'public': False, 'label': 'Instruments', 'uri': self.settings['askomics.prefix']+'Instruments', 'private': True, 'g': 'urn:sparql:test_askomics:jdoe:instruments_tsv_' + timestamp_instruments, 'endpoint': 'http://localhost:8890/sparql' } }, 'galaxy': False } assert data == expected_result def test_get_list_user_graph(self): """Test get_list_private_graph method insert 1 dataset and one public dataset and check which is private """ # empty tps self.tps.clean_up() # load a test timestamp_people = self.tps.load_public_people() timestamp_instrument = self.tps.load_instruments() #TODO: insert data for another user and test that the function don't return data of another user data = self.askview.list_user_graph() readable_date_people = datetime.datetime.strptime(timestamp_people, "%Y-%m-%dT%H:%M:%S.%f").strftime("%d/%m/%Y %H:%M:%S") readable_date_instrument = datetime.datetime.strptime(timestamp_instrument, "%Y-%m-%dT%H:%M:%S.%f").strftime("%d/%m/%Y %H:%M:%S") assert len(data) == 2 assert isinstance(data, list) print("-- PRINT data --") print(data) print("--") assert { 'g': 'urn:sparql:test_askomics:jdoe:people_tsv_' + timestamp_people, 'count': '85', 'access': 'public', 'owner': 'jdoe', 'date': timestamp_people, 'readable_date': readable_date_people, 'name': 'people.tsv', 'access_bool': True, 'endpoint': '' } in data assert { 'g': 'urn:sparql:test_askomics:jdoe:instruments_tsv_' + timestamp_instrument, 'count': '76', 'access': 'private', 'owner': 'jdoe', 'date': timestamp_instrument, 'readable_date': readable_date_instrument, 'name': 'instruments.tsv', 'access_bool': False, 'endpoint': '' } in data def test_source_files_overview(self): """Test source_files_overview method""" self.tps.clean_up() self.request.json_body = ['people.tsv', 'instruments.tsv'] data = self.askview.source_files_overview() instrument = {'name': 'instruments.tsv', 'type': 'tsv', 'headers': ['Instruments', 'Name', 'Class'], 'preview_data': [['i1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7', 'i8', 'i9'], ['Tubular_Bells', 'Mandolin', 'Electric_guitar', 'Violin', 'Acoustic_guitar', 'Bass_guitar', 'MiniMoog', 'Laser_Harp', 'Piano'], ['Percussion', 'String', 'String', 'String', 'String', 'String', 'Electro-analog', 'Electro-analog', 'String']], 'column_types': ['entity_start', 'text', 'category']} people = {'name': 'people.tsv', 'type': 'tsv', 'headers': ['People', 'First_name', 'Last_name', 'Sex', 'Age'], 'preview_data': [['p1', 'p2', 'p3', 'p4', 'p5', 'p6'], ['Mike', 'Jean-Michel', 'Roger', 'Matthew', 'Ellen', 'Richard'], ['Oldfield', 'Jarre', 'Waters', 'Bellamy', 'Fraatz', 'Melville'], ['M', 'M', 'M', 'M', 'F', 'M'], ['63', '68', '73', '38', '39', '51']], 'column_types': ['entity_start', 'text', 'text', 'category', 'numeric']} assert set(data) == {'files', 'taxons'} assert data['taxons'] == [] assert len(data['files']) == 2 assert instrument in data['files'] assert people in data['files'] self.request.json_body = ['transcript.tsv'] data = self.askview.source_files_overview() expected = { "files": [ { "name": "transcript.tsv", "headers": [ "transcript", "taxon", "chromosomeName", "start", "end", "strand", "biotype" ], "column_types": [ "entity_start", "taxon", "ref", "start", "end", "strand", "category" ], "preview_data": [ [ "AT3G10490","AT3G13660","AT3G51470","AT3G10460","AT3G22640","AT1G33615","AT5G41905","AT1G57800","AT1G49500","AT5G35334" ], [ "Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana","Arabidopsis_thaliana" ], [ "At3","At3","At3","At3","At3","At1","At5","At1","At1","At5" ], [ "3267835","4464908","19097787","3255800","8011724","12193325","16775524","21408623","18321295","13537917" ], [ "3270883","4465586","19099275","3256439","8013902","12194374","16775658","21412283","18322284","13538984" ], [ "plus", "plus", "minus", "plus", "minus", "minus", "minus", "minus", "minus", "plus" ], [ "protein_coding", "protein_coding", "protein_coding", "protein_coding", "protein_coding", "ncRNA", "miRNA", "protein_coding", "protein_coding", "transposable_element" ] ], "type": "tsv" } ], "taxons": [] } assert data == expected self.request.json_body = ['bed_example.bed'] data = self.askview.source_files_overview() self.request.json_body = ['turtle_data.ttl'] data = self.askview.source_files_overview() self.request.json_body = ['small_data.gff3'] data = self.askview.source_files_overview() self.request.json_body = ['wrong.gff'] data = self.askview.source_files_overview() def test_prefix_uri(self): """Test prefix_uri method""" self.tps.clean_up() data = self.askview.prefix_uri() def test_load_remote_data_into_graph(self): """Test load_remote_data_into_graph method""" self.tps.clean_up() try: data = self.askview.load_remote_data_into_graph() assert False except Exception as e: assert True self.request.json_body['public'] = True try: data = self.askview.load_remote_data_into_graph() assert False except Exception as e: assert True self.request.json_body['public'] = False try: data = self.askview.load_remote_data_into_graph() assert False except Exception as e: assert True self.request.json_body['public'] = False self.request.json_body['url'] = 'bidonurl.ttl' try: data = self.askview.load_remote_data_into_graph() assert 'error' in data except Exception as e: assert True self.request.json_body['public'] = True self.request.session['admin'] = False try: data = self.askview.load_remote_data_into_graph() assert False except Exception as e: assert True self.request.session['admin'] = True self.request.json_body['public'] = False self.request.json_body['url'] = 'https://raw.githubusercontent.com/askomics/askomics/master/askomics/static/modules/dbpedia.ttl' try: data = self.askview.load_remote_data_into_graph() assert True except Exception as e: assert False def test_preview_ttl(self): """Test preview_ttl method""" self.tps.clean_up() self.request.json_body = { 'file_name': 'people.tsv', 'key_columns': [0], 'col_types': [ 'entity_start', 'text', 'text', 'category', 'numeric' ], 'disabled_columns': [], 'uris': {'0': 'http://www.semanticweb.org/user/ontologies/2018/1#', '1': None, '2': None, '3': None, '4': None} } data = self.askview.preview_ttl() def test_check_existing_data(self): """Test check_existing_data""" #FIXME: I think this method is no longer used in askomics pass def test_load_data_into_graph(self): """Test load_data_into_graph method Load the file people.tsv and test the results """ self.tps.clean_up() self.request.json_body = { 'file_name': 'people.tsv', 'key_columns': [0], 'col_types': [ 'entity_start', 'text', 'text', 'category', 'numeric' ], 'uris': {'0': 'http://www.semanticweb.org/user/ontologies/2018/1#', '1': None, '2': None, '3': None, '4': None}, 'disabled_columns': [], 'public': False, 'headers': ['People', 'First_name', 'Last_name', 'Sex', 'Age'], 'method': 'noload' } data = self.askview.load_data_into_graph() assert data == {'total_triple_count': 6, 'status': 'ok', 'expected_lines_number': 6} def test_load_gff_into_graph(self): """Test load_gff_into_graph method Load the file small_data.gff3 and test the results """ self.tps.clean_up() self.request.json_body = { 'file_name': 'small_data.gff3', 'taxon': 'Arabidopsis_thaliana', 'entities': ['transcript', 'gene'], 'public': False, 'method': 'load' } data = self.askview.load_gff_into_graph() self.request.json_body['uri'] = 'Bad uri' data = self.askview.load_gff_into_graph() self.request.json_body['forced_type'] = 'bad' data = self.askview.load_gff_into_graph() try: self.request.json_body['public'] = True self.request.session['admin'] = False data = self.askview.load_gff_into_graph() assert False # Expected exception except ValueError: assert True self.request.json_body['public'] = True self.request.session['admin'] = True data = self.askview.load_gff_into_graph() #The test can no be OK because no Askomics serveur is available and so the # command LOAD <http://localhost:6543/ttl/jdoe/tmp_small_data.gff3sebeuo2e.ttl> INTO GRAPH <urn:sparql:test_askomics:jdoe:small_data.gff3_2017-04-27T14:58:59.676364> # can no be work ! #assert data == {'status': 'ok'} def test_load_ttl_into_graph(self): """Test load_ttl_into_graph method Load the file turtle_data.ttl and test the results """ self.tps.clean_up() self.request.json_body = { 'file_name': 'turtle_data.ttl', 'public': False, 'method': 'load' } self.askview.load_ttl_into_graph() self.request.json_body['forced_type'] = 'bad' self.askview.load_ttl_into_graph() try: self.request.json_body['public'] = True self.request.session['admin'] = False self.askview.load_ttl_into_graph() assert False # Expected exception except ValueError: assert True # The load can't work because no http server is running and virtuoso can not find file to http://localhost:6543/file/xxxx.ttl self.request.json_body['public'] = True self.request.session['admin'] = True self.askview.load_ttl_into_graph() def test_load_bed_into_graph(self): """Test load_bed_into_graph method Load the file turtle_data.ttl and test the results """ self.tps.clean_up() self.request.json_body = { 'file_name': 'bed_example.bed', 'taxon': 'Arabidopsis_thaliana', 'entity_name': 'test', 'public': False, 'method': 'load' } self.askview.load_ttl_into_graph() self.request.json_body['uri'] = 'test' self.askview.load_bed_into_graph() self.request.json_body['forced_type'] = 'bad' self.askview.load_bed_into_graph() try: self.request.json_body['public'] = True self.request.session['admin'] = False self.askview.load_bed_into_graph() assert False # Expected exception except ValueError: assert True # The load can't work because no http server is running and virtuoso can not find file to http://localhost:6543/file/xxxx.ttl self.request.json_body['public'] = True self.request.session['admin'] = True self.askview.load_bed_into_graph() def test_get_user_abstraction(self): """Test getUser_Abstraction""" self.tps.clean_up() # load a test self.tps.load_people() self.tps.load_instruments() self.request.json_body = {} data = self.askview.getUserAbstraction() print("-- data --") for k in data: print(k) print(" -- ") # FIXME hard to compare wih expected result cause there is a timestamp assert len(data) == 8 assert 'categories' in data assert 'endpoints' in data assert 'endpoints_ext' in data assert 'attributes' in data assert 'entities' in data assert 'subclassof' in data assert 'relations' in data assert 'positionable' in data def test_importShortcut(self): """ """ # TODO: pass def test_deleteShortcut(self): """ """ # TODO: pass def test_get_value(self): """test get_value method Load a test and test get_value """ self.tps.clean_up() # load a test timestamp_people = self.tps.load_people() self.request.json_body = { 'type_endpoints' : [ "askomics" ], 'endpoints' : [ "http://localhost:8890/sparql" ], 'graphs' : [ 'urn:sparql:test_askomics:jdoe:people_tsv_' + timestamp_people ], 'limit': 30, 'constraintesRelations': [[[[ '?URIPeople1 rdf:type <'+self.settings['askomics.prefix']+'People>', '?URIPeople1 rdfs:label ?People1' ], '']], ''], 'variates': { 'People1' : ['?People1'] }, 'removeGraph': [] } data = self.askview.get_value() assert data == { 'values': [{ 'People1': 'p1' }, { 'People1': 'p2' }, { 'People1': 'p3' }, { 'People1': 'p4' }, { 'People1': 'p5' }, { 'People1': 'p6' }], 'file': data['file'], 'nrow': 6, 'galaxy': False } def test_get_sparql_query_text(self): """Test get_sparql_query_in_text_format method""" self.tps.clean_up() # load a test timestamp_people = self.tps.load_people() self.request.json_body = { 'type_endpoints' : [ "askomics" ], 'endpoints' : [ "http://localhost:8890/sparql" ], 'graphs' : [ 'urn:sparql:test_askomics:jdoe:people_tsv_' + timestamp_people ], 'export': False, 'limit': 500, 'constraintesRelations': [[[[ '?URIPeople1 rdf:type <'+self.settings['askomics.prefix']+'People>', '?URIPeople1 rdfs:label ?People1' ], '']], ''], 'variates': ['?People1'] } data = self.askview.getSparqlQueryInTextFormat() def test_upload_ttl(self): """Test uploadTtl method""" #TODO: pass def test_upload_csv(self): """Test uploadCsv method""" #TODO: pass def test_delet_csv(self): """Test deletCsv method""" #TODO: pass def test_delete_uploaded_files(self): """Test load_gff_into_graph method Load the file turtle_data.ttl and test the results """ self.tps.clean_up() self.askview.delete_uploaded_files() self.request.session['admin'] = True self.askview.delete_uploaded_files() def test_serverinformations(self): """Test load_gff_into_graph method Load the file turtle_data.ttl and test the results """ self.tps.clean_up() self.askview.serverinformations() self.request.session['admin'] = True self.askview.serverinformations() def test_cleantmpdirectory(self): """Test load_gff_into_graph method Load the file turtle_data.ttl and test the results """ self.tps.clean_up() self.askview.cleantmpdirectory() self.request.session['admin'] = True self.askview.cleantmpdirectory() def test_signup(self): """Test signup method""" self.tps.clean_up() self.request.json_body = { 'username': 'jdoe', 'email': 'jdoe@example.com', 'password': 'iamjohndoe', 'password2': 'iamjohndoe' } data = self.askview.signup() assert data == {'error': [], 'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': True, 'blocked': False, 'galaxy': None} def test_checkuser(self): """Test checkuser method""" self.tps.clean_up() self.tps.add_jdoe_in_users() data = self.askview.checkuser() assert data == {'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': False, 'blocked': False, 'galaxy': None} def test_logout(self): """Test logout method""" self.tps.clean_up() self.askview.logout() assert self.request.session == {} def test_login(self): """Test login method""" self.tps.clean_up() #first, create a user self.request.json_body = { 'username': 'jdoe', 'email': 'jdoe@example.com', 'password': 'iamjohndoe', 'password2': 'iamjohndoe' } self.askview.signup() # then, logout this user self.askview.logout() # and then, test login self.request.json_body = { 'username_email': 'jdoe', 'password': 'iamjohndoe' } data = self.askview.login() assert data == {'error': [], 'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': True, 'blocked': False, 'galaxy': None} def test_login_api(self): """Test login_api method""" self.tps.clean_up() self.tps.add_jdoe_in_users() self.request.GET['key'] = 'jdoe_apikey' data = self.askview.login_api() assert data == {'error': '', 'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': False, 'blocked': False, 'galaxy': None} def test_login_api_gie(self): """Test login_api_gie method""" self.tps.clean_up() self.tps.add_jdoe_in_users() self.request.GET['key'] = 'jdoe_apikey' self.askview.login_api() def test_get_users_infos(self): """Test get_users_infos""" self.tps.clean_up() # first test with non admin try : data = self.askview.get_users_infos() assert False except Exception as e: assert True # then, is user is admin self.request.session['admin'] = True data = self.askview.get_users_infos() assert data == {'result': [], 'me': 'jdoe'} #result is empty cause there is no user #test with user self.request.json_body = { 'username': 'jdoe', 'email': 'jdoe@example.com', 'password': 'iamjohndoe', 'password2': 'iamjohndoe' } # get dir size pm = ParamManager(self.settings, self.request.session) dir_size = pm.get_size(pm.get_user_dir_path()) human_dir_size = humanize.naturalsize(dir_size) self.askview.signup() data = self.askview.get_users_infos() assert data == {'result': [{'ldap': False, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': True, 'blocked': False, 'gurl': None, 'nquery': 0, 'nintegration': 0, 'dirsize': dir_size, 'hdirsize': human_dir_size}], 'me': 'jdoe', 'error': [], 'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': True, 'blocked': False, 'galaxy': None} def test_lock_user(self): """Test lock_user method""" self.tps.clean_up() self.request.json_body = { 'username': 'jdoe', 'lock': True } # first test with non admin try: data = self.askview.lock_user() assert False except Exception as e: assert True # then, is user is admin self.request.session['admin'] = True data = self.askview.lock_user() assert data == 'success' def test_set_admin(self): """Test set_admin_method""" self.tps.clean_up() self.request.json_body = { 'username': 'jdoe', 'admin': True } try: data = self.askview.set_admin() except Exception as e: assert True # then, is user is admin self.request.session['admin'] = True data = self.askview.set_admin() assert data == 'success' def test_delete_user(self): """Test delete_user method""" self.tps.clean_up() # Insert a user self.request.json_body = { 'username': 'jdoe', 'email': 'jdoe@example.com', 'password': 'iamjohndoe', 'password2': 'iamjohndoe' } self.askview.signup() # test the deletion self.request.json_body = { 'username': 'jdoe', 'passwd': 'iamjohndoe', 'passwd_conf': 'iamjohndoe' } self.request.session['blocked'] = False self.request.session['admin'] = False self.request.session['username'] = 'jdoe' data = self.askview.delete_user() assert data == 'success' def test_get_my_infos(self): """Test get_my_infos""" self.tps.clean_up() self.tps.add_jdoe_in_users() # get my infos data = self.askview.get_my_infos() assert data == {'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': False, 'blocked': False, 'apikey': 'jdoe_apikey', 'galaxy': None, 'ldap': False} def test_update_mail(self): """Test update_mail""" self.tps.clean_up() self.tps.add_jdoe_in_users() # And change my email self.request.json_body = { 'username': 'jdoe', 'email': 'mynewmail@example.com' } data = self.askview.update_mail() assert data == {'success': 'success'} def test_update_passwd(self): """Test update_passwd method""" self.tps.clean_up() # First, insert me self.request.json_body = { 'username': 'jdoe', 'email': 'jdoe@example.com', 'password': 'iamjohndoe', 'password2': 'iamjohndoe' } self.askview.signup() # And update my password self.request.json_body = { 'username': 'jdoe', 'current_passwd': 'iamjohndoe', 'passwd': 'mynewpassword', 'passwd2': 'mynewpassword', } data = self.askview.update_passwd() assert data == {'error': [], 'user_id': 1, 'username': 'jdoe', 'email': 'jdoe@example.com', 'admin': True, 'blocked': False, 'galaxy': None, 'success': 'success'}
askomics/askomics
askomics/test/askView_test.py
Python
agpl-3.0
35,237
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.ttaprintdialog; import java.io.Serializable; import ims.framework.Context; import ims.framework.FormName; import ims.framework.FormAccessLogic; public class BaseAccessLogic extends FormAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public final void setContext(Context context, FormName formName) { form = new CurrentForm(new GlobalContext(context), new CurrentForms()); engine = new CurrentEngine(formName); } public boolean isAccessible() { if(!form.getGlobalContext().Core.getCurrentCareContextIsNotNull()) return false; return true; } public boolean isReadOnly() { return false; } public CurrentEngine engine; public CurrentForm form; public final static class CurrentForm implements Serializable { private static final long serialVersionUID = 1L; CurrentForm(GlobalContext globalcontext, CurrentForms forms) { this.globalcontext = globalcontext; this.forms = forms; } public final GlobalContext getGlobalContext() { return globalcontext; } public final CurrentForms getForms() { return forms; } private GlobalContext globalcontext; private CurrentForms forms; } public final static class CurrentEngine implements Serializable { private static final long serialVersionUID = 1L; CurrentEngine(FormName formName) { this.formName = formName; } public final FormName getFormName() { return formName; } private FormName formName; } public static final class CurrentForms implements Serializable { private static final long serialVersionUID = 1L; protected final class LocalFormName extends FormName { private static final long serialVersionUID = 1L; protected LocalFormName(int value) { super(value); } } private CurrentForms() { } } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/forms/ttaprintdialog/BaseAccessLogic.java
Java
agpl-3.0
4,023
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.forms.clinicalnotescustomcontrol; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void onFormModeChanged(); abstract protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnPrintClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnPreviousClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onRadioButtonGroupViewValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onDyngrdNotesRowSelectionChanged(ims.framework.controls.DynamicGridRow row) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onDyngrdNotesColumnHeaderClicked(ims.framework.controls.DynamicGridColumn column); abstract protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIComponentEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormModeChangedEvent(new FormModeChanged() { private static final long serialVersionUID = 1L; public void handle() { onFormModeChanged(); } }); this.form.setFormDialogClosedEvent(new FormDialogClosed() { private static final long serialVersionUID = 1L; public void handle(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onFormDialogClosed(formName, result); } }); this.form.btnPrint().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnPrintClick(); } }); this.form.btnPrevious().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnPreviousClick(); } }); this.form.GroupView().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onRadioButtonGroupViewValueChanged(); } }); this.form.dyngrdNotes().setDynamicGridRowSelectionChangedEvent(new DynamicGridRowSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.controls.DynamicGridRow row, ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onDyngrdNotesRowSelectionChanged(row); } }); this.form.dyngrdNotes().setDynamicGridColumnHeaderClickedEvent(new DynamicGridColumnHeaderClicked() { private static final long serialVersionUID = 1L; public void handle(ims.framework.controls.DynamicGridColumn column) throws ims.framework.exceptions.PresentationLogicException { onDyngrdNotesColumnHeaderClicked(column); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuADD_NOTESItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.ADD_NOTES, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuADD_DIAGNOSISItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.ADD_DIAGNOSIS, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuADD_PROCEDUREItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.ADD_PROCEDURE, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuEDIT_NOTEItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.EDIT_NOTE, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuEDIT_DIAGNOSEItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.EDIT_DIAGNOSE, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuEDIT_PROCEDUREItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.EDIT_PROCEDURE, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuDELETE_NOTEItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.DELETE_NOTE, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuDELETE_DIAGNOSISItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.DELETE_DIAGNOSIS, sender); } }); this.form.getContextMenus().RefMan.getClinicalNotesMenuDELETE_PROCEDUREItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ClinicalNotesMenu.DELETE_PROCEDURE, sender); } }); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIComponentEngine engine; protected GenForm form; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/forms/clinicalnotescustomcontrol/Handlers.java
Java
agpl-3.0
9,488
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH package ims.clinical.forms.edischargefutureplancomponent; import java.io.Serializable; public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable { private static final long serialVersionUID = 1L; public final STALE_OBJECT_MESSAGEClass STALE_OBJECT_MESSAGE; public final EDISCHARGE_RESULTS_NUM_DAYSClass EDISCHARGE_RESULTS_NUM_DAYS; public ConfigFlags(ims.framework.ConfigFlag configFlags) { super(configFlags); STALE_OBJECT_MESSAGE = new STALE_OBJECT_MESSAGEClass(configFlags); EDISCHARGE_RESULTS_NUM_DAYS = new EDISCHARGE_RESULTS_NUM_DAYSClass(configFlags); } public final class STALE_OBJECT_MESSAGEClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public STALE_OBJECT_MESSAGEClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public String getValue() { return (String)configFlags.get("STALE_OBJECT_MESSAGE"); } } public final class EDISCHARGE_RESULTS_NUM_DAYSClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public EDISCHARGE_RESULTS_NUM_DAYSClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public Integer getValue() { return (Integer)configFlags.get("EDISCHARGE_RESULTS_NUM_DAYS"); } } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/forms/edischargefutureplancomponent/ConfigFlags.java
Java
agpl-3.0
3,347
class ChangeMetricDescriptionToText < ActiveRecord::Migration def change change_column :metrics, :description, :text end end
peterkshultz/gradecraft-development
db/migrate/20150829215357_change_metric_description_to_text.rb
Ruby
agpl-3.0
133
/* * RapidMiner * * Copyright (C) 2001-2013 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.learner.subgroups.hypothesis; import java.io.Serializable; import java.util.Collection; import java.util.LinkedHashMap; import com.rapidminer.example.Example; import com.rapidminer.operator.learner.subgroups.utility.UtilityFunction; import com.rapidminer.tools.Tools; /** * A rule for subgroup discovery. * * @author Tobias Malbrecht */ public class Rule implements Serializable { private static final long serialVersionUID = 1L; Hypothesis hypothesis; Literal prediction; LinkedHashMap<UtilityFunction, Double> utilityMap = new LinkedHashMap<UtilityFunction, Double>(); public Rule(Hypothesis hypothesis, Literal prediction) { this.hypothesis = hypothesis; this.prediction = prediction; } public boolean applicable(Example example) { return hypothesis.applicable(example); } public double getCoveredWeight() { return hypothesis.getCoveredWeight(); } public double getPositiveWeight() { return hypothesis.getPositiveWeight(); } public double getNegativeWeight() { return hypothesis.getCoveredWeight() - hypothesis.getPositiveWeight(); } public double getPredictionWeight() { if (predictsPositive()) { return getPositiveWeight(); } else { return getNegativeWeight(); } } public boolean predictsPositive() { return (prediction.getValue() == prediction.getAttribute().getMapping().getPositiveIndex()); } public double getPrediction() { return prediction.getValue(); } public Hypothesis getHypothesis() { return hypothesis; } public void setUtility(UtilityFunction function, double utility) { utilityMap.put(function, utility); } public double getUtility(Class<? extends UtilityFunction> functionClass) { for (UtilityFunction function : utilityMap.keySet()) { if (function.getClass().equals(functionClass)) { return utilityMap.get(function); } } return Double.NaN; } public UtilityFunction getUtilityFunction(Class<? extends UtilityFunction> functionClass) { for (UtilityFunction function : utilityMap.keySet()) { if (function.getClass().equals(functionClass)) { return function; } } return null; } public Collection<UtilityFunction> getUtilityFunctions() { return utilityMap.keySet(); } @Override public boolean equals(Object object) { if (object == null) { return false; } if (this.getClass() != object.getClass()) { return false; } Rule otherRule = (Rule) object; return (hypothesis.equals(otherRule.hypothesis) && prediction.equals(otherRule.prediction)); } private String utilityString() { StringBuffer stringBuffer = new StringBuffer("["); stringBuffer.append("Pos=" + getPositiveWeight() + ", "); stringBuffer.append("Neg=" + getNegativeWeight() + ", "); stringBuffer.append("Size=" + getCoveredWeight() + ", "); for (UtilityFunction function : utilityMap.keySet()) { stringBuffer.append(function.getAbbreviation() + "=" + Tools.formatIntegerIfPossible(utilityMap.get(function)) + ", "); } stringBuffer.subSequence(0, stringBuffer.length() - 2); stringBuffer.append("]"); return stringBuffer.toString(); } public String toStringScored() { return toString() + " " + utilityString(); } @Override public String toString() { return hypothesis + " --> " + prediction; } public Hypothesis getPremise() { return hypothesis; } public Literal getConclusion() { return prediction; } }
aborg0/RapidMiner-Unuk
src/com/rapidminer/operator/learner/subgroups/hypothesis/Rule.java
Java
agpl-3.0
4,273
/* Open Chord Charts -- Database of free chord charts By: Christophe Benz <contact@openchordcharts.org> Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz https://github.com/openchordcharts/ This file is part of Open Chord Charts. Open Chord Charts 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. Open Chord Charts is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. @flow weak */ import webservices from "./webservices"; function forgetCredentials() { delete sessionStorage.loggedInUsername; global.authEvents.emit("loggedOut"); } function login() { return webservices.login().then((res) => { if (res.login === "ok") { sessionStorage.loggedInUsername = res.username; global.authEvents.emit("loggedIn"); return true; } else { forgetCredentials(); return false; } }); } function logout() { // TODO simplify promises construct return webservices.logout().catch(() => { forgetCredentials(); }).then(() => { forgetCredentials(); }); } module.exports = {login, logout};
openchordcharts/openchordcharts-web-site
src/auth.js
JavaScript
agpl-3.0
1,554
/* * opencog/embodiment/Control/Procedure/ProcedureRepository.cc * * Copyright (C) 2002-2009 Novamente LLC * All Rights Reserved * Author(s): Novamente team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "ProcedureRepository.h" namespace opencog { namespace Procedure { ProcedureRepository::ProcedureRepository(pai::PAI& pai) : builtInRepository(*(new BuiltInProcedureRepository(pai))) { } ProcedureRepository::~ProcedureRepository() { delete &builtInRepository; } bool ProcedureRepository::contains(const std::string& name) const { return comboRepository.contains(name) || builtInRepository.contains(name); } void ProcedureRepository::remove(const std::string& name) { if (comboRepository.contains(name)) { comboRepository.remove(name); } } const GeneralProcedure& ProcedureRepository::get(const std::string& name) const { if (comboRepository.contains(name)) { return comboRepository.get(name); } else { return builtInRepository.get(name); } } void ProcedureRepository::add(const ComboProcedure& cp) { comboRepository.add(cp); } const ComboProcedureRepository& ProcedureRepository::getComboRepository() const { return comboRepository; } const BuiltInProcedureRepository& ProcedureRepository::getBuiltInRepository() const { return builtInRepository; } const char* ProcedureRepository::getId() const { return "ProcedureRepository"; } void ProcedureRepository::saveRepository(FILE* dump) const { comboRepository.saveRepository(dump); } void ProcedureRepository::loadRepository(FILE* dump, HandleMap<Atom *>* conv) { comboRepository.loadRepository(dump, conv); } int ProcedureRepository::loadComboFromStream(std::istream& in) { return comboRepository.loadFromStream(in); } void ProcedureRepository::clear() { comboRepository.clear(); } }} // ~namespace opencog::Procedure
rkarlberg/opencog
opencog/embodiment/Control/Procedure/ProcedureRepository.cc
C++
agpl-3.0
2,590
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import datetime, timedelta from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare from openerp.osv import fields, osv from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ import pytz from openerp import SUPERUSER_ID from openerp.exceptions import UserError class sale_order(osv.osv): _inherit = "sale.order" def _get_default_warehouse(self, cr, uid, context=None): company_id = self.pool.get('res.users')._get_company(cr, uid, context=context) warehouse_ids = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', company_id)], context=context) if not warehouse_ids: return False return warehouse_ids[0] def _get_shipped(self, cr, uid, ids, name, args, context=None): res = {} for sale in self.browse(cr, uid, ids, context=context): group = sale.procurement_group_id if group: res[sale.id] = all([proc.state in ['cancel', 'done'] for proc in group.procurement_ids]) else: res[sale.id] = False return res def _get_orders(self, cr, uid, ids, context=None): res = set() for move in self.browse(cr, uid, ids, context=context): if move.procurement_id and move.procurement_id.sale_line_id: res.add(move.procurement_id.sale_line_id.order_id.id) return list(res) def _get_orders_procurements(self, cr, uid, ids, context=None): res = set() for proc in self.pool.get('procurement.order').browse(cr, uid, ids, context=context): if proc.state =='done' and proc.sale_line_id: res.add(proc.sale_line_id.order_id.id) return list(res) def _get_picking_ids(self, cr, uid, ids, name, args, context=None): res = {} for sale in self.browse(cr, uid, ids, context=context): if not sale.procurement_group_id: res[sale.id] = [] continue res[sale.id] = self.pool.get('stock.picking').search(cr, uid, [('group_id', '=', sale.procurement_group_id.id)], context=context) return res def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): vals = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context) location_id = order.partner_shipping_id.property_stock_customer.id vals['location_id'] = location_id routes = line.route_id and [(4, line.route_id.id)] or [] vals['route_ids'] = routes vals['warehouse_id'] = order.warehouse_id and order.warehouse_id.id or False vals['partner_dest_id'] = order.partner_shipping_id.id vals['invoice_state'] = (order.order_policy == 'picking') and '2binvoiced' or 'none' return vals def _prepare_invoice(self, cr, uid, order, lines, context=None): if context is None: context = {} invoice_vals = super(sale_order, self)._prepare_invoice(cr, uid, order, lines, context=context) invoice_vals['incoterms_id'] = order.incoterm.id or False return invoice_vals def _get_delivery_count(self, cr, uid, ids, field_name, arg, context=None): res = {} for order in self.browse(cr, uid, ids, context=context): res[order.id] = len([picking for picking in order.picking_ids if picking.picking_type_id.code == 'outgoing']) return res _columns = { 'incoterm': fields.many2one('stock.incoterms', 'Incoterms', help="International Commercial Terms are a series of predefined commercial terms used in international transactions."), 'picking_policy': fields.selection([('direct', 'Deliver each product when available'), ('one', 'Deliver all products at once')], 'Shipping Policy', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""Pick 'Deliver each product when available' if you allow partial delivery."""), 'order_policy': fields.selection([ ('manual', 'On Demand'), ('picking', 'On Delivery Order'), ('prepaid', 'Before Delivery'), ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""On demand: A draft invoice can be created from the sales order when needed. \nOn delivery order: A draft invoice can be created from the delivery order when the products have been delivered. \nBefore delivery: A draft invoice is created from the sales order and must be paid before the products can be delivered."""), 'shipped': fields.function(_get_shipped, string='Delivered', type='boolean', store={ 'procurement.order': (_get_orders_procurements, ['state'], 10) }), 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}), 'picking_ids': fields.function(_get_picking_ids, method=True, type='one2many', relation='stock.picking', string='Picking associated to this sale'), 'delivery_count': fields.function(_get_delivery_count, type='integer', string='Delivery Orders'), } _defaults = { 'warehouse_id': _get_default_warehouse, 'picking_policy': 'direct', 'order_policy': 'manual', } def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None): val = {} if warehouse_id: warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context) if warehouse.company_id: val['company_id'] = warehouse.company_id.id return {'value': val} def action_view_delivery(self, cr, uid, ids, context=None): ''' This function returns an action that display existing delivery orders of given sales order ids. It can either be a in a list or in a form view, if there is only one delivery order to show. ''' mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree_all') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] #compute the number of delivery orders to display pick_ids = [] for so in self.browse(cr, uid, ids, context=context): pick_ids += [picking.id for picking in so.picking_ids if picking.picking_type_id.code == 'outgoing'] #choose the view_mode accordingly if len(pick_ids) > 1: result['domain'] = "[('id','in',[" + ','.join(map(str, pick_ids)) + "])]" else: res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_form') result['views'] = [(res and res[1] or False, 'form')] result['res_id'] = pick_ids and pick_ids[0] or False return result def action_invoice_create(self, cr, uid, ids, grouped=False, states=['confirmed', 'done', 'exception'], date_invoice = False, context=None): move_obj = self.pool.get("stock.move") res = super(sale_order,self).action_invoice_create(cr, uid, ids, grouped=grouped, states=states, date_invoice = date_invoice, context=context) for order in self.browse(cr, uid, ids, context=context): if order.order_policy == 'picking': for picking in order.picking_ids: move_obj.write(cr, uid, [x.id for x in picking.move_lines], {'invoice_state': 'invoiced'}, context=context) return res def action_wait(self, cr, uid, ids, context=None): res = super(sale_order, self).action_wait(cr, uid, ids, context=context) for o in self.browse(cr, uid, ids): noprod = self.test_no_product(cr, uid, o, context) if noprod and o.order_policy=='picking': self.write(cr, uid, [o.id], {'order_policy': 'manual'}, context=context) return res def _get_date_planned(self, cr, uid, order, line, start_date, context=None): date_planned = super(sale_order, self)._get_date_planned(cr, uid, order, line, start_date, context=context) date_planned = (date_planned - timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT) return date_planned def _prepare_procurement_group(self, cr, uid, order, context=None): res = super(sale_order, self)._prepare_procurement_group(cr, uid, order, context=None) res.update({'move_type': order.picking_policy}) return res def action_ship_end(self, cr, uid, ids, context=None): super(sale_order, self).action_ship_end(cr, uid, ids, context=context) for order in self.browse(cr, uid, ids, context=context): val = {'shipped': True} if order.state == 'shipping_except': val['state'] = 'progress' if (order.order_policy == 'manual'): for line in order.order_line: if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break res = self.write(cr, uid, [order.id], val) return True def has_stockable_products(self, cr, uid, ids, *args): for order in self.browse(cr, uid, ids): for order_line in order.order_line: if order_line.product_id and order_line.product_id.type in ('product', 'consu'): return True return False class product_product(osv.osv): _inherit = 'product.product' def need_procurement(self, cr, uid, ids, context=None): #when sale/product is installed alone, there is no need to create procurements, but with sale_stock #we must create a procurement for each product that is not a service. for product in self.browse(cr, uid, ids, context=context): if product.type != 'service': return True return super(product_product, self).need_procurement(cr, uid, ids, context=context) class sale_order_line(osv.osv): _inherit = 'sale.order.line' def _number_packages(self, cr, uid, ids, field_name, arg, context=None): res = {} for line in self.browse(cr, uid, ids, context=context): try: res[line.id] = int((line.product_uom_qty+line.product_packaging.qty-0.0001) / line.product_packaging.qty) except: res[line.id] = 1 return res _columns = { 'product_packaging': fields.many2one('product.packaging', 'Packaging'), 'number_packages': fields.function(_number_packages, type='integer', string='Number Packages'), 'route_id': fields.many2one('stock.location.route', 'Route', domain=[('sale_selectable', '=', True)]), 'product_tmpl_id': fields.related('product_id', 'product_tmpl_id', type='many2one', relation='product.template', string='Product Template'), } _defaults = { 'product_packaging': False, } def product_packaging_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, partner_id=False, packaging=False, flag=False, context=None): if not product: return {'value': {'product_packaging': False}} product_obj = self.pool.get('product.product') product_uom_obj = self.pool.get('product.uom') pack_obj = self.pool.get('product.packaging') warning = {} result = {} warning_msgs = '' if flag: res = self.product_id_change(cr, uid, ids, pricelist=pricelist, product=product, qty=qty, uom=uom, partner_id=partner_id, packaging=packaging, flag=False, context=context) warning_msgs = res.get('warning') and res['warning'].get('message', '') or '' products = product_obj.browse(cr, uid, product, context=context) if not products.packaging_ids: packaging = result['product_packaging'] = False if packaging: default_uom = products.uom_id and products.uom_id.id pack = pack_obj.browse(cr, uid, packaging, context=context) q = product_uom_obj._compute_qty(cr, uid, uom, pack.qty, default_uom) # qty = qty - qty % q + q if qty and (q and not (qty % q) == 0): barcode = pack.barcode or _('(n/a)') qty_pack = pack.qty type_ul = pack.ul if not warning_msgs: warn_msg = _("You selected a quantity of %d Units.\n" "But it's not compatible with the selected packaging.\n" "Here is a proposition of quantities according to the packaging:\n" "Barcode: %s Quantity: %s Type of ul: %s") % \ (qty, barcode, qty_pack, type_ul.name) warning_msgs += _("Picking Information ! : ") + warn_msg + "\n\n" warning = { 'title': _('Configuration Error!'), 'message': warning_msgs } result['product_uom_qty'] = qty return {'value': result, 'warning': warning} def product_id_change_with_wh(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, context=None): context = context or {} product_uom_obj = self.pool.get('product.uom') product_obj = self.pool.get('product.product') warehouse_obj = self.pool['stock.warehouse'] warning = {} #UoM False due to hack which makes sure uom changes price, ... in product_id_change res = self.product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=False, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, context=context) if not product: res['value'].update({'product_packaging': False}) return res # set product uom in context to get virtual stock in current uom if 'product_uom' in res.get('value', {}): # use the uom changed by super call context = dict(context, uom=res['value']['product_uom']) elif uom: # fallback on selected context = dict(context, uom=uom) #update of result obtained in super function product_obj = product_obj.browse(cr, uid, product, context=context) res['value'].update({'product_tmpl_id': product_obj.product_tmpl_id.id, 'delay': (product_obj.sale_delay or 0.0)}) # Calling product_packaging_change function after updating UoM res_packing = self.product_packaging_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, packaging, context=context) res['value'].update(res_packing.get('value', {})) warning_msgs = res_packing.get('warning') and res_packing['warning']['message'] or '' if product_obj.type == 'product': #determine if the product is MTO or not (for a further check) isMto = False if warehouse_id: warehouse = warehouse_obj.browse(cr, uid, warehouse_id, context=context) for product_route in product_obj.route_ids: if warehouse.mto_pull_id and warehouse.mto_pull_id.route_id and warehouse.mto_pull_id.route_id.id == product_route.id: isMto = True break else: try: mto_route_id = warehouse_obj._get_mto_route(cr, uid, context=context) except: # if route MTO not found in ir_model_data, we treat the product as in MTS mto_route_id = False if mto_route_id: for product_route in product_obj.route_ids: if product_route.id == mto_route_id: isMto = True break #check if product is available, and if not: raise a warning, but do this only for products that aren't processed in MTO if not isMto: uom_record = False if uom: uom_record = product_uom_obj.browse(cr, uid, uom, context=context) if product_obj.uom_id.category_id.id != uom_record.category_id.id: uom_record = False if not uom_record: uom_record = product_obj.uom_id compare_qty = float_compare(product_obj.virtual_available, qty, precision_rounding=uom_record.rounding) if compare_qty == -1: warn_msg = _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') % \ (qty, uom_record.name, max(0,product_obj.virtual_available), uom_record.name, max(0,product_obj.qty_available), uom_record.name) warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n" #update of warning messages if warning_msgs: warning = { 'title': _('Configuration Error!'), 'message' : warning_msgs } res.update({'warning': warning}) return res class stock_move(osv.osv): _inherit = 'stock.move' def _create_invoice_line_from_vals(self, cr, uid, move, invoice_line_vals, context=None): invoice_line_id = super(stock_move, self)._create_invoice_line_from_vals(cr, uid, move, invoice_line_vals, context=context) if move.procurement_id and move.procurement_id.sale_line_id: sale_line = move.procurement_id.sale_line_id self.pool.get('sale.order.line').write(cr, uid, [sale_line.id], { 'invoice_lines': [(4, invoice_line_id)] }, context=context) self.pool.get('sale.order').write(cr, uid, [sale_line.order_id.id], { 'invoice_ids': [(4, invoice_line_vals['invoice_id'])], }) sale_line_obj = self.pool.get('sale.order.line') invoice_line_obj = self.pool.get('account.invoice.line') sale_line_ids = sale_line_obj.search(cr, uid, [('order_id', '=', move.procurement_id.sale_line_id.order_id.id), ('invoiced', '=', False), '|', ('product_id', '=', False), ('product_id.type', '=', 'service')], context=context) if sale_line_ids: created_lines = sale_line_obj.invoice_line_create(cr, uid, sale_line_ids, context=context) invoice_line_obj.write(cr, uid, created_lines, {'invoice_id': invoice_line_vals['invoice_id']}, context=context) return invoice_line_id def _get_master_data(self, cr, uid, move, company, context=None): if move.procurement_id and move.procurement_id.sale_line_id and move.procurement_id.sale_line_id.order_id.order_policy == 'picking': sale_order = move.procurement_id.sale_line_id.order_id return sale_order.partner_invoice_id, sale_order.user_id.id, sale_order.pricelist_id.currency_id.id elif move.picking_id.sale_id: # In case of extra move, it is better to use the same data as the original moves sale_order = move.picking_id.sale_id return sale_order.partner_invoice_id, sale_order.user_id.id, sale_order.pricelist_id.currency_id.id return super(stock_move, self)._get_master_data(cr, uid, move, company, context=context) def _get_invoice_line_vals(self, cr, uid, move, partner, inv_type, context=None): res = super(stock_move, self)._get_invoice_line_vals(cr, uid, move, partner, inv_type, context=context) if move.procurement_id and move.procurement_id.sale_line_id: sale_line = move.procurement_id.sale_line_id res['invoice_line_tax_id'] = [(6, 0, [x.id for x in sale_line.tax_id])] res['account_analytic_id'] = sale_line.order_id.project_id and sale_line.order_id.project_id.id or False res['discount'] = sale_line.discount if move.product_id.id != sale_line.product_id.id: res['price_unit'] = self.pool['product.pricelist'].price_get( cr, uid, [sale_line.order_id.pricelist_id.id], move.product_id.id, move.product_uom_qty or 1.0, sale_line.order_id.partner_id, context=context)[sale_line.order_id.pricelist_id.id] else: res['price_unit'] = sale_line.price_unit uos_coeff = move.product_uom_qty and move.product_uos_qty / move.product_uom_qty or 1.0 res['price_unit'] = res['price_unit'] / uos_coeff return res class stock_location_route(osv.osv): _inherit = "stock.location.route" _columns = { 'sale_selectable': fields.boolean("Selectable on Sales Order Line") } class stock_picking(osv.osv): _inherit = "stock.picking" def _get_partner_to_invoice(self, cr, uid, picking, context=None): """ Inherit the original function of the 'stock' module We select the partner of the sales order as the partner of the customer invoice """ saleorder_ids = self.pool['sale.order'].search(cr, uid, [('procurement_group_id' ,'=', picking.group_id.id)], context=context) saleorders = self.pool['sale.order'].browse(cr, uid, saleorder_ids, context=context) if saleorders and saleorders[0] and saleorders[0].order_policy == 'picking': saleorder = saleorders[0] return saleorder.partner_invoice_id.id return super(stock_picking, self)._get_partner_to_invoice(cr, uid, picking, context=context) def _get_sale_id(self, cr, uid, ids, name, args, context=None): sale_obj = self.pool.get("sale.order") res = {} for picking in self.browse(cr, uid, ids, context=context): res[picking.id] = False if picking.group_id: sale_ids = sale_obj.search(cr, uid, [('procurement_group_id', '=', picking.group_id.id)], context=context) if sale_ids: res[picking.id] = sale_ids[0] return res _columns = { 'sale_id': fields.function(_get_sale_id, type="many2one", relation="sale.order", string="Sale Order"), } def _create_invoice_from_picking(self, cr, uid, picking, vals, context=None): sale_obj = self.pool.get('sale.order') sale_line_obj = self.pool.get('sale.order.line') invoice_line_obj = self.pool.get('account.invoice.line') invoice_id = super(stock_picking, self)._create_invoice_from_picking(cr, uid, picking, vals, context=context) return invoice_id def _get_invoice_vals(self, cr, uid, key, inv_type, journal_id, move, context=None): inv_vals = super(stock_picking, self)._get_invoice_vals(cr, uid, key, inv_type, journal_id, move, context=context) sale = move.picking_id.sale_id if sale: inv_vals.update({ 'fiscal_position': sale.fiscal_position.id, 'payment_term': sale.payment_term.id, 'user_id': sale.user_id.id, 'team_id': sale.team_id.id, 'name': sale.client_order_ref or '', }) return inv_vals class account_invoice(osv.Model): _inherit = 'account.invoice' _columns = { 'incoterms_id': fields.many2one( 'stock.incoterms', "Incoterms", help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices.", readonly=True, states={'draft': [('readonly', False)]}), } class sale_advance_payment_inv(osv.TransientModel): _inherit = 'sale.advance.payment.inv' def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None): result = super(sale_advance_payment_inv,self)._prepare_advance_invoice_vals(cr, uid, ids, context=context) if context is None: context = {} sale_obj = self.pool.get('sale.order') sale_ids = context.get('active_ids', []) res = [] for sale in sale_obj.browse(cr, uid, sale_ids, context=context): elem = filter(lambda t: t[0] == sale.id, result)[0] elem[1]['incoterms_id'] = sale.incoterm.id or False res.append(elem) return res class procurement_order(osv.osv): _inherit = "procurement.order" def _run_move_create(self, cr, uid, procurement, context=None): vals = super(procurement_order, self)._run_move_create(cr, uid, procurement, context=context) #copy the sequence from the sale order line on the stock move if procurement.sale_line_id: vals.update({'sequence': procurement.sale_line_id.sequence}) return vals
addition-it-solutions/project-all
addons/sale_stock/sale_stock.py
Python
agpl-3.0
26,655
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using Chraft.Entity.Items; using Chraft.Interfaces; using Chraft.Utilities; using Chraft.Utilities.Blocks; using Chraft.World.Blocks.Base; namespace Chraft.World.Blocks { class BlockIronBlock : BlockBase { public BlockIronBlock() { Name = "IronBlock"; Type = BlockData.Blocks.Iron_Block; IsSolid = true; var item = ItemHelper.GetInstance(Type); item.Count = 1; LootTable.Add(item); } } }
chraft/c-raft
Chraft/World/Blocks/BlockIronBlock.cs
C#
agpl-3.0
1,256
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {bool, node, oneOf} from 'prop-types' import {Alert} from '@instructure/ui-alerts' import {ScreenReaderContent} from '@instructure/ui-a11y-content' CanvasInlineAlert.propTypes = { liveAlert: bool, screenReaderOnly: bool, politeness: oneOf(['assertive', 'polite']), children: node } export default function CanvasInlineAlert({ children, liveAlert, screenReaderOnly, politeness = 'assertive', ...alertProps }) { let body = children if (liveAlert || screenReaderOnly) { body = ( <span role="alert" aria-live={politeness} aria-atomic> {body} </span> ) } if (screenReaderOnly) { body = <ScreenReaderContent>{body}</ScreenReaderContent> } return <Alert {...alertProps}>{body}</Alert> }
djbender/canvas-lms
app/jsx/shared/components/CanvasInlineAlert.js
JavaScript
agpl-3.0
1,478
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.forms.patientreferralstatuslist; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void onMessageBoxClosed(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onDyngrdReferralsCellButtonClicked(ims.framework.controls.DynamicGridCell cell); abstract protected void onDyngrdReferralsRowSelectionChanged(ims.framework.controls.DynamicGridRow row) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setMessageBoxClosedEvent(new MessageBoxClosed() { private static final long serialVersionUID = 1L; public void handle(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onMessageBoxClosed(messageBoxId, result); } }); this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { onFormOpen(args); } }); this.form.setFormDialogClosedEvent(new FormDialogClosed() { private static final long serialVersionUID = 1L; public void handle(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onFormDialogClosed(formName, result); } }); this.form.dyngrdReferrals().setDynamicGridCellButtonClickedEvent(new DynamicGridCellButtonClicked() { private static final long serialVersionUID = 1L; public void handle(ims.framework.controls.DynamicGridCell cell) throws ims.framework.exceptions.PresentationLogicException { onDyngrdReferralsCellButtonClicked(cell); } }); this.form.dyngrdReferrals().setDynamicGridRowSelectionChangedEvent(new DynamicGridRowSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.controls.DynamicGridRow row, ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onDyngrdReferralsRowSelectionChanged(row); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuViewDemographicsItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ViewDemographics, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuNewReferralWizardItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.NewReferralWizard, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuViewReferralDetailsItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ViewReferralDetails, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuEDIT_REFERRAL_DETAILSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.EDIT_REFERRAL_DETAILS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuPresentationItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.Presentation, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuAtConsultationItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.AtConsultation, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuCALL_ATTEMPTSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.CALL_ATTEMPTS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuReviewRejectedInvestigationsItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ReviewRejectedInvestigations, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuVIEW_REJECTION_DETAILSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.VIEW_REJECTION_DETAILS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuFlagForReviewItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.FlagForReview, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuReviewFlagForReviewDetailItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ReviewFlagForReviewDetail, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuNewProviderCancellationItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.NewProviderCancellation, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuEditProviderCancellationItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.EditProviderCancellation, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuNEWREJECTEDONWARDREFERRALItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.NEWREJECTEDONWARDREFERRAL, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuEDITREJECTONWARDREFERRALDETAILSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.EDITREJECTONWARDREFERRALDETAILS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuStartConsultantContactItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.StartConsultantContact, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuStartClinicalContactItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.StartClinicalContact, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuStartTLTContactItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.StartTLTContact, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuEditConsultationDetailsItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.EditConsultationDetails, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuNEWONWARDREFERRALItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.NEWONWARDREFERRAL, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuViewConsultationDetailsItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ViewConsultationDetails, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuEND_TLT_CONTACTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.END_TLT_CONTACT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuViewRejectedReferralDetailsItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ViewRejectedReferralDetails, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuBOOK_THEATRE_APPTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.BOOK_THEATRE_APPT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuReAdmitPatientItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ReAdmitPatient, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuREJECTED_ON_CABItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.REJECTED_ON_CAB, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuPATIENT_REJ_LETTER_SENTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.PATIENT_REJ_LETTER_SENT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuREF_IS_PROV_CANC_ON_CABItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.REF_IS_PROV_CANC_ON_CAB, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuDOC_SENT_TO_PATIENTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.DOC_SENT_TO_PATIENT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuVIEW_DISCHARGE_SUMMARY_DETAILSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.VIEW_DISCHARGE_SUMMARY_DETAILS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuREVIEW_SUITABLE_FOR_SURGERYItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.REVIEW_SUITABLE_FOR_SURGERY, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuREVIEW_FITItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.REVIEW_FIT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuRESET_PROVEIDER_CANCELLATIONItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.RESET_PROVEIDER_CANCELLATION, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuRESET_REJECT_REFERRALItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.RESET_REJECT_REFERRAL, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuUNDO_PROVIDER_CANCELLATIONItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.UNDO_PROVIDER_CANCELLATION, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuUNDO_REFERRAL_REJECTIONItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.UNDO_REFERRAL_REJECTION, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuEND_OF_CAREItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.END_OF_CARE, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuPOST_OP_CONTACTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.POST_OP_CONTACT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuREMOVE_FROM_24HOURItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.REMOVE_FROM_24HOUR, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuREMOVE_FROM_CATS_ONWARD_REFERRAL_WORKLISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.REMOVE_FROM_CATS_ONWARD_REFERRAL_WORKLIST, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuUNDO_END_OF_CAREItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.UNDO_END_OF_CARE, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuNEW_WAITING_LIST_ENTRYItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.NEW_WAITING_LIST_ENTRY, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuADD_TO_WAITING_LISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ADD_TO_WAITING_LIST, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuADD_TO_BOOKED_LISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ADD_TO_BOOKED_LIST, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuADD_TO_PLANNED_LISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.ADD_TO_PLANNED_LIST, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuVIEW_EDIT_ELECTIVE_LIST_DETAILSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.VIEW_EDIT_ELECTIVE_LIST_DETAILS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuRECORD_ADMIN_EVENTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.RECORD_ADMIN_EVENT, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuVIEW_ADMIN_EVENTSItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.VIEW_ADMIN_EVENTS, sender); } }); this.form.getContextMenus().RefMan.getReferralStatusListMenuBOOK_APPOINTMENTItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.RefManNamespace.ReferralStatusListMenu.BOOK_APPOINTMENT, sender); } }); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIEngine engine; protected GenForm form; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/forms/patientreferralstatuslist/Handlers.java
Java
agpl-3.0
27,526
<?php namespace App\Http\Controllers; use enshrined\svgSanitize\Sanitizer; use App\Helpers\Helper; use App\Http\Requests\ImageUploadRequest; use App\Http\Requests\SettingsSamlRequest; use App\Http\Requests\SetupUserRequest; use App\Models\Setting; use App\Models\Asset; use App\Models\User; use App\Notifications\FirstAdminNotification; use App\Notifications\MailTest; use Artisan; use Auth; use Crypt; use DB; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Image; use Input; use Redirect; use Response; use App\Helpers\StorageHelper; use App\Http\Requests\SlackSettingsRequest; /** * This controller handles all actions related to Settings for * the Snipe-IT Asset Management application. * * @version v1.0 */ class SettingsController extends Controller { /** * Checks to see whether or not the database has a migrations table * and a user, otherwise display the setup view. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return View */ public function getSetupIndex() { $start_settings['php_version_min'] = false; if (version_compare(PHP_VERSION, config('app.min_php'), '<')) { return response('<center><h1>This software requires PHP version ' . config('app.min_php') . ' or greater. This server is running ' . PHP_VERSION . '. </h1><h2>Please upgrade PHP on this server and try again. </h2></center>', 500); } try { $conn = DB::select('select 2 + 2'); $start_settings['db_conn'] = true; $start_settings['db_name'] = DB::connection()->getDatabaseName(); $start_settings['db_error'] = null; } catch (\PDOException $e) { $start_settings['db_conn'] = false; $start_settings['db_name'] = config('database.connections.mysql.database'); $start_settings['db_error'] = $e->getMessage(); } $protocol = array_key_exists('HTTPS', $_SERVER) && ('on' == $_SERVER['HTTPS']) ? 'https://' : 'http://'; $host = array_key_exists('SERVER_NAME', $_SERVER) ? $_SERVER['SERVER_NAME'] : null; $port = array_key_exists('SERVER_PORT', $_SERVER) ? $_SERVER['SERVER_PORT'] : null; if (('http://' === $protocol && '80' != $port) || ('https://' === $protocol && '443' != $port)) { $host .= ':' . $port; } $pageURL = $protocol . $host . $_SERVER['REQUEST_URI']; $start_settings['url_valid'] = (url('/') . '/setup' === $pageURL); $start_settings['url_config'] = url('/'); $start_settings['real_url'] = $pageURL; $start_settings['php_version_min'] = true; // Curl the .env file to make sure it's not accessible via a browser $ch = curl_init($protocol . $host . '/.env'); curl_setopt($ch, CURLOPT_HEADER, true); // we want headers curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (404 == $httpcode || 403 == $httpcode || 0 == $httpcode) { $start_settings['env_exposed'] = false; } else { $start_settings['env_exposed'] = true; } if (\App::Environment('production') && (true == config('app.debug'))) { $start_settings['debug_exposed'] = true; } else { $start_settings['debug_exposed'] = false; } $environment = app()->environment(); if ('production' != $environment) { $start_settings['env'] = $environment; $start_settings['prod'] = false; } else { $start_settings['env'] = $environment; $start_settings['prod'] = true; } if (function_exists('posix_getpwuid')) { // Probably Linux $owner = posix_getpwuid(fileowner($_SERVER['SCRIPT_FILENAME'])); $start_settings['owner'] = $owner['name']; } else { // Windows // TODO: Is there a way of knowing if a windows user has elevated permissions // This just gets the user name, which likely isn't 'root' // $start_settings['owner'] = getenv('USERNAME'); $start_settings['owner'] = ''; } if (('root' === $start_settings['owner']) || ('0' === $start_settings['owner'])) { $start_settings['owner_is_admin'] = true; } else { $start_settings['owner_is_admin'] = false; } if ((is_writable(storage_path())) && (is_writable(storage_path() . '/framework')) && (is_writable(storage_path() . '/framework/cache')) && (is_writable(storage_path() . '/framework/sessions')) && (is_writable(storage_path() . '/framework/views')) && (is_writable(storage_path() . '/logs')) ) { $start_settings['writable'] = true; } else { $start_settings['writable'] = false; } $start_settings['gd'] = extension_loaded('gd'); return view('setup/index') ->with('step', 1) ->with('start_settings', $start_settings) ->with('section', 'Pre-Flight Check'); } /** * Save the first admin user from Setup. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return Redirect */ public function postSaveFirstAdmin(SetupUserRequest $request) { $user = new User(); $user->first_name = $data['first_name'] = $request->input('first_name'); $user->last_name = $request->input('last_name'); $user->email = $data['email'] = $request->input('email'); $user->activated = 1; $permissions = ['superuser' => 1]; $user->permissions = json_encode($permissions); $user->username = $data['username'] = $request->input('username'); $user->password = bcrypt($request->input('password')); $data['password'] = $request->input('password'); $settings = new Setting(); $settings->full_multiple_companies_support = $request->input('full_multiple_companies_support', 0); $settings->site_name = $request->input('site_name'); $settings->alert_email = $request->input('email'); $settings->alerts_enabled = 1; $settings->pwd_secure_min = 10; $settings->brand = 1; $settings->locale = $request->input('locale', 'en'); $settings->default_currency = $request->input('default_currency', 'USD'); $settings->user_id = 1; $settings->email_domain = $request->input('email_domain'); $settings->email_format = $request->input('email_format'); $settings->next_auto_tag_base = 1; $settings->auto_increment_assets = $request->input('auto_increment_assets', 0); $settings->auto_increment_prefix = $request->input('auto_increment_prefix'); if ((! $user->isValid()) || (! $settings->isValid())) { return redirect()->back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors()); } else { $user->save(); Auth::login($user, true); $settings->save(); if ($request->input('email_creds') == '1') { $data = []; $data['email'] = $user->email; $data['username'] = $user->username; $data['first_name'] = $user->first_name; $data['last_name'] = $user->last_name; $data['password'] = $request->input('password'); $user->notify(new FirstAdminNotification($data)); } return redirect()->route('setup.done'); } } /** * Return the admin user creation form in Setup. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return View */ public function getSetupUser() { return view('setup/user') ->with('step', 3) ->with('section', 'Create a User'); } /** * Return the view that tells the user that the Setup is done. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return View */ public function getSetupDone() { return view('setup/done') ->with('step', 4) ->with('section', 'Done!'); } /** * Migrate the database tables, and return the output * to a view for Setup. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return View */ public function getSetupMigrate() { Artisan::call('migrate', ['--force' => true]); if ((! file_exists(storage_path() . '/oauth-private.key')) || (! file_exists(storage_path() . '/oauth-public.key'))) { Artisan::call('migrate', ['--path' => 'vendor/laravel/passport/database/migrations', '--force' => true]); Artisan::call('passport:install'); } return view('setup/migrate') ->with('output', 'Databases installed!') ->with('step', 2) ->with('section', 'Create Database Tables'); } /** * Return a view that shows some of the key settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function index() { $settings = Setting::getSettings(); return view('settings/index', compact('settings')); } /** * Return the admin settings page. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getEdit() { $setting = Setting::getSettings(); return view('settings/general', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getSettings() { $setting = Setting::getSettings(); return view('settings/general', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postSettings(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->modellist_displays = ''; if (($request->filled('show_in_model_list')) && (count($request->input('show_in_model_list')) > 0)) { $setting->modellist_displays = implode(',', $request->input('show_in_model_list')); } $setting->full_multiple_companies_support = $request->input('full_multiple_companies_support', '0'); $setting->unique_serial = $request->input('unique_serial', '0'); $setting->show_images_in_email = $request->input('show_images_in_email', '0'); $setting->show_archived_in_list = $request->input('show_archived_in_list', '0'); $setting->dashboard_message = $request->input('dashboard_message'); $setting->email_domain = $request->input('email_domain'); $setting->email_format = $request->input('email_format'); $setting->username_format = $request->input('username_format'); $setting->require_accept_signature = $request->input('require_accept_signature'); $setting->show_assigned_assets = $request->input('show_assigned_assets', '0'); if (! config('app.lock_passwords')) { $setting->login_note = $request->input('login_note'); } $setting->default_eula_text = $request->input('default_eula_text'); $setting->thumbnail_max_h = $request->input('thumbnail_max_h'); $setting->privacy_policy_link = $request->input('privacy_policy_link'); $setting->depreciation_method = $request->input('depreciation_method'); if ($request->input('per_page') != '') { $setting->per_page = $request->input('per_page'); } else { $setting->per_page = 200; } if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getBranding() { $setting = Setting::getSettings(); return view('settings.branding', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postBranding(ImageUploadRequest $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->brand = $request->input('brand', '1'); $setting->header_color = $request->input('header_color'); $setting->support_footer = $request->input('support_footer'); $setting->version_footer = $request->input('version_footer'); $setting->footer_text = $request->input('footer_text'); $setting->skin = $request->input('skin'); $setting->allow_user_skin = $request->input('allow_user_skin'); $setting->show_url_in_emails = $request->input('show_url_in_emails', '0'); $setting->logo_print_assets = $request->input('logo_print_assets', '0'); // Only allow the site name and CSS to be changed if lock_passwords is false // Because public demos make people act like dicks if (! config('app.lock_passwords')) { $setting->site_name = $request->input('site_name'); $setting->custom_css = $request->input('custom_css'); } $setting = $request->handleImages($setting,600,'logo','', 'logo'); if ('1' == $request->input('clear_logo')) { Storage::disk('public')->delete($setting->logo); $setting->logo = null; $setting->brand = 1; } $setting = $request->handleImages($setting,600,'email_logo','', 'email_logo'); if ('1' == $request->input('clear_email_logo')) { Storage::disk('public')->delete($setting->email_logo); $setting->email_logo = null; // If they are uploading an image, validate it and upload it } $setting = $request->handleImages($setting,600,'label_logo','', 'label_logo'); if ('1' == $request->input('clear_label_logo')) { Storage::disk('public')->delete($setting->label_logo); $setting->label_logo = null; } // If the user wants to clear the favicon... if ($request->hasFile('favicon')) { $favicon_image = $favicon_upload = $request->file('favicon'); $favicon_ext = $favicon_image->getClientOriginalExtension(); $setting->favicon = $favicon_file_name = 'favicon-uploaded.' . $favicon_ext; if (($favicon_image->getClientOriginalExtension()!='ico') && ($favicon_image->getClientOriginalExtension()!='svg')) { $favicon_upload = Image::make($favicon_image->getRealPath())->resize(null, 36, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); // This requires a string instead of an object, so we use ($string) Storage::disk('public')->put($favicon_file_name, (string) $favicon_upload->encode()); } else { Storage::disk('public')->put($favicon_file_name, file_get_contents($request->file('favicon'))); } // Remove Current image if exists if (($setting->favicon) && (file_exists($favicon_file_name))) { Storage::disk('public')->delete($favicon_file_name); } } elseif ('1' == $request->input('clear_favicon')) { Storage::disk('public')->delete($setting->clear_favicon); $setting->favicon = null; // If they are uploading an image, validate it and upload it } if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getSecurity() { $setting = Setting::getSettings(); return view('settings.security', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postSecurity(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } if (! config('app.lock_passwords')) { if ('' == $request->input('two_factor_enabled')) { $setting->two_factor_enabled = null; } else { $setting->two_factor_enabled = $request->input('two_factor_enabled'); } // remote user login $setting->login_remote_user_enabled = (int) $request->input('login_remote_user_enabled'); $setting->login_common_disabled = (int) $request->input('login_common_disabled'); $setting->login_remote_user_custom_logout_url = $request->input('login_remote_user_custom_logout_url'); $setting->login_remote_user_header_name = $request->input('login_remote_user_header_name'); } $setting->pwd_secure_uncommon = (int) $request->input('pwd_secure_uncommon'); $setting->pwd_secure_min = (int) $request->input('pwd_secure_min'); $setting->pwd_secure_complexity = ''; if ($request->filled('pwd_secure_complexity')) { $setting->pwd_secure_complexity = implode('|', $request->input('pwd_secure_complexity')); } if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getLocalization() { $setting = Setting::getSettings(); return view('settings.localization', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postLocalization(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } if (! config('app.lock_passwords')) { $setting->locale = $request->input('locale', 'en'); } $setting->default_currency = $request->input('default_currency', '$'); $setting->date_display_format = $request->input('date_display_format'); $setting->time_display_format = $request->input('time_display_format'); $setting->digit_separator = $request->input('digit_separator'); if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getAlerts() { $setting = Setting::getSettings(); return view('settings.alerts', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postAlerts(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } // Check if the audit interval has changed - if it has, we want to update ALL of the assets audit dates if ($request->input('audit_interval') != $setting->audit_interval) { // Be careful - this could be a negative number $audit_diff_months = ((int)$request->input('audit_interval') - (int)($setting->audit_interval)); // Grab all of the assets that have an existing next_audit_date $assets = Asset::whereNotNull('next_audit_date')->get(); // Update all of the assets' next_audit_date values foreach ($assets as $asset) { if ($asset->next_audit_date != '') { $old_next_audit = new \DateTime($asset->next_audit_date); $asset->next_audit_date = $old_next_audit->modify($audit_diff_months.' month')->format('Y-m-d'); $asset->forceSave(); } } } $alert_email = rtrim($request->input('alert_email'), ','); $alert_email = trim($alert_email); $admin_cc_email = rtrim($request->input('admin_cc_email'), ','); $admin_cc_email = trim($admin_cc_email); $setting->alert_email = $alert_email; $setting->admin_cc_email = $admin_cc_email; $setting->alerts_enabled = $request->input('alerts_enabled', '0'); $setting->alert_interval = $request->input('alert_interval'); $setting->alert_threshold = $request->input('alert_threshold'); $setting->audit_interval = $request->input('audit_interval'); $setting->audit_warning_days = $request->input('audit_warning_days'); $setting->show_alerts_in_menu = $request->input('show_alerts_in_menu', '0'); if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getSlack() { $setting = Setting::getSettings(); return view('settings.slack', compact('setting')); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postSlack(SlackSettingsRequest $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->slack_endpoint = $request->input('slack_endpoint'); $setting->slack_channel = $request->input('slack_channel'); $setting->slack_botname = $request->input('slack_botname'); if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getAssetTags() { $setting = Setting::getSettings(); return view('settings.asset_tags', compact('setting')); } /** * Saves settings from form. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postAssetTags(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->auto_increment_prefix = $request->input('auto_increment_prefix'); $setting->auto_increment_assets = $request->input('auto_increment_assets', '0'); $setting->zerofill_count = $request->input('zerofill_count'); $setting->next_auto_tag_base = $request->input('next_auto_tag_base'); if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function getBarcodes() { $setting = Setting::getSettings(); $is_gd_installed = extension_loaded('gd'); return view('settings.barcodes', compact('setting'))->with('is_gd_installed', $is_gd_installed); } /** * Saves settings from form. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.0] * * @return View */ public function postBarcodes(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->qr_code = $request->input('qr_code', '0'); $setting->alt_barcode = $request->input('alt_barcode'); $setting->alt_barcode_enabled = $request->input('alt_barcode_enabled', '0'); $setting->barcode_type = $request->input('barcode_type'); $setting->qr_text = $request->input('qr_text'); if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function getPhpInfo() { if (true === config('app.debug')) { return view('settings.phpinfo'); } return redirect()->route('settings.index') ->with('error', 'PHP syetem debugging information is only available when debug is enabled in your .env file.'); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function getLabels() { $setting = Setting::getSettings(); return view('settings.labels', compact('setting')); } /** * Saves settings from form. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function postLabels(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->labels_per_page = $request->input('labels_per_page'); $setting->labels_width = $request->input('labels_width'); $setting->labels_height = $request->input('labels_height'); $setting->labels_pmargin_left = $request->input('labels_pmargin_left'); $setting->labels_pmargin_right = $request->input('labels_pmargin_right'); $setting->labels_pmargin_top = $request->input('labels_pmargin_top'); $setting->labels_pmargin_bottom = $request->input('labels_pmargin_bottom'); $setting->labels_display_bgutter = $request->input('labels_display_bgutter'); $setting->labels_display_sgutter = $request->input('labels_display_sgutter'); $setting->labels_fontsize = $request->input('labels_fontsize'); $setting->labels_pagewidth = $request->input('labels_pagewidth'); $setting->labels_pageheight = $request->input('labels_pageheight'); $setting->labels_display_company_name = $request->input('labels_display_company_name', '0'); $setting->labels_display_company_name = $request->input('labels_display_company_name', '0'); if ($request->filled('labels_display_name')) { $setting->labels_display_name = 1; } else { $setting->labels_display_name = 0; } if ($request->filled('labels_display_serial')) { $setting->labels_display_serial = 1; } else { $setting->labels_display_serial = 0; } if ($request->filled('labels_display_tag')) { $setting->labels_display_tag = 1; } else { $setting->labels_display_tag = 0; } if ($request->filled('labels_display_tag')) { $setting->labels_display_tag = 1; } else { $setting->labels_display_tag = 0; } if ($request->filled('labels_display_model')) { $setting->labels_display_model = 1; } else { $setting->labels_display_model = 0; } if ($setting->save()) { return redirect()->route('settings.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function getLdapSettings() { $setting = Setting::getSettings(); return view('settings.ldap', compact('setting')); } /** * Saves settings from form. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function postLdapSettings(Request $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } if (!config('app.lock_passwords')===true) { $setting->ldap_enabled = $request->input('ldap_enabled', '0'); $setting->ldap_server = $request->input('ldap_server'); $setting->ldap_server_cert_ignore = $request->input('ldap_server_cert_ignore', false); $setting->ldap_uname = $request->input('ldap_uname'); if ($request->filled('ldap_pword')) { $setting->ldap_pword = Crypt::encrypt($request->input('ldap_pword')); } $setting->ldap_basedn = $request->input('ldap_basedn'); $setting->ldap_filter = $request->input('ldap_filter'); $setting->ldap_username_field = $request->input('ldap_username_field'); $setting->ldap_lname_field = $request->input('ldap_lname_field'); $setting->ldap_fname_field = $request->input('ldap_fname_field'); $setting->ldap_auth_filter_query = $request->input('ldap_auth_filter_query'); $setting->ldap_version = $request->input('ldap_version'); $setting->ldap_active_flag = $request->input('ldap_active_flag'); $setting->ldap_emp_num = $request->input('ldap_emp_num'); $setting->ldap_email = $request->input('ldap_email'); $setting->ad_domain = $request->input('ad_domain'); $setting->is_ad = $request->input('is_ad', '0'); $setting->ad_append_domain = $request->input('ad_append_domain', '0'); $setting->ldap_tls = $request->input('ldap_tls', '0'); $setting->ldap_pw_sync = $request->input('ldap_pw_sync', '0'); $setting->custom_forgot_pass_url = $request->input('custom_forgot_pass_url'); $setting->ldap_phone_field = $request->input('ldap_phone'); $setting->ldap_jobtitle = $request->input('ldap_jobtitle'); $setting->ldap_country = $request->input('ldap_country'); $setting->ldap_dept = $request->input('ldap_dept'); $setting->ldap_client_tls_cert = $request->input('ldap_client_tls_cert'); $setting->ldap_client_tls_key = $request->input('ldap_client_tls_key'); } if ($setting->save()) { $setting->update_client_side_cert_files(); return redirect()->route('settings.ldap.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Return a form to allow a super admin to update settings. * * @author Johnson Yi <jyi.dev@outlook.com> * * @since v5.0.0 * * @return View */ public function getSamlSettings() { $setting = Setting::getSettings(); return view('settings.saml', compact('setting')); } /** * Saves settings from form. * * @author Johnson Yi <jyi.dev@outlook.com> * * @since v5.0.0 * * @return View */ public function postSamlSettings(SettingsSamlRequest $request) { if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } $setting->saml_enabled = $request->input('saml_enabled', '0'); $setting->saml_idp_metadata = $request->input('saml_idp_metadata'); $setting->saml_attr_mapping_username = $request->input('saml_attr_mapping_username'); $setting->saml_forcelogin = $request->input('saml_forcelogin', '0'); $setting->saml_slo = $request->input('saml_slo', '0'); if (!empty($request->input('saml_sp_privatekey'))) { $setting->saml_sp_x509cert = $request->input('saml_sp_x509cert'); $setting->saml_sp_privatekey = $request->input('saml_sp_privatekey'); } if (!empty($request->input('saml_sp_x509certNew'))) { $setting->saml_sp_x509certNew = $request->input('saml_sp_x509certNew'); } else { $setting->saml_sp_x509certNew = ""; } $setting->saml_custom_settings = $request->input('saml_custom_settings'); if ($setting->save()) { return redirect()->route('settings.saml.index') ->with('success', trans('admin/settings/message.update.success')); } return redirect()->back()->withInput()->withErrors($setting->getErrors()); } /** * Show the listing of backups. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.8] * * @return View */ public function getBackups() { $path = 'app/backups'; $backup_files = Storage::files($path); $files_raw = []; if (count($backup_files) > 0) { for ($f = 0; $f < count($backup_files); ++$f) { // Skip dotfiles like .gitignore and .DS_STORE if ((substr(basename($backup_files[$f]), 0, 1) != '.')) { $files_raw[] = [ 'filename' => basename($backup_files[$f]), 'filesize' => Setting::fileSizeConvert(Storage::size($backup_files[$f])), 'modified' => Storage::lastModified($backup_files[$f]), ]; } } } // Reverse the array so it lists oldest first $files = array_reverse($files_raw); return view('settings/backups', compact('path', 'files')); } /** * Process the backup. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.8] * * @return Redirect */ public function postBackups() { if (! config('app.lock_passwords')) { Artisan::call('backup:run'); $output = Artisan::output(); // Backup completed if (! preg_match('/failed/', $output)) { return redirect()->route('settings.backups.index') ->with('success', trans('admin/settings/message.backup.generated')); } $formatted_output = str_replace('Backup completed!', '', $output); $output_split = explode('...', $formatted_output); if (array_key_exists(2, $output_split)) { return redirect()->route('settings.backups.index')->with('error', $output_split[2]); } return redirect()->route('settings.backups.index')->with('error', $formatted_output); } return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled')); } /** * Download the backup file. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.8] * * @return Storage */ public function downloadFile($filename = null) { $path = 'app/backups'; if (! config('app.lock_passwords')) { if (Storage::exists($path . '/' . $filename)) { return StorageHelper::downloader($path . '/' . $filename); } else { // Redirect to the backup page return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found')); } } else { // Redirect to the backup page return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled')); } } /** * Delete the backup file. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v1.8] * * @return View */ public function deleteFile($filename = null) { if (! config('app.lock_passwords')) { $path = 'app/backups'; if (Storage::exists($path . '/' . $filename)) { try { Storage::delete($path . '/' . $filename); return redirect()->route('settings.backups.index')->with('success', trans('admin/settings/message.backup.file_deleted')); } catch (\Exception $e) { \Log::debug($e); } } else { return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found')); } } else { return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled')); } } /** * Return a form to allow a super admin to update settings. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function getPurge() { \Log::warning('User ID '.Auth::user()->id.' is attempting a PURGE'); return view('settings.purge-form'); } /** * Purges soft-deletes. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return View */ public function postPurge(Request $request) { if (! config('app.lock_passwords')) { if ('DELETE' == $request->input('confirm_purge')) { \Log::warning('User ID '.Auth::user()->id.' initiated a PURGE!'); // Run a backup immediately before processing Artisan::call('backup:run'); Artisan::call('snipeit:purge', ['--force' => 'true', '--no-interaction' => true]); $output = Artisan::output(); return view('settings/purge') ->with('output', $output)->with('success', trans('admin/settings/message.purge.success')); } else { return redirect()->back()->with('error', trans('admin/settings/message.purge.validation_failed')); } } else { return redirect()->back()->with('error', trans('general.feature_disabled')); } } /** * Returns a page with the API token generation interface. * * We created a controller method for this because closures aren't allowed * in the routes file if you want to be able to cache the routes. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v4.0] * * @return View */ public function api() { return view('settings.api'); } /** * Test the email configuration. * * @author [A. Gianotto] [<snipe@snipe.net>] * * @since [v3.0] * * @return Redirect */ public function ajaxTestEmail() { try { (new User())->forceFill([ 'name' => config('mail.from.name'), 'email' => config('mail.from.address'), ])->notify(new MailTest()); return response()->json(Helper::formatStandardApiResponse('success', null, 'Maiol sent!')); } catch (Exception $e) { return response()->json(Helper::formatStandardApiResponse('success', null, $e->getMessage())); } } public function getLoginAttempts() { return view('settings.logins'); } }
uberbrady/snipe-it
app/Http/Controllers/SettingsController.php
PHP
agpl-3.0
44,112
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="description" content="Responsive design testing for the masses"> <title>Responsive Design Testing</title> <style> *{vertical-align:top;} body{padding:20px;font-family:sans-serif;overflow-y:scroll;} h2{margin:0 0 20px 0;} #frames{overflow-x:scroll;width:100%;margin-bottom:10px;padding-bottom:20px;} .frame{margin-right:20px;float:left;} .frame:last-child{margin-right:0;} .frame img{display:none;vertical-align:middle;} iframe{border:solid 1px #000;} .widthOnly {height:580px;} .widthOnly h2 span{display:none;} .widthOnly iframe{height:500px;} br{clear:both} </style> </head> <body> <h1>../about.html</h1> <div id="frames"> <div> <div class="frame"> <h2>240 x 320 (xs)</h2> <iframe src="../about.html" seamless width="255" height="320"></iframe> </div> <div class="frame"> <h2>320 x 240 (xs)</h2> <iframe src="../about.html" seamless width="335" height="240"></iframe> </div> <br /> <br /> <div id="f3" class="frame"> <h2>480 x 640 (xs)</h2> <iframe src="../about.html" seamless width="495" height="640"></iframe> </div> <div id="f3" class="frame"> <h2>640 x 480 (xs)</h2> <iframe src="../about.html" seamless width="655" height="480"></iframe> </div> <br /> <br /> <div id="f4" class="frame"> <h2>768 x 1024 (sm)</h2> <iframe src="../about.html" seamless width="783" height="1024"></iframe> </div> <br /> <br /> <div id="f5" class="frame"> <h2>1024 x 768 (md)</h2> <iframe src="../about.html" seamless width="1039" height="768"></iframe> </div> </div> </div> </body> </html>
tweetssentiment/tweetssentiment.github.com
test/test-about.html
HTML
agpl-3.0
1,681
/* * Copyright 2011 Benjamin Glatzel <benjamin.glatzel@me.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Ported and modified by Stefano Bonicatti <smjert@gmail.com> */ using System.Threading.Tasks; using Chraft.PluginSystem; using System; using Chraft.PluginSystem.World; using Chraft.PluginSystem.World.Blocks; using Chraft.Utilities.Blocks; namespace CustomGenerator { public class CustomChunkGenerator : IChunkGenerator { private bool GenInit = false; private PerlinNoise _Gen1; private PerlinNoise _Gen2; private PerlinNoise _Gen3; private PerlinNoise _Gen4; private PerlinNoise _Gen5; private PerlinNoise _Gen6; private FastRandom _FastRandom; private long _Seed; private IWorldManager _World; Random r = new Random(); private IBlockHelper _blockHelper; public enum BIOME_TYPE : byte { PLAINS = 1, DESERT, MOUNTAINS, SNOW = 12 } public void Init(IWorldManager world, long seed) { _Seed = seed; _World = world; _blockHelper = _World.GetServer().GetBlockHelper(); } public void Init(long seed, IBlockHelper helper) { _blockHelper = helper; _Seed = seed; } private void InitGen() { if (GenInit) return; GenInit = true; _Gen1 = new PerlinNoise(_Seed); _Gen2 = new PerlinNoise(_Seed + 1); _Gen3 = new PerlinNoise(_Seed + 2); _Gen4 = new PerlinNoise(_Seed + 3); _Gen5 = new PerlinNoise(_Seed + 4); _Gen6 = new PerlinNoise(_Seed + 5); _FastRandom = new FastRandom(_Seed); } public IChunk GenerateChunk(IChunk chunk, int x, int z, bool external) { InitGen(); #if PROFILE Stopwatch watch = new Stopwatch(); watch.Start(); #endif GenerateTerrain(chunk, x, z); GenerateFlora(chunk, x, z); if (!external) { chunk.RecalculateHeight(); chunk.LightToRecalculate = true; #if PROFILE watch.Stop(); _World.Logger.Log(Logger.LogLevel.Info, "Chunk {0} {1}, {2}", false, x, z, watch.ElapsedMilliseconds); #endif _World.AddChunk(chunk); chunk.MarkToSave(); } return chunk; } private void GenerateTerrain(IChunk c, int x, int z) { double[, ,] density = new double[17, 129, 17]; // Build the density map with lower resolution, 4*4*16 instead of 16*16*128 for (int bx = 0; bx <= 16; bx += 4) { int worldX = bx + (x * 16); for (int bz = 0; bz <= 16; bz += 4) { BIOME_TYPE type = CalcBiomeType(x, z); int worldZ = bz + (z * 16); for (int by = 0; by <= 128; by += 8) { density[bx, by, bz] = CalcDensity(worldX, by, worldZ, type); } } } triLerpDensityMap(density); for (int bx = 0; bx < 16; bx++) { int worldX = bx + (x * 16); for (int bz = 0; bz < 16; bz++) { int worldZ = bz + (z * 16); int firstBlockHeight = -1; BIOME_TYPE type = CalcBiomeType(worldX, worldZ); for (int by = 127; by >= 0; --by) { //int index = bx << 11 | bz << 7 | by; if (by == 0) // First bedrock Layer c.SetType(bx, by, bz, BlockData.Blocks.Bedrock, false); else if (by > 0 && by < 5 && _FastRandom.randomDouble() > 0.3) // Randomly put blocks of the remaining 4 layers of bedrock c.SetType(bx, by, bz, BlockData.Blocks.Bedrock, false); else if (by <= 55) c.SetType(bx, by, bz, BlockData.Blocks.Stone, false); else { if (by > 55 && by < 64) { c.SetType(bx, by, bz, BlockData.Blocks.Still_Water, false); if (by == 63 && type == BIOME_TYPE.SNOW) { c.SetBiomeColumn(bx, bz, (byte)BIOME_TYPE.SNOW); c.SetType(bx, by, bz, BlockData.Blocks.Ice, false); } } double dens = density[bx, by, bz]; if (dens >= 0.009 && dens <= 0.02) { // Some block was set... if (firstBlockHeight == -1) firstBlockHeight = by; GenerateOuterLayer(bx, by, bz, firstBlockHeight, type, c); } else if (dens > 0.02) { // Some block was set... if (firstBlockHeight == -1) firstBlockHeight = by; if (CalcCaveDensity(worldX, by, worldZ) > -0.6) GenerateInnerLayer(bx, by, bz, type, c); } else firstBlockHeight = -1; } if (c.GetType(bx, by, bz) == BlockData.Blocks.Stone) GenerateResource(bx, by, bz, c); } } } } private void GenerateResource(int x, int y, int z, IChunk c) { if (r.Next(100 * y) == 0) c.SetType(x, y, z, BlockData.Blocks.Diamond_Ore, false); else if (r.Next(100 * y) == 0) c.SetType(x, y, z, BlockData.Blocks.Lapis_Lazuli_Ore, false); else if (r.Next(40 * y) == 0) c.SetType(x, y, z, BlockData.Blocks.Gold_Ore, false); else if (r.Next(10 * y) == 0) c.SetType(x, y, z, BlockData.Blocks.Redstone_Ore_Glowing, false); else if (r.Next(4 * y) == 0) c.SetType(x, y, z, BlockData.Blocks.Iron_Ore, false); else if (r.Next(2 * y) == 0) c.SetType(x, y, z, BlockData.Blocks.Coal_Ore, false); } private void GenerateFlora(IChunk c, int x, int z) { BIOME_TYPE biome = CalcBiomeType(x, z); for (int bx = 0; bx < 16; ++bx) { int worldX = bx + x * 16; for (int bz = 0; bz < 16; ++bz) { int worldZ = bz + z * 16; for (int by = 64; by < 128; ++by) { int worldY = by; //int index = bx << 11 | bz << 7 | by + 1; if (c.GetType(bx, by, bz) == BlockData.Blocks.Grass && c.GetType(bx, by + 1, bz) == (byte)BlockData.Blocks.Air) { double grassDens = CalcGrassDensity(worldX, worldZ); if (grassDens > 0.0) { // Generate high grass. double rand = _FastRandom.standNormalDistrDouble(); if (rand > -0.2 && rand < 0.2) { c.SetType(bx, by + 1, bz, BlockData.Blocks.TallGrass, false); c.SetData(bx, by + 1, bz, 1, false); } //Generate flowers. if (_FastRandom.standNormalDistrDouble() < -2) { if (_FastRandom.randomBoolean()) c.SetType(bx, by + 1, bz, BlockData.Blocks.Rose, false); else c.SetType(bx, by + 1, bz, BlockData.Blocks.Yellow_Flower, false); } } if (by < 110 && bx % 4 == 0 && bz % 4 == 0) { double forestDens = CalcForestDensity(worldX, worldZ); if (forestDens > 0.005) { int randX = bx + _FastRandom.randomInt() % 12 + 4; int randZ = bz + _FastRandom.randomInt() % 12 + 4; if (randX < 3) randX = 3; else if (randX > 12) randX = 12; if (randZ < 3) randZ = 3; else if (randZ > 15) randZ = 12; if (c.GetType(randX, by, randZ) == BlockData.Blocks.Grass) GenerateTree(c, randX, by, randZ); else if (biome == BIOME_TYPE.DESERT && c.GetType(randX, by, randZ) == BlockData.Blocks.Sand) GenerateCactus(c, randX, by, randZ); } } } } } } } private void GenerateCactus(IChunk c, int x, int y, int z) { int height = (_FastRandom.randomInt() + 1) % 3; if (!CanSeeTheSky(x, y + 1, z, c)) return; for (int by = height; by < y + height; ++y) c.SetType(x, y, z, BlockData.Blocks.Cactus, false); } private void GenerateTree(IChunk c, int x, int y, int z) { // Trees should only be placed in direct sunlight if (!CanSeeTheSky(x, y + 1, z, c)) return; double r2 = _FastRandom.standNormalDistrDouble(); /*if (r2 > -2 && r2 < -1) {*/ // Standard tree for (int by = y + 4; by < y + 6; by++) for (int bx = x - 2; bx <= x + 2; bx++) for (int bz = z - 2; bz <= z + 2; bz++) { c.SetType(bx, by, bz, BlockData.Blocks.Leaves, false); c.SetData(bx, by, bz, 0, false); } for (int bx = x - 1; bx <= x + 1; bx++) for (int bz = z - 1; bz <= z + 1; bz++) { c.SetType(bx, y + 6, bz, BlockData.Blocks.Leaves, false); c.SetData(bx, y + 6, bz, 0, false); } for (int by = y + 1; by < y + 6; by++) { c.SetType(x, by, z, BlockData.Blocks.Wood, false); c.SetData(x, by, z, 0, false); } //} // TODO: other tree types /*else if (r2 > 1 && r2 < 2) { c.setBlock(x, y + 1, z, (byte)0x0); c.getParent().getObjectGenerator("firTree").generate(c.getBlockWorldPosX(x), y + 1, c.getBlockWorldPosZ(z), false); } else { c.setBlock(x, y + 1, z, (byte)0x0); c.getParent().getObjectGenerator("tree").generate(c.getBlockWorldPosX(x), y + 1, c.getBlockWorldPosZ(z), false); }*/ } private bool CanSeeTheSky(int x, int y, int z, IChunk c) { int by; for (by = y; _blockHelper.Opacity(c.GetType(x, by, z)) == 0 && by < 128; ++by) ; return by == 128; } private double CalcForestDensity(double x, double z) { double result = 0.0; result += _Gen1.fBm(0.03 * x, 0, 0.03 * z, 7, 2.3614521, 0.85431); return result; } private double CalcGrassDensity(double x, double z) { double result = 0.0; result += _Gen3.fBm(0.05 * x, 0, 0.05 * z, 4, 2.37152, 0.8571); return result; } private double CalcDensity(double x, double y, double z, BIOME_TYPE type) { double height = CalcBaseTerrain(x, z); double density = CalcMountainDensity(x, y, z); double divHeight = (y - 55) * 1.5; if (y > 100) divHeight *= 2.0; if (type == BIOME_TYPE.DESERT) { divHeight *= 2.5; } else if (type == BIOME_TYPE.PLAINS) { divHeight *= 1.6; } else if (type == BIOME_TYPE.MOUNTAINS) { divHeight *= 1.1; } else if (type == BIOME_TYPE.SNOW) { divHeight *= 1.2; } return (height + density) / divHeight; } private double CalcBaseTerrain(double x, double z) { double result = 0.0; result += _Gen2.fBm(0.0009 * x, 0, 0.0009 * z, 3, 2.2341, 0.94321) + 0.4; return result; } private double CalcMountainDensity(double x, double y, double z) { double result = 0.0; double x1, y1, z1; x1 = x * 0.0006; y1 = y * 0.0008; z1 = z * 0.0006; double[] freq = { 1.232, 8.4281, 16.371, 32, 64 }; double[] amp = { 1.0, 1.4, 1.6, 1.8, 2.0 }; double ampSum = 0.0; for (int i = 0; i < freq.Length; i++) { result += _Gen5.noise(x1 * freq[i], y1 * freq[i], z1 * freq[i]) * amp[i]; ampSum += amp[i]; } return result / ampSum; } private double CalcTemperature(double x, double z) { double result = 0.0; result += _Gen4.fBm(x * 0.0008, 0, 0.0008 * z, 7, 2.1836171, 0.7631); result = 32.0 + (result) * 64.0; return result; } private BIOME_TYPE CalcBiomeType(int x, int z) { double temp = CalcTemperature(x, z); if (temp >= 60) { return BIOME_TYPE.DESERT; } else if (temp >= 32) { return BIOME_TYPE.MOUNTAINS; } else if (temp < 8) { return BIOME_TYPE.SNOW; } return BIOME_TYPE.PLAINS; } private void GenerateOuterLayer(int x, int y, int z, int firstBlockHeight, BIOME_TYPE type, IChunk c) { double heightPercentage = (firstBlockHeight - y) / 128.0; switch (type) { case BIOME_TYPE.PLAINS: case BIOME_TYPE.MOUNTAINS: // Beach if (y >= 60 && y <= 66) { c.SetBiomeColumn(x, z, (byte)BIOME_TYPE.MOUNTAINS); c.SetType(x, y, z, BlockData.Blocks.Sand, false); break; } c.SetBiomeColumn(x, z, (byte)BIOME_TYPE.MOUNTAINS); if (heightPercentage == 0.0 && y > 66) { // Grass on top c.SetType(x, y, z, BlockData.Blocks.Grass, false); } else if (heightPercentage > 0.2) { // Stone c.SetType(x, y, z, BlockData.Blocks.Stone, false); } else { // Dirt c.SetType(x, y, z, BlockData.Blocks.Dirt, false); } GenerateRiver(c, x, y, z, heightPercentage, type); break; case BIOME_TYPE.SNOW: c.SetBiomeColumn(x, z, (byte)BIOME_TYPE.SNOW); if (heightPercentage == 0.0 && y > 65) { // Snow on top c.SetType(x, y, z, BlockData.Blocks.Snow, false); // Grass under the snow c.SetType(x, y - 1, z, BlockData.Blocks.Grass, false); } else if (heightPercentage > 0.2) // Stone c.SetType(x, y, z, BlockData.Blocks.Stone, false); else // Dirt c.SetType(x, y, z, BlockData.Blocks.Dirt, false); GenerateRiver(c, x, y, z, heightPercentage, type); break; case BIOME_TYPE.DESERT: c.SetBiomeColumn(x, z, (byte)BIOME_TYPE.DESERT); /*if (heightPercentage > 0.6 && y < 75) { // Stone data[x << 11 | z << 7 | y] = (byte)BlockData.Blocks.Stone; } else*/ if (y < 80) c.SetType(x, y, z, BlockData.Blocks.Sand, false); break; } } protected void GenerateRiver(IChunk c, int x, int y, int z, double heightPercentage, BIOME_TYPE type) { // Rivers under water? Nope. if (y <= 63) return; double lakeIntens = CalcLakeIntensity(x + c.Coords.ChunkX * 16, z + c.Coords.ChunkZ * 16); short currentIndex = (short)(x << 11 | z << 7 | y); if (lakeIntens < 0.2) { if (heightPercentage < 0.001) c.SetType(x, y, z, BlockData.Blocks.Air, false); else if (heightPercentage < 0.02) { if (type == BIOME_TYPE.SNOW) { // To be sure that there's no snow above us c.SetType(x, y + 1, z, BlockData.Blocks.Air, false); c.SetType(x, y, z, BlockData.Blocks.Ice, false); } else c.SetType(x, y, z, BlockData.Blocks.Still_Water, false); } } } protected double CalcLakeIntensity(double x, double z) { double result = 0.0; result += _Gen3.fBm(x * 0.0085, 0, 0.0085 * z, 2, 1.98755, 0.98); return Math.Sqrt(Math.Abs(result)); } protected double CalcCaveDensity(double x, double y, double z) { double result = 0.0; result += _Gen6.fBm(x * 0.04, y * 0.04, z * 0.04, 2, 2.0, 0.98); return result; } private void GenerateInnerLayer(int x, int y, int z, BIOME_TYPE type, IChunk c) { c.SetType(x, y, z, BlockData.Blocks.Stone, false); } private static double lerp(double t, double q00, double q01) { return q00 + t * (q01 - q00); } private static double triLerp(double x, double y, double z, double q000, double q001, double q010, double q011, double q100, double q101, double q110, double q111, double x1, double x2, double y1, double y2, double z1, double z2) { double distanceX = x2 - x1; double distanceY = y2 - y1; double distanceZ = z2 - z1; double tX = (x - x1) / distanceX; double tY = (y - y1) / distanceY; double x00 = lerp(tX, q000, q100); double x10 = lerp(tX, q010, q110); double x01 = lerp(tX, q001, q101); double x11 = lerp(tX, q011, q111); double r0 = lerp(tY, x00, x01); double r1 = lerp(tY, x10, x11); return lerp((z - z1) / distanceZ, r0, r1); } private void triLerpDensityMap(double[, ,] densityMap) { Parallel.For(0, 16, x => { int offsetX = (x/4)*4; for (int y = 0; y < 128; y++) { int offsetY = (y/8)*8; for (int z = 0; z < 16; z++) { if (!(x%4 == 0 && y%8 == 0 && z%4 == 0)) { int offsetZ = (z/4)*4; densityMap[x, y, z] = triLerp(x, y, z, densityMap[offsetX, offsetY, offsetZ], densityMap[offsetX, offsetY + 8, offsetZ], densityMap[offsetX, offsetY, offsetZ + 4], densityMap[offsetX, offsetY + 8, offsetZ + 4], densityMap[4 + offsetX, offsetY, offsetZ], densityMap[4 + offsetX, offsetY + 8, offsetZ], densityMap[4 + offsetX, offsetY, offsetZ + 4], densityMap[4 + offsetX, offsetY + 8, offsetZ + 4], offsetX, 4 + offsetX, offsetY, 8 + offsetY, offsetZ, offsetZ + 4); } } } }); } } }
chraft/c-raft
CustomGenerator/CustomChunkGenerator.cs
C#
agpl-3.0
22,590
class Mfi include DataMapper::Resource MinDateFrom = {:in_operation_since => "In operation since date", :today => "Today's date"} SYSTEM_STATES = [:running, :stopped, :migration, :admin_only] def self.default_repository_name :abstract end attr_accessor :subdomain, :city_name, :state_id, :district_id, :logo, :fetched property :id, Serial, :nullable => false, :index => true property :name, String, :nullable => true, :index => true property :address, Text property :website, String property :telephone, String property :in_operation_since, Date, :nullable => false, :index => true, :default => Date.new(2000, 1, 1) property :number_of_past_days, Integer, :nullable => true, :index => true, :default => 5 property :min_date_from, Enum.send('[]', *MinDateFrom.keys), :nullable => true, :index => true, :default => :in_operation_since property :number_of_future_transaction_days, Integer, :nullable => true, :index => true, :default => 0 property :number_of_future_days, Integer, :nullable => true, :index => true, :default => 100 property :date_box_editable, Boolean, :default => true, :index => true property :allow_grt_date_on_form, Boolean, :default => false, :index => true property :email, String, :nullable => false, :index => true, :format => :email_address property :created, Boolean, :nullable => false, :index => true, :default => false property :color, String, :nullable => true property :logo_name, String, :nullable => true property :accounting_enabled, Boolean, :default => false, :index => true property :transaction_logging_enabled, Boolean, :default => false, :index => true property :event_model_logging_enabled, Boolean, :default => false, :index => true property :dirty_queue_enabled, Boolean, :default => false, :index => true property :map_enabled, Boolean, :default => false, :index => true property :branch_diary_enabled, Boolean, :default => false, :index => true property :stock_register_enabled, Boolean, :default => false, :index => true property :asset_register_enabled, Boolean, :default => false, :index => true property :allow_choice_of_repayment_style, Boolean, :default => true, :index => true property :default_repayment_style, Enum.send('[]', *REPAYMENT_STYLES), :default => NORMAL_REPAYMENT_STYLE, :index => true property :generate_day_sheet_before, Integer, :default => 1, :max => 5 property :currency_format, String, :nullable => true, :length => 20, :default => "in_with_paise" property :session_expiry, Integer, :nullable => true, :min => 60, :max => 86400 property :password_change_in, Integer, :nullable => true property :org_locale, String property :prefered_date_pattern, String, :nullable => true property :prefered_date_separator, String, :nullable => true property :prefered_date_style, String, :nullable => true property :report_access_rules, Yaml, :nullable => true, :default => {} property :system_state, Enum.send('[]', *SYSTEM_STATES), :default => :running property :main_text, Text, :nullable => true, :lazy => true validates_length :name, :min => 0, :max => 20 before :valid?, :save_image validates_with_method :check_contact_details, :if => Proc.new{|m| m.new?} def self.first if $globals and $globals[:mfi_details] and $globals[:mfi_details].fetched==Date.today $globals[:mfi_details] else mfi = if File.exists?(File.join(Merb.root, "config", "mfi.yml")) Mfi.new(YAML.load(File.read(File.join(Merb.root, "config", "mfi.yml"))).only(*Mfi.properties.map(&:name))) else Mfi.new(:name => "Mostfit", :fetched => Date.today) end mfi.fetched = Date.today $globals ||= {} $globals[:mfi_details] = mfi return mfi end end def self.activate mfi = Mfi.first mfi.set_variables end def save $globals ||= {} $globals[:mfi_details] = Mfi.new(self.attributes) self.in_operation_since = self.in_operation_since.strftime("%Y-%m-%d") File.open(File.join(Merb.root, "config", "mfi.yml"), "w"){|f| f.puts self.to_yaml } FileUtils.touch(File.join(Merb.root, "tmp", "restart.txt")) Mfi.activate end def save_image if self.logo and self.logo[:filename] and not self.logo[:filename].blank? and ["image/jpeg", "image/png", "image/gif"].include?(self.logo[:content_type]) File.makedirs(File.join(Merb.root, "public", "images", "logos")) FileUtils.mv(self.logo[:tempfile].path, File.join(Merb.root, "public", "images", "logos", self.logo[:filename])) File.chmod(0755, File.join(Merb.root, "public", "images", "logos", self.logo[:filename])) self.logo_name = self.logo[:filename] end end def set_currency_format if format = currency_format and not format.blank? and Numeric::Transformer.instance_variable_get("@formats").keys.include?(format.to_sym) Numeric::Transformer.change_default_format(format.to_sym) else Numeric::Transformer.change_default_format(:mostfit_default) end end def set_variables self.report_access_rules = REPORT_ACCESS_HASH if not self.report_access_rules or self.report_access_rules == {} Misfit::Config::DateFormat.compile set_currency_format DirtyLoan.start_thread end def date_format mfi = Mfi.first style = mfi.prefered_date_style || DEFAULT_DATE_STYLE case style when "MEDIUM" return MEDIUM_DATE_PATTERN when "LONG" return LONG_DATE_PATTERN when "FULL" return FULL_DATE_PATTERN else pattern = (mfi.prefered_date_pattern if not mfi.prefered_date_pattern.blank?) || DEFAULT_DATE_PATTERN separator = (mfi.prefered_date_separator if not mfi.prefered_date_separator.blank?) || DEFAULT_DATE_SEPARATOR pattern = pattern.to_s.gsub(FORMAT_REG_EXP, separator.to_s) return pattern end end # How about some normal validations? def check_contact_details return true if address and telephone return [false, "Please enter your address and telephone number"] end end
Mostfit/mostfit
app/models/mfi.rb
Ruby
agpl-3.0
6,116
/* * This file is part of LibrePlan * * Copyright (C) 2016 LibrePlan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.importers.notifications.realization; import org.joda.time.LocalDate; import org.libreplan.business.common.Configuration; import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.email.entities.EmailNotification; import org.libreplan.business.email.entities.EmailTemplateEnum; import org.libreplan.business.planner.daos.ITaskElementDAO; import org.libreplan.business.planner.entities.TaskElement; import org.libreplan.business.users.daos.IUserDAO; import org.libreplan.business.users.entities.User; import org.libreplan.business.users.entities.UserRole; import org.libreplan.importers.notifications.ComposeMessage; import org.libreplan.importers.notifications.EmailConnectionValidator; import org.libreplan.importers.notifications.IEmailNotificationJob; import org.libreplan.web.email.IEmailNotificationModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; /** * Sends E-mail to manager user (it writes in responsible field in project properties) * with data that storing in notification_queue table * and that are treat to {@link EmailTemplateEnum#TEMPLATE_MILESTONE_REACHED} * Date will be send on current date equals to deadline date of {@link org.zkoss.ganttz.data.Milestone}. * But it will be only send to Manager (you can assign him in project properties). * * @author Vova Perebykivskyi <vova@libreplan-enterprise.com> */ @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class SendEmailOnMilestoneReached implements IEmailNotificationJob { @Autowired private IEmailNotificationModel emailNotificationModel; @Autowired private ITaskElementDAO taskElementDAO; @Autowired private IUserDAO userDAO; @Autowired private ComposeMessage composeMessage; @Autowired EmailConnectionValidator emailConnectionValidator; /** * Transactional here is needed because without this annotation we are getting * "LazyInitializationException: could not initialize proxy - no Session" error, * when "item.getParent().getOrderElement().getOrder().getResponsible()" method was called. * Earlier this trouble was not present because in Tasks.hbm.xml for "TaskElement" class field * named "parent", which has relation "many-to-one" to "TaskGroup", lazy was set to "false". */ @Override @Transactional public void sendEmail() { // Gathering data checkMilestoneDate(); if ( Configuration.isEmailSendingEnabled() ) { if ( emailConnectionValidator.isConnectionActivated() && emailConnectionValidator.validConnection() ) { List<EmailNotification> notifications = emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_MILESTONE_REACHED); for (EmailNotification notification : notifications) { if ( composeMessageForUser(notification) ) { deleteSingleNotification(notification); } } } } } @Override public boolean composeMessageForUser(EmailNotification notification) { return composeMessage.composeMessageForUser(notification); } private void deleteSingleNotification(EmailNotification notification){ emailNotificationModel.deleteById(notification); } private void sendEmailNotificationToManager(TaskElement item) { emailNotificationModel.setNewObject(); emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_MILESTONE_REACHED); emailNotificationModel.setUpdated(new Date()); String responsible = ""; if ( item.getParent().getOrderElement().getOrder().getResponsible() != null ) { responsible = item.getParent().getOrderElement().getOrder().getResponsible(); } User user = null; try { // FIXME: Code below can produce NullPointerException if "Responsible" field is not set in Project Details -> General data user = userDAO.findByLoginName(responsible); } catch (InstanceNotFoundException e) { e.printStackTrace(); } boolean userHasNeededRoles = user.isInRole(UserRole.ROLE_SUPERUSER) || user.isInRole(UserRole.ROLE_EMAIL_MILESTONE_REACHED); if ( user.getWorker() != null && userHasNeededRoles ) { emailNotificationModel.setResource(user.getWorker()); emailNotificationModel.setTask(item); emailNotificationModel.setProject(item.getParent()); emailNotificationModel.confirmSave(); } } public void checkMilestoneDate() { List<TaskElement> milestones = taskElementDAO.getTaskElementsWithMilestones(); LocalDate date = new LocalDate(); int currentYear = date.getYear(); int currentMonth = date.getMonthOfYear(); int currentDay = date.getDayOfMonth(); for (TaskElement item : milestones) { if ( item.getDeadline() != null ) { LocalDate deadline = item.getDeadline(); int deadlineYear = deadline.getYear(); int deadlineMonth = deadline.getMonthOfYear(); int deadlineDay = deadline.getDayOfMonth(); if (currentYear == deadlineYear && currentMonth == deadlineMonth && currentDay == deadlineDay) { sendEmailNotificationToManager(item); } } } } }
PaulLuchyn/libreplan
libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnMilestoneReached.java
Java
agpl-3.0
6,523
/* Copyright (C) 2014 Omega software d.o.o. This file is part of Rhetos. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Rhetos.Dom.DefaultConcepts; using Rhetos.Configuration.Autofac; using Rhetos.Utilities; using Rhetos.TestCommon; using System.Threading.Tasks; using System.Diagnostics; using System.Threading; using System.Collections.Concurrent; namespace CommonConcepts.Test { [TestClass] public class AutoCodeTest { private static void DeleteOldData(RhetosTestContainer container) { container.Resolve<ISqlExecuter>().ExecuteSql(new[] { @"DELETE FROM TestAutoCode.ReferenceGroup; DELETE FROM TestAutoCode.ShortReferenceGroup; DELETE FROM TestAutoCode.Grouping; DELETE FROM TestAutoCode.StringGroup; DELETE FROM TestAutoCode.IntGroup; DELETE FROM TestAutoCode.Simple; DELETE FROM TestAutoCode.DoubleAutoCode; DELETE FROM TestAutoCode.DoubleAutoCodeWithGroup; DELETE FROM TestAutoCode.IntegerAutoCode; DELETE FROM TestAutoCode.MultipleGroups;" }); } private static void TestSimple(RhetosTestContainer container, Common.DomRepository repository, string format, string expectedCode) { Guid id = Guid.NewGuid(); repository.TestAutoCode.Simple.Insert(new[] { new TestAutoCode.Simple { ID = id, Code = format } }); string generatedCode = repository.TestAutoCode.Simple.Query().Where(item => item.ID == id).Select(item => item.Code).Single(); Console.WriteLine(format + " => " + generatedCode); Assert.AreEqual(expectedCode, generatedCode); } private static void TestIntAutoCode(RhetosTestContainer container, Common.DomRepository repository, int? input, int expectedCode) { Guid id = Guid.NewGuid(); repository.TestAutoCode.IntegerAutoCode.Insert(new[] { new TestAutoCode.IntegerAutoCode { ID = id, Code = input } }); int? generatedCode = repository.TestAutoCode.IntegerAutoCode.Query().Where(item => item.ID == id).Select(item => item.Code).Single(); Console.WriteLine(input.ToString() + " => " + generatedCode.ToString()); Assert.AreEqual(expectedCode, generatedCode); } private static void TestDoubleAutoCode(RhetosTestContainer container, Common.DomRepository repository, string formatA, string formatB, string expectedCodes) { Guid id = Guid.NewGuid(); repository.TestAutoCode.DoubleAutoCode.Insert(new[] { new TestAutoCode.DoubleAutoCode { ID = id, CodeA = formatA, CodeB = formatB } }); string generatedCodes = repository.TestAutoCode.DoubleAutoCode.Query() .Where(item => item.ID == id) .Select(item => item.CodeA + "," + item.CodeB).Single(); Console.WriteLine(formatA + "," + formatB + " => " + generatedCodes); Assert.AreEqual(expectedCodes, generatedCodes); } private static void TestDoubleAutoCodeWithGroup(RhetosTestContainer container, Common.DomRepository repository, string group, string formatA, string formatB, string expectedCodes) { Guid id = Guid.NewGuid(); repository.TestAutoCode.DoubleAutoCodeWithGroup.Insert(new[] { new TestAutoCode.DoubleAutoCodeWithGroup { ID = id, Grouping = group, CodeA = formatA, CodeB = formatB } }); string generatedCodes = repository.TestAutoCode.DoubleAutoCodeWithGroup.Query() .Where(item => item.ID == id) .Select(item => item.CodeA + "," + item.CodeB).Single(); Console.WriteLine(formatA + "," + formatB + " => " + generatedCodes); Assert.AreEqual(expectedCodes, generatedCodes); } private static void TestDoubleIntegerAutoCodeWithGroup(RhetosTestContainer container, Common.DomRepository repository, int group, int? codeA, int? codeB, string expectedCodes) { Guid id = Guid.NewGuid(); repository.TestAutoCode.IntegerAutoCodeForEach.Insert(new[] { new TestAutoCode.IntegerAutoCodeForEach { ID = id, Grouping = group, CodeA = codeA, CodeB = codeB } }); string generatedCodes = repository.TestAutoCode.IntegerAutoCodeForEach.Query() .Where(item => item.ID == id) .Select(item => item.CodeA.ToString() + "," + item.CodeB.ToString()).Single(); Console.WriteLine(codeA.ToString() + "," + codeB.ToString() + " => " + generatedCodes); Assert.AreEqual(expectedCodes, generatedCodes); } [TestMethod] public void Simple() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestSimple(container, repository, "+", "1"); TestSimple(container, repository, "+", "2"); TestSimple(container, repository, "+", "3"); TestSimple(container, repository, "9", "9"); TestSimple(container, repository, "+", "10"); TestSimple(container, repository, "+", "11"); TestSimple(container, repository, "AB+", "AB1"); TestSimple(container, repository, "X", "X"); TestSimple(container, repository, "X+", "X1"); TestSimple(container, repository, "AB007", "AB007"); TestSimple(container, repository, "AB+", "AB008"); TestSimple(container, repository, "AB999", "AB999"); TestSimple(container, repository, "AB+", "AB1000"); } } [TestMethod] public void InsertMultipleItems() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); var tests = new ListOfTuples<string, string> { { "+", "10" }, // Exactly specified values are considered before generated values, therefore this item is handled after core "9". { "+", "11" }, { "+", "12" }, { "9", "9" }, { "+", "13" }, { "+", "14" }, { "AB+", "AB1000" }, { "X", "X" }, { "X+", "X1" }, { "AB007", "AB007" }, { "AB+", "AB1001" }, { "AB999", "AB999" }, { "AB+", "AB1002" }, }; repository.TestAutoCode.Simple.Insert( tests.Select((test, index) => new TestAutoCode.Simple { ID = new Guid(index + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Code = test.Item1 })); IEnumerable<string> generatedCodes = repository.TestAutoCode.Simple.Load() .OrderBy(item => item.ID) .Select(item => item.Code); IEnumerable<string> expectedCodes = tests.Select(test => test.Item2); Assert.AreEqual(TestUtility.Dump(expectedCodes), TestUtility.Dump(generatedCodes)); } } [TestMethod] public void SimpleFromHelp() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestSimple(container, repository, "ab+", "ab1"); TestSimple(container, repository, "ab+", "ab2"); TestSimple(container, repository, "ab+", "ab3"); TestSimple(container, repository, "ab++++", "ab0004"); TestSimple(container, repository, "c+", "c1"); TestSimple(container, repository, "+", "1"); TestSimple(container, repository, "+", "2"); TestSimple(container, repository, "ab+", "ab0005"); } } [TestMethod] public void DoubleAutoCode() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestDoubleAutoCode(container, repository, "+", "+", "1,1"); TestDoubleAutoCode(container, repository, "+", "4", "2,4"); TestDoubleAutoCode(container, repository, "+", "+", "3,5"); TestDoubleAutoCode(container, repository, "9", "+", "9,6"); TestDoubleAutoCode(container, repository, "+", "11", "10,11"); TestDoubleAutoCode(container, repository, "+", "+", "11,12"); TestDoubleAutoCode(container, repository, "AB+", "+", "AB1,13"); TestDoubleAutoCode(container, repository, "AB+", "X", "AB2,X"); TestDoubleAutoCode(container, repository, "AB+", "X+", "AB3,X1"); TestDoubleAutoCode(container, repository, "AB008", "X+", "AB008,X2"); TestDoubleAutoCode(container, repository, "AB+", "+", "AB009,14"); TestDoubleAutoCode(container, repository, "+", "AB9999", "12,AB9999"); TestDoubleAutoCode(container, repository, "AB+", "AB+", "AB010,AB10000"); } } [TestMethod] public void IntAutoCode() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestIntAutoCode(container, repository, 0, 1); TestIntAutoCode(container, repository, 10, 10); TestIntAutoCode(container, repository, 0, 11); TestIntAutoCode(container, repository, 99, 99); TestIntAutoCode(container, repository, 0, 100); TestIntAutoCode(container, repository, 0, 101); TestIntAutoCode(container, repository, 0, 102); } } [TestMethod] public void IntAutoCodeNull() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestIntAutoCode(container, repository, null, 1); TestIntAutoCode(container, repository, null, 2); } } [TestMethod] public void DoubleAutoCodeWithGroup() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestDoubleAutoCodeWithGroup(container, repository, "1", "+", "+", "1,1"); TestDoubleAutoCodeWithGroup(container, repository, "1", "+", "4", "2,4"); TestDoubleAutoCodeWithGroup(container, repository, "2", "+", "+", "3,1"); TestDoubleAutoCodeWithGroup(container, repository, "1", "9", "+", "9,5"); TestDoubleAutoCodeWithGroup(container, repository, "2", "+", "11", "10,11"); TestDoubleAutoCodeWithGroup(container, repository, "1", "+", "+", "11,6"); TestDoubleAutoCodeWithGroup(container, repository, "1", "AB+", "+", "AB1,7"); TestDoubleAutoCodeWithGroup(container, repository, "1", "AB+", "X", "AB2,X"); TestDoubleAutoCodeWithGroup(container, repository, "2", "AB+", "X09", "AB3,X09"); TestDoubleAutoCodeWithGroup(container, repository, "2", "AB+", "X+", "AB4,X10"); TestDoubleAutoCodeWithGroup(container, repository, "1", "AB+", "X+", "AB5,X1"); TestDoubleAutoCodeWithGroup(container, repository, "1", "AB008", "X+", "AB008,X2"); TestDoubleAutoCodeWithGroup(container, repository, "1", "AB+", "+", "AB009,8"); TestDoubleAutoCodeWithGroup(container, repository, "1", "+", "AB9999", "12,AB9999"); TestDoubleAutoCodeWithGroup(container, repository, "1", "AB+", "AB+", "AB010,AB10000"); } } [TestMethod] public void DoubleIntegerAutoCodeWithGroup() { using (var container = new RhetosTestContainer()) { var repository = container.Resolve<Common.DomRepository>(); repository.TestAutoCode.IntegerAutoCodeForEach.Delete(repository.TestAutoCode.IntegerAutoCodeForEach.Query()); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, 0, 0, "1,1"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, 5, 0, "5,2"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, 0, 0, "6,3"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 2, 8, 0, "8,1"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 2, 0, 0, "9,2"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, 0, 0, "10,4"); } } [TestMethod] public void DoubleIntegerAutoCodeWithGroupNull() { using (var container = new RhetosTestContainer()) { var repository = container.Resolve<Common.DomRepository>(); repository.TestAutoCode.IntegerAutoCodeForEach.Delete(repository.TestAutoCode.IntegerAutoCodeForEach.Query()); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, null, null, "1,1"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, 5, null, "5,2"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, null, null, "6,3"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 2, 8, null, "8,1"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 2, null, null, "9,2"); TestDoubleIntegerAutoCodeWithGroup(container, repository, 1, null, null, "10,4"); } } private static void TestGroup<TEntity, TGroup>( RhetosTestContainer container, IQueryableRepository<IEntity> entityRepository, TGroup group, string format, string expectedCode) where TEntity : class, IEntity, new() { var writeableRepository = (IWritableRepository<TEntity>) entityRepository; Guid id = Guid.NewGuid(); dynamic entity = new TEntity(); entity.ID = id; entity.Code = format; try { entity.Grouping = group; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { entity.GroupingID = ((dynamic)group).ID; } writeableRepository.Insert((TEntity)entity); var query = entityRepository.Query().Where(e => e.ID == id); Console.WriteLine(query.GetType().FullName); Console.WriteLine(query.Expression.ToString()); Console.WriteLine(query.ToString()); dynamic loaded = query.Single(); string generatedCode = loaded.Code; Console.WriteLine(format + " => " + generatedCode); Assert.AreEqual(expectedCode, generatedCode); } [TestMethod] public void Grouping() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestGroup<TestAutoCode.IntGroup, int>(container, repository.TestAutoCode.IntGroup, 500, "+", "1"); TestGroup<TestAutoCode.IntGroup, int>(container, repository.TestAutoCode.IntGroup, 500, "+", "2"); TestGroup<TestAutoCode.IntGroup, int>(container, repository.TestAutoCode.IntGroup, 600, "+", "1"); TestGroup<TestAutoCode.IntGroup, int>(container, repository.TestAutoCode.IntGroup, 600, "A+", "A1"); TestGroup<TestAutoCode.StringGroup, string>(container, repository.TestAutoCode.StringGroup, "x", "+", "1"); TestGroup<TestAutoCode.StringGroup, string>(container, repository.TestAutoCode.StringGroup, "x", "+", "2"); TestGroup<TestAutoCode.StringGroup, string>(container, repository.TestAutoCode.StringGroup, "y", "+", "1"); TestGroup<TestAutoCode.StringGroup, string>(container, repository.TestAutoCode.StringGroup, "y", "A+", "A1"); var simple1 = new TestAutoCode.Simple { ID = Guid.NewGuid(), Code = "1" }; var simple2 = new TestAutoCode.Simple { ID = Guid.NewGuid(), Code = "2" }; repository.TestAutoCode.Simple.Insert(new[] { simple1, simple2 }); TestGroup<TestAutoCode.ReferenceGroup, TestAutoCode.Simple>(container, repository.TestAutoCode.ReferenceGroup, simple1, "+", "1"); TestGroup<TestAutoCode.ReferenceGroup, TestAutoCode.Simple>(container, repository.TestAutoCode.ReferenceGroup, simple1, "+", "2"); TestGroup<TestAutoCode.ReferenceGroup, TestAutoCode.Simple>(container, repository.TestAutoCode.ReferenceGroup, simple2, "+", "1"); TestGroup<TestAutoCode.ReferenceGroup, TestAutoCode.Simple>(container, repository.TestAutoCode.ReferenceGroup, simple2, "A+", "A1"); var grouping1 = new TestAutoCode.Grouping { ID = Guid.NewGuid(), Code = "1" }; var grouping2 = new TestAutoCode.Grouping { ID = Guid.NewGuid(), Code = "2" }; repository.TestAutoCode.Grouping.Insert(new[] { grouping1, grouping2 }); TestGroup<TestAutoCode.ShortReferenceGroup, TestAutoCode.Grouping>(container, repository.TestAutoCode.ShortReferenceGroup, grouping1, "+", "1"); TestGroup<TestAutoCode.ShortReferenceGroup, TestAutoCode.Grouping>(container, repository.TestAutoCode.ShortReferenceGroup, grouping1, "+", "2"); TestGroup<TestAutoCode.ShortReferenceGroup, TestAutoCode.Grouping>(container, repository.TestAutoCode.ShortReferenceGroup, grouping2, "+", "1"); TestGroup<TestAutoCode.ShortReferenceGroup, TestAutoCode.Grouping>(container, repository.TestAutoCode.ShortReferenceGroup, grouping2, "A+", "A1"); } } [TestMethod] public void AllowedNullValueInternally() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var context = container.Resolve<Common.ExecutionContext>(); var s1 = new TestAutoCode.Simple { ID = Guid.NewGuid(), Code = null }; AutoCodeHelper.UpdateCodesWithoutCache( context.SqlExecuter, "TestAutoCode.Simple", "Code", new[] { AutoCodeItem.Create(s1, s1.Code) }, (item, newCode) => item.Code = newCode); Assert.AreEqual("1", s1.Code); } } [TestMethod] public void AutocodeStringNull() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); var item1 = new TestAutoCode.Simple { ID = Guid.NewGuid() }; var item2 = new TestAutoCode.Simple { ID = Guid.NewGuid() }; repository.TestAutoCode.Simple.Insert(item1); repository.TestAutoCode.Simple.Insert(item2); Assert.AreEqual("1", repository.TestAutoCode.Simple.Load(new[] { item1.ID }).Single().Code); Assert.AreEqual("2", repository.TestAutoCode.Simple.Load(new[] { item2.ID }).Single().Code); } } [TestMethod] public void AutocodeStringEmpty() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); var item1 = new TestAutoCode.Simple { ID = Guid.NewGuid(), Code = "" }; repository.TestAutoCode.Simple.Insert(item1); Assert.AreEqual("", repository.TestAutoCode.Simple.Load(new[] { item1.ID }).Single().Code); } } [TestMethod] public void SimpleWithPredefinedSuffixLength() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestSimple(container, repository, "+", "1"); TestSimple(container, repository, "+", "2"); TestSimple(container, repository, "++++", "0003"); TestSimple(container, repository, "+", "0004"); TestSimple(container, repository, "++", "0005"); TestSimple(container, repository, "AB+", "AB1"); TestSimple(container, repository, "X", "X"); TestSimple(container, repository, "X+", "X1"); TestSimple(container, repository, "AB007", "AB007"); TestSimple(container, repository, "AB+", "AB008"); TestSimple(container, repository, "AB999", "AB999"); TestSimple(container, repository, "AB+", "AB1000"); TestSimple(container, repository, "AB++++++", "AB001001"); } } [TestMethod] public void SimpleWithPredefinedSuffixLength2() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestSimple(container, repository, "+++", "001"); TestSimple(container, repository, "+", "002"); TestSimple(container, repository, "AB99", "AB99"); TestSimple(container, repository, "AB++", "AB100"); TestSimple(container, repository, "AB999", "AB999"); TestSimple(container, repository, "AB++++++", "AB001000"); TestSimple(container, repository, "B999", "B999"); TestSimple(container, repository, "B++", "B1000"); TestSimple(container, repository, "C500", "C500"); TestSimple(container, repository, "C++", "C501"); } } [TestMethod] public void DifferentLengths() { using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestSimple(container, repository, "002", "002"); TestSimple(container, repository, "55", "55"); TestSimple(container, repository, "+", "56"); TestSimple(container, repository, "A002", "A002"); TestSimple(container, repository, "A55", "A55"); TestSimple(container, repository, "A++", "A56"); TestSimple(container, repository, "C100", "C100"); TestSimple(container, repository, "C99", "C99"); TestSimple(container, repository, "C+", "C101"); } } [TestMethod] public void InvalidFormat() { foreach (var test in new[] {"a+a", "a++a", "+a", "++a", "+a+", "++a+", "+a++", "++a++"}) { Console.WriteLine("Test: " + test); using (var container = new RhetosTestContainer()) { DeleteOldData(container); var repository = container.Resolve<Common.DomRepository>(); TestUtility.ShouldFail( () => repository.TestAutoCode.Simple.Insert(new[] { new TestAutoCode.Simple { ID = Guid.NewGuid(), Code = test } }), "invalid code"); } } } [TestMethod] public void ParallelInsertsSmokeTestSamePrefix() { // Each thread inserts 10*2 records with an empty AutoCode cache: for (int i = 0; i < 10; i++) Execute2ParallelInserts(1, (process, repository) => { repository.Insert(new[] { new TestAutoCode.Simple { Code = "+", Data = process.ToString() } }); repository.Insert(new[] { new TestAutoCode.Simple { Code = "+", Data = process.ToString() } }); }); // Each thread inserts 50*2 records, reusing the existing AutoCode cache: Execute2ParallelInserts(50, (process, repository) => { repository.Insert(new[] { new TestAutoCode.Simple { Code = "+", Data = process.ToString() } }); repository.Insert(new[] { new TestAutoCode.Simple { Code = "+", Data = process.ToString() } }); }); using (var container = new RhetosTestContainer()) { var repository = container.Resolve<Common.DomRepository>().TestAutoCode.Simple; var generatedCodes = repository.Query().Select(item => item.Code).ToList(); var expected = Enumerable.Range(1, 50 * 2 * 2); Assert.AreEqual(TestUtility.DumpSorted(expected), TestUtility.DumpSorted(generatedCodes)); } } [TestMethod] public void ParallelInsertsSmokeTestDifferentPrefix() { // Each thread inserts 10*2 records with an empty AutoCode cache: for (int i = 0; i < 10; i++) Execute2ParallelInserts(1, (process, repository) => { repository.Insert(new[] { new TestAutoCode.Simple { Code = (char)('a' + process) + "+", Data = process.ToString() } }); repository.Insert(new[] { new TestAutoCode.Simple { Code = (char)('a' + process) + "+", Data = process.ToString() } }); }); // Each thread inserts 50*2 records, reusing the existing AutoCode cache: Execute2ParallelInserts(50, (process, repository) => { repository.Insert(new[] { new TestAutoCode.Simple { Code = (char)('a' + process) + "+", Data = process.ToString() } }); repository.Insert(new[] { new TestAutoCode.Simple { Code = (char)('a' + process) + "+", Data = process.ToString() } }); }); using (var container = new RhetosTestContainer()) { var repository = container.Resolve<Common.DomRepository>().TestAutoCode.Simple; var generatedCodes = repository.Query().Select(item => item.Code).ToList(); var expected = Enumerable.Range(1, 50 * 2).SelectMany(x => new[] { "a" + x, "b" + x }); Assert.AreEqual(TestUtility.DumpSorted(expected), TestUtility.DumpSorted(generatedCodes)); } } [TestMethod] public void ParallelInsertsLockingTestSamePrefix() { // One process must wait for another, since they use the same code prefix and code group: var endTimes = new DateTime[2]; Execute2ParallelInserts(1, (process, repository) => { repository.Insert(new[] { new TestAutoCode.Simple { Code = "+", Data = process.ToString() } }); System.Threading.Thread.Sleep(200); endTimes[process] = DateTime.Now; }); using (var container = new RhetosTestContainer()) { var repository = container.Resolve<Common.DomRepository>().TestAutoCode.Simple; var generatedCodes = repository.Query().Select(item => item.Code).ToList(); var expected = Enumerable.Range(1, 2); Assert.AreEqual(TestUtility.DumpSorted(expected), TestUtility.DumpSorted(generatedCodes)); var codeByProcessReport = TestUtility.Dump(repository.Query() .OrderBy(item => item.Code) .Take(4) .Select(item => item.Data + ":" + item.Code)); Assert.IsTrue(codeByProcessReport == "0:1, 1:2" || codeByProcessReport == "1:1, 0:2"); TestUtility.DumpSorted(endTimes); var delay = Math.Abs(endTimes[0].Subtract(endTimes[1]).TotalMilliseconds); Console.WriteLine(delay); if (delay < 200) Assert.Fail("One process did not wait for another."); if (delay > 300) Assert.Inconclusive("System too slow. Delay should be a little above 200."); } } [TestMethod] public void ParallelInsertsLockingTestDifferentPrefix() { // Executing this test multiple time, to reduce system warm-up effects and performance instability. for (int retries = 0; retries < 4; retries++) { try { // One process may be executed in parallel with another, since they use different prefixes: var endTimes = new DateTime[2]; Execute2ParallelInserts(1, (process, repository) => { repository.Insert(new[] { new TestAutoCode.Simple { Code = (char)('a' + process) + "+", Data = process.ToString() } }); System.Threading.Thread.Sleep(200); endTimes[process] = DateTime.Now; }); using (var container = new RhetosTestContainer()) { var repository = container.Resolve<Common.DomRepository>().TestAutoCode.Simple; var generatedCodes = repository.Query().Select(item => item.Code).ToList(); var expected = new[] { "a1", "b1" }; Assert.AreEqual(TestUtility.DumpSorted(expected), TestUtility.DumpSorted(generatedCodes)); var codeByProcessReport = TestUtility.Dump(repository.Query() .OrderBy(item => item.Code) .Take(4) .Select(item => item.Data + ":" + item.Code)); Assert.AreEqual("0:a1, 1:b1", codeByProcessReport); TestUtility.DumpSorted(endTimes, item => item.ToString("o")); var delay = Math.Abs(endTimes[0].Subtract(endTimes[1]).TotalMilliseconds); Console.WriteLine(delay); if (delay < 200) Assert.Fail("One process did not wait for another."); if (delay > 300) Assert.Inconclusive("System too slow. Delay should be a little above 200."); } } catch (Exception ex) { if (retries > 0) { Console.WriteLine(ex); Console.WriteLine("Retrying " + retries + " more times."); } else throw; } } } private void Execute2ParallelInserts(int testCount, Action<int, TestAutoCode._Helper.Simple_Repository> action) { const int threadCount = 2; using (var container = new RhetosTestContainer(true)) { CheckForParallelism(container.Resolve<ISqlExecuter>(), threadCount); DeleteOldData(container); } for (int test = 1; test <= testCount; test++) { Console.WriteLine("Test: " + test); var containers = Enumerable.Range(0, threadCount).Select(t => new RhetosTestContainer(true)).ToArray(); try { var repositories = containers.Select(c => c.Resolve<Common.DomRepository>().TestAutoCode.Simple).ToArray(); foreach (var r in repositories) Assert.IsTrue(r.Query().Count() >= 0); // Cold start. Parallel.For(0, threadCount, process => { action(process, repositories[process]); containers[process].Dispose(); containers[process] = null; }); } finally { foreach (var c in containers) if (c != null) c.Dispose(); } } } [TestMethod] public void ParallelInsertsLockErrorHandling() { var actions = new Action<Common.ExecutionContext>[] { // Starts at 0 ms, ends at 400ms. context => { Thread.Sleep(0); context.SqlExecuter.ExecuteSql("SET LOCK_TIMEOUT 0"); context.Repository.TestAutoCode.Simple.Insert(new TestAutoCode.Simple { Code = "+" }); Thread.Sleep(400); }, // Starts at 100 ms, lock timeout at 300ms. context => { Thread.Sleep(100); context.SqlExecuter.ExecuteSql("SET LOCK_TIMEOUT 200"); context.Repository.TestAutoCode.Simple.Insert(new TestAutoCode.Simple { Code = "+" }); }, // Starts at 200 ms, lock timeout at 200ms. context => { Thread.Sleep(200); context.SqlExecuter.ExecuteSql("SET LOCK_TIMEOUT 0"); context.Repository.TestAutoCode.Simple.Insert(new TestAutoCode.Simple { Code = "+" }); }, // Starts at 200 ms, ends at 200ms. context => { Thread.Sleep(200); context.SqlExecuter.ExecuteSql("SET LOCK_TIMEOUT 0"); context.Repository.TestAutoCode.Simple.Load(item => item.Code == "1"); } }; var exceptions = ExecuteParallel(actions, context => context.Repository.TestAutoCode.Simple.Insert(new TestAutoCode.Simple { Code = "1" }), context => Assert.AreEqual(1, context.Repository.TestAutoCode.Simple.Query().Count())); Assert.IsNull(exceptions[0]); Assert.IsNotNull(exceptions[1]); Assert.IsNotNull(exceptions[2]); Assert.IsNull(exceptions[3]); // sql3 should be allowed to read the record with code '1'. sql0 has exclusive lock on code '2'. autocode should not put exclusive lock on other records. // Query sql1 may generate next autocode, but it should wait for the entity's table exclusive lock to be released (from sql0). TestUtility.AssertContains(exceptions[1].ToString(), new[] { "Cannot insert", "another user's insert command is still running", "TestAutoCode.Simple" }); // Query sql2 may not generate next autocode until sql1 releases the lock. TestUtility.AssertContains(exceptions[2].ToString(), new[] { "Cannot insert", "another user's insert command is still running", "TestAutoCode.Simple" }); } private Exception[] ExecuteParallel(Action<Common.ExecutionContext>[] actions, Action<Common.ExecutionContext> coldStartInsert, Action<Common.ExecutionContext> coldStartQuery) { int threadCount = actions.Count(); using (var container = new RhetosTestContainer(true)) { var sqlExecuter = container.Resolve<ISqlExecuter>(); CheckForParallelism(sqlExecuter, threadCount); DeleteOldData(container); coldStartInsert(container.Resolve<Common.ExecutionContext>()); } var containers = Enumerable.Range(0, threadCount).Select(t => new RhetosTestContainer(true)).ToArray(); var exceptions = new Exception[threadCount]; try { var contexts = containers.Select(c => c.Resolve<Common.ExecutionContext>()).ToArray(); foreach (var context in contexts) coldStartQuery(context); Parallel.For(0, threadCount, thread => { try { actions[thread].Invoke(contexts[thread]); } catch (Exception ex) { exceptions[thread] = ex; contexts[thread].PersistenceTransaction.DiscardChanges(); } finally { containers[thread].Dispose(); containers[thread] = null; } }); } finally { foreach (var c in containers) if (c != null) c.Dispose(); } for (int x = 0; x < threadCount; x++) Console.WriteLine("Exception " + x + ": " + exceptions[x] + "."); return exceptions; } private void CheckForParallelism(ISqlExecuter sqlExecuter, int requiredNumberOfThreads) { string sqlDelay01 = "WAITFOR DELAY '00:00:00.100'"; var sqls = new[] { sqlDelay01 }; sqlExecuter.ExecuteSql(sqls); // Possible cold start. var sw = Stopwatch.StartNew(); Parallel.For(0, requiredNumberOfThreads, x => { sqlExecuter.ExecuteSql(sqls, false); }); sw.Stop(); Console.WriteLine("CheckForParallelism: " + sw.ElapsedMilliseconds + " ms."); if (sw.ElapsedMilliseconds < 50) Assert.Fail("Delay is unexpectedly short: " + sw.ElapsedMilliseconds); if (sw.Elapsed.TotalMilliseconds > 190) Assert.Inconclusive(string.Format( "This test requires {0} parallel SQL queries. {0} parallel delays for 100 ms are executed in {1} ms.", requiredNumberOfThreads, sw.ElapsedMilliseconds)); } /// <summary> /// There is no need to lock all inserts. It should be allowed to insert different groups in parallel. /// </summary> [TestMethod] public void OptimizeParallelInsertsForDifferentGroups() { var tests = new ListOfTuples<string, string, bool> // Format: // 1. Records to insert (Grouping1-Grouping2) to entity MultipleGroups, with parallel requests. // 2. Expected generated codes (Code1-Code2) for each record. // 3. Whether the inserts should be executed in parallel. { { "A-B, A-B", "1-1, 2-2", false }, // Same Grouping1 and Grouping2: codes should be generated sequentially. { "A-B, A-C", "1-1, 2-1", false }, // Same Grouping1: Code1 should be generated sequentially. { "A-B, C-B", "1-1, 1-2", false }, // Same Grouping2: Code2 should be generated sequentially. { "A-B, C-D", "1-1, 1-1", true }, { "A-B, B-A", "1-1, 1-1", true }, }; var results = new ListOfTuples<string, string, bool>(); var report = new List<string>(); const int testPause = 100; const int retries = 4; foreach (var test in tests) { for (int retry = 0; retry < retries; retry++) { var items = test.Item1.Split(',').Select(item => item.Trim()).Select(item => item.Split('-')) .Select(item => new TestAutoCode.MultipleGroups { Grouping1 = item[0], Grouping2 = item[1] }) .ToArray(); var insertDurations = new double[items.Length]; var parallelInsertRequests = items.Select((item, x) => (Action<Common.ExecutionContext>) (context => { var sw = Stopwatch.StartNew(); context.Repository.TestAutoCode.MultipleGroups.Insert(item); insertDurations[x] = sw.Elapsed.TotalMilliseconds; Thread.Sleep(testPause); })) .ToArray(); var exceptions = ExecuteParallel(parallelInsertRequests, context => context.Repository.TestAutoCode.MultipleGroups.Insert(new TestAutoCode.MultipleGroups { }), context => Assert.AreEqual(1, context.Repository.TestAutoCode.MultipleGroups.Query().Count(), $"({test.Item1}) Test initialization failed.")); Assert.IsTrue(exceptions.All(e => e == null), $"({test.Item1}) Test initialization threw exception. See the test output for details"); // Check the generated codes: string generatedCodes; using (var container = new RhetosTestContainer(false)) { var repository = container.Resolve<Common.DomRepository>(); generatedCodes = TestUtility.DumpSorted( repository.TestAutoCode.MultipleGroups.Load(items.Select(item => item.ID)), x => $"{x.Code1}-{x.Code2}"); } // Check if the inserts were executed in parallel: bool startedImmediately = insertDurations.Any(t => t < testPause); bool executedInParallel = insertDurations.All(t => t < testPause); // It the parallelism check did not pass, try again to reduce false negatives when the test machine is under load. if (!startedImmediately || executedInParallel != test.Item3) { Console.WriteLine("Retry"); continue; } Assert.IsTrue(startedImmediately, $"({test.Item1}) At lease one item should be inserted without waiting. The test machine was probably under load during the parallelism test."); report.Add($"Test '{test.Item1}' insert durations: '{TestUtility.Dump(insertDurations)}'."); results.Add(test.Item1, generatedCodes, executedInParallel); break; } } Assert.AreEqual( string.Concat(tests.Select(test => $"{test.Item1} => {test.Item2} {(test.Item3 ? "parallel" : "sequential")}\r\n")), string.Concat(results.Select(test => $"{test.Item1} => {test.Item2} {(test.Item3 ? "parallel" : "sequential")}\r\n")), "Report: " + string.Concat(report.Select(line => "\r\n" + line))); } } }
kmeze/Rhetos
CommonConcepts/CommonConceptsTest/CommonConcepts.Test/AutoCodeTest.cs
C#
agpl-3.0
45,388
<?php /** * @author Vincent Petry <pvince81@owncloud.com> * * @copyright Copyright (c) 2017, ownCloud GmbH * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCP\Files\Storage; use OCP\Files\StorageNotAvailableException; /** * Storage adapter implementing most of the common methods from IStorage. * * @since 10.0 */ abstract class StorageAdapter extends \OC\Files\Storage\Common { /** * Get the identifier for the storage, * the returned id should be the same for every storage object that is created with the same parameters * and two storage objects with the same id should refer to two storages that display the same files. * * @return string storage id * @since 10.0 */ abstract public function getId(); /** * see http://php.net/manual/en/function.mkdir.php * implementations need to implement a recursive mkdir * * @param string $path * @return bool true on success, false otherwise * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function mkdir($path); /** * see http://php.net/manual/en/function.rmdir.php * * @param string $path * @return bool true on success, false otherwise * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function rmdir($path); /** * see http://php.net/manual/en/function.opendir.php * * @param string $path * @return resource|false * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function opendir($path); /** * see http://php.net/manual/en/function.stat.php * only the following keys are required in the result: size and mtime * * @param string $path * @return array|false * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function stat($path); /** * see http://php.net/manual/en/function.filetype.php * * @param string $path * @return string|false * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function filetype($path); /** * see http://php.net/manual/en/function.file_exists.php * * @param string $path * @return bool * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function file_exists($path); /** * see http://php.net/manual/en/function.unlink.php * * @param string $path * @return bool true on success, false otherwise * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function unlink($path); /** * see http://php.net/manual/en/function.fopen.php * * @param string $path * @param string $mode * @return resource|false * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function fopen($path, $mode); /** * see http://php.net/manual/en/function.touch.php * If the backend does not support the operation, false should be returned * * @param string $path * @param int $mtime * @return bool true on success, false otherwise * @throws StorageNotAvailableException if the storage is temporarily not available * @since 10.0 */ abstract public function touch($path, $mtime = NULL); }
jacklicn/owncloud
lib/public/Files/Storage/StorageAdapter.php
PHP
agpl-3.0
4,040
/*! * Ext JS Library 3.3.0 * Copyright(c) 2006-2010 Ext JS, Inc. * licensing@extjs.com * http://www.extjs.com/license */ /* * Ukrainian translations for ExtJS (UTF-8 encoding) * * Original translation by zlatko * 3 October 2007 * * Updated by dev.ashevchuk@gmail.com * 01.09.2009 */ Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">Завантаження...</div>'; if (Ext.View) { Ext.View.prototype.emptyText = "<Порожньо>"; } if (Ext.grid.GridPanel) { Ext.grid.GridPanel.prototype.ddText = "{0} обраних рядків"; } if (Ext.TabPanelItem) { Ext.TabPanelItem.prototype.closeText = "Закрити цю вкладку"; } if (Ext.form.Field) { Ext.form.Field.prototype.invalidText = "Хибне значення"; } if (Ext.LoadMask) { Ext.LoadMask.prototype.msg = "Завантаження..."; } Date.monthNames = [ "Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень" ]; Date.dayNames = [ "Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П’ятниця", "Субота" ]; if (Ext.MessageBox) { Ext.MessageBox.buttonText = { ok : "OK", cancel : "Відміна", yes : "Так", no : "Ні" }; } if (Ext.util.Format) { Ext.util.Format.date = function (v, format) { if (!v) return ""; if (!(v instanceof Date)) v = new Date(Date.parse(v)); return v.dateFormat(format || "d.m.Y"); }; } if (Ext.DatePicker) { Ext.apply(Ext.DatePicker.prototype, { todayText : "Сьогодні", minText : "Ця дата меньша за мінімальну допустиму дату", maxText : "Ця дата більша за максимальну допустиму дату", disabledDaysText : "", disabledDatesText : "", monthNames : Date.monthNames, dayNames : Date.dayNames, nextText : 'Наступний місяць (Control+Вправо)', prevText : 'Попередній місяць (Control+Вліво)', monthYearText : 'Вибір місяця (Control+Вверх/Вниз для вибору року)', todayTip : "{0} (Пробіл)", format : "d.m.y", okText : "&#160;OK&#160;", cancelText : "Відміна", startDay : 1 }); } if (Ext.PagingToolbar) { Ext.apply(Ext.PagingToolbar.prototype, { beforePageText : "Сторінка", afterPageText : "з {0}", firstText : "Перша сторінка", prevText : "Попередня сторінка", nextText : "Наступна сторінка", lastText : "Остання сторінка", refreshText : "Освіжити", displayMsg : "Відображення записів з {0} по {1}, всього {2}", emptyMsg : 'Дані для відображення відсутні' }); } if (Ext.form.TextField) { Ext.apply(Ext.form.TextField.prototype, { minLengthText : "Мінімальна довжина цього поля {0}", maxLengthText : "Максимальна довжина цього поля {0}", blankText : "Це поле є обов’язковим для заповнення", regexText : "", emptyText : null }); } if (Ext.form.NumberField) { Ext.apply(Ext.form.NumberField.prototype, { minText : "Значення у цьому полі не може бути меньше {0}", maxText : "Значення у цьому полі не може бути більше {0}", nanText : "{0} не є числом" }); } if (Ext.form.DateField) { Ext.apply(Ext.form.DateField.prototype, { disabledDaysText : "Не доступно", disabledDatesText : "Не доступно", minText : "Дата у цьому полі повинна бути більша {0}", maxText : "Дата у цьому полі повинна бути меньша {0}", invalidText : "{0} хибна дата - дата повинна бути вказана у форматі {1}", format : "d.m.y" }); } if (Ext.form.ComboBox) { Ext.apply(Ext.form.ComboBox.prototype, { loadingText : "Завантаження...", valueNotFoundText : undefined }); } if (Ext.form.VTypes) { Ext.apply(Ext.form.VTypes, { emailText : 'Це поле повинно містити адресу електронної пошти у форматі "user@example.com"', urlText : 'Це поле повинно містити URL у форматі "http:/'+'/www.example.com"', alphaText : 'Це поле повинно містити виключно латинські літери та символ підкреслення "_"', alphanumText : 'Це поле повинно містити виключно латинські літери, цифри та символ підкреслення "_"' }); } if (Ext.form.HtmlEditor) { Ext.apply(Ext.form.HtmlEditor.prototype, { createLinkText : 'Будь-ласка введіть адресу:', buttonTips : { bold : { title: 'Напівжирний (Ctrl+B)', text: 'Зробити напівжирним виділений текст.', cls: 'x-html-editor-tip' }, italic : { title: 'Курсив (Ctrl+I)', text: 'Зробити курсивом виділений текст.', cls: 'x-html-editor-tip' }, underline : { title: 'Підкреслений (Ctrl+U)', text: 'Зробити підкресленим виділений текст.', cls: 'x-html-editor-tip' }, increasefontsize : { title: 'Збільшити розмір', text: 'Збільшити розмір шрифта.', cls: 'x-html-editor-tip' }, decreasefontsize : { title: 'Зменьшити розмір', text: 'Зменьшити розмір шрифта.', cls: 'x-html-editor-tip' }, backcolor : { title: 'Заливка', text: 'Змінити колір фону для виділеного тексту або абзацу.', cls: 'x-html-editor-tip' }, forecolor : { title: 'Колір тексту', text: 'Змінити колір виділеного тексту або абзацу.', cls: 'x-html-editor-tip' }, justifyleft : { title: 'Вирівняти текст по лівому полю', text: 'Вирівнювання тексту по лівому полю.', cls: 'x-html-editor-tip' }, justifycenter : { title: 'Вирівняти текст по центру', text: 'Вирівнювання тексту по центру.', cls: 'x-html-editor-tip' }, justifyright : { title: 'Вирівняти текст по правому полю', text: 'Вирівнювання тексту по правому полю.', cls: 'x-html-editor-tip' }, insertunorderedlist : { title: 'Маркери', text: 'Почати маркований список.', cls: 'x-html-editor-tip' }, insertorderedlist : { title: 'Нумерація', text: 'Почати нумернований список.', cls: 'x-html-editor-tip' }, createlink : { title: 'Вставити гіперпосилання', text: 'Створення посилання із виділеного тексту.', cls: 'x-html-editor-tip' }, sourceedit : { title: 'Джерельний код', text: 'Режим редагування джерельного коду.', cls: 'x-html-editor-tip' } } }); } if (Ext.grid.GridView) { Ext.apply(Ext.grid.GridView.prototype, { sortAscText : "Сортувати по зростанню", sortDescText : "Сортувати по спаданню", lockText : "Закріпити стовпець", unlockText : "Відкріпити стовпець", columnsText : "Стовпці" }); } if (Ext.grid.PropertyColumnModel) { Ext.apply(Ext.grid.PropertyColumnModel.prototype, { nameText : "Назва", valueText : "Значення", dateFormat : "j.m.Y" }); } if (Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion) { Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, { splitTip : "Тягніть для зміни розміру.", collapsibleSplitTip : "Тягніть для зміни розміру. Подвійний клік сховає панель." }); }
daowzq/ExtNet
ext.net.community/Ext.Net/Build/Ext.Net/extnet/locale/ext-lang-uk.js
JavaScript
agpl-3.0
9,716
<table class="catalogue_table_view"> <thead> <tr> <th><?php echo __('Value');?></th> <th><?php echo __('Date from');?></th> <th><?php echo __('Date to');?></th> <th><?php echo __('Insurer');?></th> <th><?php echo __('Person of contact'); ?></th> <th></th> </tr> </thead> <tbody> <?php foreach($insurances as $insurance):?> <tr> <td> <?php echo $insurance->getFormatedInsuranceValue();?> </td> <td><?php echo $insurance->getDateFromMasked(ESC_RAW) ; ?></td> <td><?php echo $insurance->getDateToMasked(ESC_RAW);?></td> <td> <?php if($insurance->People): ?> <?php echo $insurance->People->getFamilyName();?> <?php else: ?> <?php echo '-'; ?> <?php endif; ?> </td> <td> <?php if($insurance->Contact): ?> <?php echo $insurance->Contact->getFormatedName();?> <?php else: ?> <?php echo '-'; ?> <?php endif; ?> </td> </tr> <?php endforeach;?> </tbody> </table>
eMerzh/Darwin
apps/backend/modules/cataloguewidgetview/templates/_insurances.php
PHP
agpl-3.0
1,079
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.statistics; import bisq.core.app.misc.ExecutableForAppWithP2p; import bisq.core.app.misc.ModuleForAppWithP2p; import bisq.common.UserThread; import bisq.common.app.AppModule; import lombok.extern.slf4j.Slf4j; @Slf4j public class StatisticsMain extends ExecutableForAppWithP2p { private static final String VERSION = "1.0.1"; private Statistics statistics; public StatisticsMain() { super("Bisq Statsnode", "bisq-statistics", "bisq_statistics", VERSION); } public static void main(String[] args) { log.info("Statistics.VERSION: " + VERSION); new StatisticsMain().execute(args); } @Override protected void doExecute() { super.doExecute(); checkMemory(config, this); keepRunning(); } @Override protected void addCapabilities() { } @Override protected void launchApplication() { UserThread.execute(() -> { try { statistics = new Statistics(); UserThread.execute(this::onApplicationLaunched); } catch (Exception e) { e.printStackTrace(); } }); } @Override protected void onApplicationLaunched() { super.onApplicationLaunched(); } /////////////////////////////////////////////////////////////////////////////////////////// // We continue with a series of synchronous execution tasks /////////////////////////////////////////////////////////////////////////////////////////// @Override protected AppModule getModule() { return new ModuleForAppWithP2p(config); } @Override protected void applyInjector() { super.applyInjector(); statistics.setInjector(injector); } @Override protected void startApplication() { super.startApplication(); statistics.startApplication(); } }
bitsquare/bitsquare
statsnode/src/main/java/bisq/statistics/StatisticsMain.java
Java
agpl-3.0
2,594
/* * Copyright (C) 2000 - 2014 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.workflow.api.model; import java.util.Iterator; /** * Interface describing a representation of the &lt;trigger&gt; element of a Process Model. */ public interface Trigger { /** * Get the name of the Trigger * @return parameter's name */ public String getName(); /** * Set the name of the Trigger * @param parameter 's name */ public void setName(String name); /** * Get the className of the Trigger * @return className */ public String getClassName(); /** * Set the className of the Trigger * @param className */ public void setClassName(String className); /** * Get the parameter specified by name * @param strName the parameter name * @return the parameters */ public Parameter getParameter(String strName); /** * Create an object implementing Parameter */ public Parameter createParameter(); /** * Add a Parameter to the collection */ public void addParameter(Parameter parameter); /** * Return an Iterator over the parameters collection */ public Iterator<Parameter> iterateParameter(); }
auroreallibe/Silverpeas-Core
core-services/workflow/src/main/java/org/silverpeas/core/workflow/api/model/Trigger.java
Java
agpl-3.0
2,272
/* * Please see the included README.md file for license terms and conditions. */ // This file is a suggested starting place for your code. // It is completely optional and not required. // Note the reference that includes it in the index.html file. /*jslint browser:true, devel:true, white:true, vars:true */ /*global $:false, intel:false app:false, dev:false, cordova:false */ // The telll advertising framework // it must be a global var if you want to use it globally var myAdFw = { status: null }; // for debuging //debug.log = //console.log(); ////console.log = function (){}; // define the instance players // the MockPlayer var myPlayer = { "error": "Player not loaded!!!" }; // the optional player var thePlayer = { "error": "Player not loaded!!!" }; var prjkPlayer = true; var moviePopupId; var photolinksSent = []; // default values for compatibility // TODO incorporate in functions in telllSDK var theHeight = $(window).height(); var actualPhotolink = 0; var highlightedPhotolink = 0; var phListSize = 7; var phListElementWidth = 77; var myPhotolinks = [ { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.00_180x90.jpg", "photolink": { "id": 0, "title": "Brad Pitt - IMDB", "description": "", "link": [ { "title": "Brad Pitt - IMDB", "description": "", "url": " http://www.imdb.com/name/nm0000093/?ref_=nv_sr_1" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.01_180x90.jpg", "photolink": { "id": 1, "title": "Ted Baker suit - Nordstrom", "description": "", "link": [ { "title": "Ted Baker suit - Nordstrom", "description": "", "url": "http://shop.nordstrom.com/c/mens-suits-sportcoats" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.02_180x90.jpg", "photolink": { "id": 2, "title": "George Clooney - IMDB", "description": "", "link": [ { "title": "George Clooney - IMDB", "description": "", "url": "http://www.imdb.com/name/nm0000123/" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.03_180x90.jpg", "photolink": { "id": 3, "title": "Armani suit - Celebrity Suit Shop", "description": "", "link": [ { "title": "Armani suit - Celebrity Suit Shop", "description": "", "url": "http://www.celebritysuitshop.com/product-category/movie-suits/oceans-11-12-and-13-suits/" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.04_180x90.jpg", "photolink": { "id": 4, "title": "Las Vegas Travel", "description": "", "link": [ { "title": "Las Vegas Travel", "description": "", "url": "http://lasvegas.com" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.05_180x90.jpg", "photolink": { "id": 5, "title": "Bellagio", "description": "", "link": [ { "title": "Bellagio", "description": "", "url": "https://www.bellagio.com/hotel/" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.06_180x90.jpg", "photolink": { "id": 6, "title": "MGM Grand", "description": "", "link": [ { "title": "MGM Grand", "description": "", "url": "https://www.mgmgrand.com" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.07_180x90.jpg", "photolink": { "id": 7, "title": "Luxor", "description": "", "link": [ { "title": "Luxor", "description": "", "url": "http://www.luxor.com" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.08_180x90.jpg", "photolink": { "title": "Ghurka vintage bag ", "description": "", "id": 8, "link": [ { "title": "Ghurka vintage bag ", "description": "", "url": "http://www.ghurka.com/cavalier-i-leather-duffel-bag-vintage-chestnut" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.09_180x90.jpg", "photolink": { "id": 9, "title": "John Varvatos bag ", "description": "", "link": [ { "title": "John Varvatos bag ", "description": "", "url": "https://www.johnvarvatos.com/moto-braid-duffle/4380241-CIP.html?dwvar_4380241-CIP_size=OSZ&dwvar_4380241-CIP_color=001#start=1" } ] } }, { "thumb": "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.10_180x90.jpg", "photolink": { "id": 10, "title": "Ford Taurus ", "description": "", "link": [ { "title": "Ford Taurus ", "description": "", "url": "http://www.ford.com/cars/taurus/" } ] } }, { "thumb": "/img/photolinks/45s/45sec_64_180x90.jpg", "photolink": { "id": 11, "title": "Levi's Jacket", "description": "Kanye wearing a Levi's jacket", "link": [ { "title": "Levi's Jacket", "description": "Kanye wearing a Levi's jacket", "url": "http://us.levi.com/family/index.jsp?categoryId=3146860&cp=3146842.3146845&ab=mdp_shopdept_outerwear_030613" } ] } }, { "thumb": "/img/photolinks/45s/45sec_60_180x90.jpg", "photolink": { "id": 12, "title": "Sean John Shirt", "description": " ", "link": [ { "title": "Sean John Shirt", "description": " ", "url": "http://www.seanjohn.com/Mens.htm?collection=Sportswear" } ] } }, { "thumb": "/img/photolinks/45s/45sec_124_180x90.jpg", "photolink": { "id": 13, "title": "Denim Jacket", "description": " ", "link": [ { "title": "Denim Jacket", "description": " ", "url": "http://www1.macys.com/shop/mens-clothing/sean-john-big-tall/Pageindex,Sortby,Productsperpage/2,ORIGINAL,40?id=23477&edge=hybrid" } ] } }, { "thumb": "/img/photolinks/45s/45sec_35_180x90.jpg", "photolink": { "id": 14, "title": "John Varvatos wear", "description": " ", "link": [ { "title": "John Varvatos wear", "description": " ", "url": "http://www.johnvarvatos.com/belts/" } ] } }, { "thumb": "/img/photolinks/45s/45sec_88_180x90.jpg", "photolink": { "id": 15, "title": "Xiao Wang necklace", "description": " ", "link": [ { "title": "Xiao Wang necklace", "description": " ", "url": "http://xiaowangnyc.com" } ] } }, { "thumb": "/img/photolinks/45s/45sec_48_180x90.jpg", "photolink": { "id": 16, "title": "Kanye's tumblr", "description": " ", "link": [ { "title": "Kanye's tumblr", "description": " ", "url": "http://kanyewestfashionstyle.tumblr.com" } ] } }, { "thumb": "/img/photolinks/45s/45sec_17_180x90.jpg", "photolink": { "id": 17, "title": "Rihanna Now website", "description": " ", "link": [ { "title": "Rihanna Now website", "description": " ", "url": "http://www.rihannanow.com" } ] } }, { "thumb": "/img/photolinks/45s/45sec_09_180x90.jpg", "photolink": { "id": 18, "title": "MCS necklace", "description": " ", "link": [ { "title": "MCS necklace", "description": " ", "url": "http://www.amazon.com/Gold-Figaro-Hollow-Chain-Necklace/dp/B016U4Y2VM/ref=sr_1_1?s=apparel&ie=UTF8&qid=1457056210&sr=1-1&nodeID=7141123011&keywords=MCS+necklace" } ] } }, { "thumb": "/img/photolinks/45s/45sec_97_180x90.jpg", "photolink": { "id": 19, "title": "Hair style", "description": " ", "link": [ { "title": "Hair style", "description": " ", "url": "http://stealherstyle.net/rihanna/?post_type=hair" } ] } }, { "thumb": "/img/photolinks/45s/45sec_93_180x90.jpg", "photolink": { "id": 20, "title": "45 sec - Wikipedia", "description": " ", "link": [ { "title": "45 sec - Wikipedia", "description": " ", "url": "http://en.wikipedia.org/wiki/FourFiveSeconds" } ] } }, { "thumb": "/img/photolinks/45s/45sec_72_180x90.jpg", "photolink": { "id": 21, "title": "Wellco Jungle Boots", "description": " ", "link": [ { "title": "Wellco Jungle Boots", "description": " ", "url": "http://www.amazon.com/Wellco-Mens-Imported-Jungle-Combat/dp/B0028QFJ9G" } ] } }, { "thumb": "/img/photolinks/45s/45sec_163_180x90.jpg", "photolink": { "id": 22, "title": "Levis Jeans", "description": " ", "link": [ { "title": "Levis Jeans", "description": " ", "url": "http://us.levi.com/family/index.jsp;jsessionid=SYp2VGCYC14SGj2vFn2wz372S7knYjPy1c17KyWsQGmc626cztHj!-1127866137?ab=Men_megaNav_Jeans+By+Style_511skinnyjean&cp=3146842.3146854&categoryId=3691990" } ] } }, { "thumb": "/img/photolinks/45s/45sec_78_180x90.jpg", "photolink": { "id": 23, "title": "Behind the scenes", "description": " ", "link": [ { "title": "Behind the scenes", "description": " ", "url": "https://www.youtube.com/watch?v=t9RfycFMnhI" } ] } }, { "thumb": "/img/photolinks/45s/45sec_167_180x90.jpg", "photolink": { "id": 24, "title": "Finger nails", "description": " ", "link": [ { "title": "Finger nails", "description": " ", "url": "http://stealherstyle.net/rihanna/?post_type=nails" } ] } }, { "thumb": "/img/photolinks/45s/45sec_53_180x90.jpg", "photolink": { "id": 25, "title": "Paul's Website", "description": " ", "link": [ { "title": "Paul's Website", "description": " ", "url": "http://www.paulmccartney.com/" } ] } }, { "thumb": "/img/photolinks/45s/45sec_172_180x90.jpg", "photolink": { "id": 26, "title": "Paul's Guitar", "description": " ", "link": [ { "title": "Paul's Guitar", "description": " ", "url": "http://www.thecanteen.com/mccartney1.html" } ] } }, { "thumb": "/img/photolinks/45s/45sec_3_180x90.jpg", "photolink": { "id": 27, "title": "Haus of Rihanna", "description": " ", "link": [ { "title": "Haus of Rihanna", "description": " ", "url": "http://hausofrihanna.com/" } ] } }, { "thumb": "/img/photolinks/45s/45sec_187_180x90.jpg", "photolink": { "id": 28, "title": "Inez & Vinoodh - The directors", "description": " ", "link": [ { "title": "Inez & Vinoodh - The directors", "description": " ", "url": "http://inezandvinoodh.com/video/" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_07_180x90.jpg", "photolink": { "id": 29, "title": "Rolls Royce Commercial", "description": "New Rolls Royce Wraith Coupe HD Sexy First Commercial Sexy 2015 Carjam TV HD Car TV Show", "link": [ { "title": "Rolls Royce Commercial", "description": "New Rolls Royce Wraith Coupe HD Sexy First Commercial Sexy 2015 Carjam TV HD Car TV Show", "url": "https://www.youtube.com/watch?v=Squv4KI751w" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_12_180x90.jpg", "photolink": { "id": 30, "title": "Daniel Craig - IMDB", "description": " ", "link": [ { "title": "Daniel Craig - IMDB", "description": " ", "url": "http://www.imdb.com/name/nm0185819/" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_16_180x90.jpg", "photolink": { "id": 31, "title": "Eva Green - IMDB", "description": " ", "link": [ { "title": "Eva Green - IMDB", "description": " ", "url": "http://www.imdb.com/name/nm1200692" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_17_180x90.jpg", "photolink": { "id": 32, "title": "Tiffany", "description": " ", "link": [ { "title": "Tiffany", "description": " ", "url": "http://www.tiffany.com/Shopping/Default.aspx?mcat=148204" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_22_180x90.jpg", "photolink": { "id": 33, "title": "Bahamas - Tourism Comercial", "description": " ", "link": [ { "title": "Bahamas - Tourism Comercial", "description": " ", "url": "https://vimeo.com/58748266" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_27_180x90.jpg", "photolink": { "id": 34, "title": "Helicopter Tour", "description": " ", "link": [ { "title": "Helicopter Tour", "description": " ", "url": "http://www.viator.com/tours/Miami/Miami-Helicopter-Tour/d662-5221HELI" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_25_180x90.jpg", "photolink": { "id": 35, "title": "Yacht Charter - 1", "description": " ", "link": [ { "title": "Yacht Charter - 1", "description": " ", "url": "http://www.boatbookings.com/yachting_content/bahamas_yacht_charter.php" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_31_180x90.jpg", "photolink": { "id": 36, "title": "Hotel Atlantis Bahamas", "description": " ", "link": [ { "title": "Hotel Atlantis Bahamas", "description": " ", "url": "http://www.tripadvisor.com.br/Hotel_Review-g147417-d507175-Reviews-Atlantis_Royal_Towers-Paradise_Island_New_Providence_Island_Bahamas.html" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_35_180x90.jpg", "photolink": { "id": 37, "title": "Neiman Marcus- Armani", "description": " ", "link": [ { "title": "Neiman Marcus- Armani", "description": " ", "url": "http://www.neimanmarcus.com/en-br/search.jsp?N=0&Ntt=armani+suits&_requestid=172548" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_43_180x90.jpg", "photolink": { "id": 38, "title": "Ferretti - Comercial", "description": " ", "link": [ { "title": "Ferretti - Comercial", "description": " ", "url": "https://www.youtube.com/watch?v=ztf5B-wEVlw" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_47_180x90.jpg", "photolink": { "id": 39, "title": "Ford Mondeo - Commercial", "description": " ", "link": [ { "title": "Ford Mondeo - Commercial", "description": " ", "url": "https://www.youtube.com/watch?v=naMdNlwYX6o" } ] } }, { "thumb": "/img/photolinks/casino_royale/casino_royale_48_180x90.jpg", "photolink": { "id": 40, "title": "Ray-Ban", "description": " ", "link": [ { "title": "Ray-Ban", "description": " ", "url": "http://www.ray-ban.com/usa/sunglasses/clp" } ] } } ] ////////////////////////////////// var trackms = [ { "points": [ { "x": 10, "y": 45, "t": 1.5 }, { "x": 14, "y": 40, "t": 5 }, { "x": 17, "y": 45, "t": 8 }, { "x": 18, "y": 45, "t": 9 }, { "x": 15, "y": 40, "t": 10 } ], "stopped": 1, "photolink": 0, "movie": 0 }, { "points": [ { "x": 15, "y": 40, "t": 16 }, { "x": 16, "y": 41, "t": 17 }, { "x": 17, "y": 42, "t": 20 }, { "x": 18, "y": 43, "t": 25 }, { "x": 21, "y": 45, "t": 28 } ], "stopped": 1, "photolink": 1, "movie": 0 }, { "points": [ { "x": 53, "y": 50, "t": 29 }, { "x": 53, "y": 50, "t": 30 }, { "x": 53, "y": 50, "t": 32 }, { "x": 53, "y": 50, "t": 33 }, { "x": 53, "y": 50, "t": 34 } ], "stopped": 1, "photolink": 2, "movie": 0 }, { "points": [ { "x": 50, "y": 55, "t": 36.5 }, { "x": 50, "y": 55, "t": 38 }, { "x": 50, "y": 55, "t": 39 }, { "x": 50, "y": 55, "t": 40 }, { "x": 51, "y": 55, "t": 42 } ], "stopped": 1, "photolink": 3, "movie": 0 }, { "points": [ { "x": 46, "y": 50, "t": 47 }, { "x": 46, "y": 50, "t": 49 }, { "x": 46, "y": 50, "t": 51 }, { "x": 46, "y": 50, "t": 52 }, { "x": 46, "y": 50, "t": 53 } ], "stopped": 1, "photolink": 4, "movie": 0 }, { "points": [ { "x": 20, "y": 50, "t": 53.5 }, { "x": 20, "y": 50, "t": 53.7 }, { "x": 20, "y": 50, "t": 54.3 }, { "x": 20, "y": 50, "t": 54.6 }, { "x": 20, "y": 50, "t": 55 } ], "stopped": 1, "photolink": 5, "movie": 0 }, { "points": [ { "x": 45, "y": 50, "t": 55.5 }, { "x": 45, "y": 50, "t": 57 } ], "stopped": 1, "photolink": 6, "movie": 0 }, { "points": [ { "x": 70, "y": 50, "t": 57.5 }, { "x": 70, "y": 50, "t": 57.8 }, { "x": 70, "y": 50, "t": 58 } ], "stopped": 1, "photolink": 7, "movie": 0 }, { "points": [ { "x": 28, "y": 60, "t": 60 }, { "x": 20, "y": 63, "t": 61 }, { "x": 15, "y": 65, "t": 63 }, { "x": 13, "y": 65, "t": 64 }, { "x": 12, "y": 66, "t": 65 } ], "stopped": 1, "photolink": 8, "movie": 0 }, { "points": [ { "x": 20, "y": 45, "t": 67 }, { "x": 25, "y": 55, "t": 68 }, { "x": 30, "y": 55, "t": 71 }, { "x": 43, "y": 55, "t": 73 }, { "x": 45, "y": 47, "t": 74 } ], "stopped": 1, "photolink": 9, "movie": 0 }, { "points": [ { "x": 70, "y": 60, "t": 75 }, { "x": 55, "y": 55, "t": 77 }, { "x": 48, "y": 50, "t": 78 }, { "x": 47, "y": 50, "t": 79 }, { "x": 47, "y": 50, "t": 80 } ], "stopped": 1, "photolink": 10, "movie": 0 }, { "id": 11, "stopped": 1, "photolink": 11, "points": [ { "x": 35, "y": 20, "t": 64 }, { "x": 35, "y": 18, "t": 67 } ], "movie": 1 }, { "id": 12, "stopped": 1, "photolink": 12, "points": [ { "x": 50, "y": 20, "t": 59 }, { "x": 49, "y": 17, "t": 63 } ], "movie": 1 }, { "id": 13, "stopped": 1, "photolink": 13, "points": [ { "x": 43, "y": 25, "t": 124 }, { "x": 42, "y": 24, "t": 130 } ], "movie": 1 }, { "id": 14, "stopped": 1, "photolink": 14, "points": [ { "x": 60, "y": 80, "t": 35 }, { "x": 40, "y": 85, "t": 45 } ], "movie": 1 }, { "id": 15, "stopped": 1, "photolink": 15, "points": [ { "x": 30, "y": 45, "t": 88 }, { "x": 60, "y": 40, "t": 93 } ], "movie": 1 }, { "id": 16, "stopped": 1, "photolink": 16, "points": [ { "x": 42, "y": 25, "t": 48 }, { "x": 43, "y": 35, "t": 54 } ], "movie": 1 }, { "id": 17, "stopped": 1, "photolink": 17, "points": [ { "x": 33, "y": 24, "t": 21 }, { "x": 29, "y": 24, "t": 23 } ], "movie": 1 }, { "id": 18, "stopped": 1, "photolink": 18, "points": [ { "x": 40, "y": 25, "t": 9 }, { "x": 55, "y": 35, "t": 13 } ], "movie": 1 }, { "id": 19, "stopped": 1, "photolink": 19, "points": [ { "x": 53, "y": 10, "t": 97 }, { "x": 50, "y": 10, "t": 100 } ], "movie": 1 }, { "id": 20, "stopped": 1, "photolink": 20, "points": [ { "x": 42, "y": 40, "t": 93 }, { "x": 43, "y": 35, "t": 95 } ], "movie": 2 }, { "id": 21, "stopped": 1, "photolink": 21, "points": [ { "x": 30, "y": 90, "t": 72 }, { "x": 33, "y": 89, "t": 75 } ], "movie": 2 }, { "id": 22, "stopped": 1, "photolink": 22, "points": [ { "x": 60, "y": 24, "t": 163 }, { "x": 63, "y": 24, "t": 165 } ], "movie": 2 }, { "id": 23, "stopped": 1, "photolink": 23, "points": [ { "x": 40, "y": 24, "t": 78 }, { "x": 43, "y": 24, "t": 82 } ], "movie": 2 }, { "id": 24, "stopped": 1, "photolink": 24, "points": [ { "x": 23, "y": 14, "t": 167 }, { "x": 22, "y": 15, "t": 169 } ], "movie": 2 }, { "id": 25, "stopped": 1, "photolink": 25, "points": [ { "x": 50, "y": 20, "t": 53 }, { "x": 52, "y": 18, "t": 56 } ], "movie": 2 }, { "id": 26, "stopped": 1, "photolink": 26, "points": [ { "x": 20, "y": 50, "t": 173 }, { "x": 25, "y": 55, "t": 175 } ], "movie": 2 }, { "id": 27, "stopped": 1, "photolink": 27, "points": [ { "x": 80, "y": 80, "t": 3 }, { "x": 63, "y": 30, "t": 10 } ], "movie": 2 }, { "id": 28, "stopped": 1, "photolink": 28, "points": [ { "x": 30, "y": 65, "t": 187 }, { "x": 30, "y": 54, "t": 200 } ], "movie": 2 }, { "id": 29, "stopped": 1, "photolink": 29, "points": [ { "x": 23, "y": 45, "t": 7 }, { "x": 23, "y": 45, "t": 10 } ], "movie": 2 }, { "id": 30, "stopped": 1, "photolink": 30, "points": [ { "x": 23, "y": 45, "t": 12 }, { "x": 23, "y": 45, "t": 15 } ], "movie": 2 }, { "id": 31, "stopped": 1, "photolink": 31, "points": [ { "x": 23, "y": 45, "t": 16 }, { "x": 23, "y": 45, "t": 19 } ], "movie": 2 }, { "id": 32, "stopped": 1, "photolink": 32, "points": [ { "x": 23, "y": 45, "t": 19 }, { "x": 23, "y": 45, "t": 21 } ], "movie": 2 }, { "id": 33, "stopped": 1, "photolink": 33, "points": [ { "x": 23, "y": 45, "t": 22 }, { "x": 23, "y": 45, "t": 25 } ], "movie": 2 }, { "id": 34, "stopped": 1, "photolink": 34, "points": [ { "x": 23, "y": 45, "t": 28 }, { "x": 23, "y": 45, "t": 31 }, ], "movie": 2 }, { "id": 35, "stopped": 1, "photolink": 35, "points": [ { "x": 23, "y": 45, "t": 25 }, { "x": 23, "y": 45, "t": 27 }, ], "movie": 2 }, { "id": 36, "stopped": 1, "photolink": 36, "points": [ { "x": 23, "y": 45, "t": 31 }, { "x": 23, "y": 45, "t": 33 }, ], "movie": 2 }, { "id": 37, "stopped": 1, "photolink": 37, "points": [ { "x": 23, "y": 45, "t": 35 }, { "x": 23, "y": 45, "t": 38 }, ], "movie": 2 }, { "id": 38, "stopped": 1, "photolink": 38, "points": [ { "x": 23, "y": 45, "t": 41 }, { "x": 23, "y": 45, "t": 43 }, ], "movie": 2 }, { "id": 39, "stopped": 1, "photolink": 39, "points": [ { "x": 23, "y": 45, "t": 47 }, { "x": 23, "y": 45, "t": 49 }, ], "movie": 2 }, { "id": 40, "stopped": 1, "photolink": 40, "points": [ { "x": 23, "y": 45, "t": 53 }, { "x": 23, "y": 45, "t": 56 }, ], "movie": 2 } ] /* var myPhotolinks = [ { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.00_180x90.jpg", photolink: { id: 0, title: "Brad Pitt - IMDB", description: "", link: [{ title: "Brad Pitt - IMDB", description: "", url: " http://www.imdb.com/name/nm0000093/?ref_=nv_sr_1" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.01_180x90.jpg", photolink: { id: 1, title: "Ted Baker suit - Nordstrom", description: "", link: [{ title: "Ted Baker suit - Nordstrom", description: "", url: "http://shop.nordstrom.com/c/mens-suits-sportcoats" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.02_180x90.jpg", photolink: { id: 2, title: "George Clooney - IMDB", description: "", link: [{ title: "George Clooney - IMDB", description: "", url: "http://www.imdb.com/name/nm0000123/" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.03_180x90.jpg", photolink: { id: 3, title: "Armani suit - Celebrity Suit Shop", description: "", link: [{ title: "Armani suit - Celebrity Suit Shop", description: "", url: "http://www.celebritysuitshop.com/product-category/movie-suits/oceans-11-12-and-13-suits/" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.04_180x90.jpg", photolink: { id: 4, title: "Las Vegas Travel", description: "", link: [{ title: "Las Vegas Travel", description: "", url: "http://lasvegas.com" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.05_180x90.jpg", photolink: { id: 5, title: "Bellagio", description: "", link: [{ title: "Bellagio", description: "", url: "https://www.bellagio.com/hotel/" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.06_180x90.jpg", photolink: { id: 6, title: "MGM Grand", description: "", link: [{ title: "MGM Grand", description: "", url: "https://www.mgmgrand.com" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.07_180x90.jpg", photolink: { id: 7, title: "Luxor", description: "", link: [{ title: "Luxor", description: "", url: "http://www.luxor.com" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.08_180x90.jpg", photolink: { title: "Ghurka vintage bag ", description: "", id: 8, link: [{ title: "Ghurka vintage bag ", description: "", url: "http://www.ghurka.com/cavalier-i-leather-duffel-bag-vintage-chestnut" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.09_180x90.jpg", photolink: { id: 9, title: "John Varvatos bag ", description: "", link: [{ title: "John Varvatos bag ", description: "", url: "https://www.johnvarvatos.com/moto-braid-duffle/4380241-CIP.html?dwvar_4380241-CIP_size=OSZ&dwvar_4380241-CIP_color=001#start=1" }] } }, { thumb: "http://webapp.telll.me/img/photolinks/photolinks_ocean_13.10_180x90.jpg", photolink: { id: 10, title: "Ford Taurus ", description: "", link: [{ title: "Ford Taurus ", description: "", url: "http://www.ford.com/cars/taurus/" }] } }, ]; var trackms = [{ points: [{ x: 10, y: 45, t: 1.5 }, { x: 14, y: 40, t: 5 }, { x: 17, y: 45, t: 8 }, { x: 18, y: 45, t: 9 }, { x: 15, y: 40, t: 10 }], stopped: 1, photolink: 0, }, { points: [{ x: 15, y: 40, t: 16 }, { x: 16, y: 41, t: 17 }, { x: 17, y: 42, t: 20 }, { x: 18, y: 43, t: 25 }, { x: 21, y: 45, t: 28 }], stopped: 1, photolink: 1, }, { points: [{ x: 53, y: 50, t: 29 }, { x: 53, y: 50, t: 30 }, { x: 53, y: 50, t: 32 }, { x: 53, y: 50, t: 33 }, { x: 53, y: 50, t: 34 }], stopped: 1, photolink: 2, }, { points: [{ x: 50, y: 55, t: 36.5 }, { x: 50, y: 55, t: 38 }, { x: 50, y: 55, t: 39 }, { x: 50, y: 55, t: 40 }, { x: 51, y: 55, t: 42 }], stopped: 1, photolink: 3, }, { points: [{ x: 46, y: 50, t: 47 }, { x: 46, y: 50, t: 49 }, { x: 46, y: 50, t: 51 }, { x: 46, y: 50, t: 52 }, { x: 46, y: 50, t: 53 }], stopped: 1, photolink: 4, }, { points: [{ x: 20, y: 50, t: 53.5 }, { x: 20, y: 50, t: 53.7 }, { x: 20, y: 50, t: 54.3 }, { x: 20, y: 50, t: 54.6 }, { x: 20, y: 50, t: 55 }], stopped: 1, photolink: 5, }, { points: [{ x: 45, y: 50, t: 55.5 }, { x: 45, y: 50, t: 57 }], stopped: 1, photolink: 6, }, { points: [{ x: 70, y: 50, t: 57.5 }, { x: 70, y: 50, t: 57.8 }, { x: 70, y: 50, t: 58 }], stopped: 1, photolink: 7, }, { points: [{ x: 28, y: 60, t: 60 }, { x: 20, y: 63, t: 61 }, { x: 15, y: 65, t: 63 }, { x: 13, y: 65, t: 64 }, { x: 12, y: 66, t: 65 }], stopped: 1, photolink: 8, }, { points: [{ x: 20, y: 45, t: 67 }, { x: 25, y: 55, t: 68 }, { x: 30, y: 55, t: 71 }, { x: 43, y: 55, t: 73 }, { x: 45, y: 47, t: 74 }], stopped: 1, photolink: 9, }, { points: [{ x: 70, y: 60, t: 75 }, { x: 55, y: 55, t: 77 }, { x: 48, y: 50, t: 78 }, { x: 47, y: 50, t: 79 }, { x: 47, y: 50, t: 80 }], stopped: 1, photolink: 10, }, ]; */ var agent = navigator.userAgent.toLowerCase(); // detect ios var isiOS = false; var isIpad = false; var isIphone = false; if (agent.indexOf('iphone') >= 0) { isiOS = true; isIphone = true; window.scrollTo(0, 1); } if (agent.indexOf('ipad') >= 0) { isiOS = true; isIpad = true; window.scrollTo(0, 1); } // detect android var isAndroid = false; if (agent.indexOf('android') >= 0) { isAndroid = true; } // play movie at youtube var isYoutube = false; if (location.search == "?youtube") { isYoutube = true; } // For improved debugging and maintenance of your app, it is highly // recommended that you separate your JavaScript from your HTML files. // Use the addEventListener() method to associate events with DOM elements. // For example: // var el ; // el = document.getElementById("id_myButton") ; // el.addEventListener("click", myEventHandler, false) ; // The function below is an example of the best way to "start" your app. // This example is calling the standard Cordova "hide splashscreen" function. // You can add other code to it or add additional functions that are triggered // by the same event or other events. function onAppReady() { if (navigator.splashscreen && navigator.splashscreen.hide) { // Cordova API detected navigator.splashscreen.hide(); } startTelll(function (t) { console.info("Its telll:", t); }); } $(function () { onAppReady(); }); //document.addEventListener("app.Ready", onAppReady, false); //document.addEventListener("deviceready", onAppReady, false) ; //document.addEventListener("onload", onAppReady, false) ; // The app.Ready event shown above is generated by the init-dev.js file; it // unifies a variety of common "ready" events. See the init-dev.js file for // more details. You can use a different event to start your app, instead of // this event. A few examples are shown in the sample code above. If you are // using Cordova plugins you need to either use this app.Ready event or the // standard Crordova deviceready event. Others will either not work or will // work poorly. // NOTE: change "dev.LOG" in "init-dev.js" to "true" to enable some //console.log // messages that can help you debug Cordova app initialization issues. function startTelll(cb) { //console.log('Starting telll ...'); $("#telll-stage").css("display","none"); // reformat the screen reformatScreen(); $(window).resize(function () { reformatScreen(); }); $(window).on('orientationchange', function (event) { reformatScreen(); }); // instabtiate the telll class myAdFw = new telllSDK.Telll(); // Dashboard does not work in iphones if (isIphone) $("#open-dashboard").next().detach(); if (isIphone) $("#open-dashboard").detach(); myAdFw.login(null, function () { // Workaround to reload page after login // TODO: solve this bug ... console.log("Login state: ", myAdFw.loginView.state); if (myAdFw.loginView.state == "authOk"){ location.reload(); } //////////////////////////// // open and control clickbox var clickbox = myAdFw.showClickbox(); //$("#popup-clickbox").removeClass("popup"); clickbox.on("show", function(){ $("#popup-clickbox").css("display", "none"); $("#clickbox").css("overflow","auto"); // mock to use demo clickbox //$("#clickbox").html("<iframe src='http://webapp.telll.me/demo/clickbox.html' border='0' width='100%' height='100%' style='border:none'></iframe>"); $("#popup-clickbox").find("button.close").unbind("click"); $("#popup-clickbox").find("button.close").on("click", function () { closeClickbox(); setTimeout(function(){$("#popup-clickbox").fadeOut();},1000); }); }); //////////////////////////// // Show stage //$("#telll-stage").fadeIn(2000); $("#telll-stage").show(); var movieToPlay = getParameter('m'); var timeToPlay = getParameter('t'); if ( movieToPlay && timeToPlay ){ //open video player telllDialog("Opening movie "+movieToPlay+" at time "+timeToPlay, 3000); setTimeout(function(){ myAdFw.getMovie(movieToPlay, function(mv){ myAdFw.moviesListView.emit('selected',mv); }); },3000); setTimeout(function(){ myAdFw.moviePageView.emit('playnow', myAdFw.movie); },5500); setTimeout(function(){ thePlayer.setPlay(); },7000); setTimeout(function(){ thePlayer.setPlayhead(Number(timeToPlay.toString())); },9500); showMovie(function( movie, player ) { ////console.log("Callback from showMovie ..."); ////console.log(myAdFw.movie); ////console.log(movie); // global player vars //myPlayer = player; //thePlayer = player; //var mp = myAdFw.moviePlayerView; // Load some default tag data //myAdFw.store.tags = trackms; //myAdFw.store.defaultTags = trackms; //myAdFw.store.photolinks = myPhotolinks; //myAdFw.store.defaultPhotolinks = myPhotolinks; }); } if (cb) cb(myAdFw); }); if (window.innerHeight < 350) $("div.notes").fadeOut("slow"); } /** to read query string */ function getParameter(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } /** Load photolinks and tags to store * */ function loadMovieData(m, cb) { var result = {}; var loaded = 0; me = this; //console.log("loadMovieData, movie to load: ", m); if (! m.photolinks) { myAdFw.getPhotolinksOfMovie(m.id, function(aPl){ //console.log("Result from loadMoviesData:"); //console.log("Movie:", m); //console.log("Actual photolinks", m.photolinks); //console.log("Photolinks:",aPl); //console.log("Store:", myAdFw.store); loaded ++; //console.log("State", loaded); result.photolinks = aPl; if (cb && loaded == 2) cb(m, result); }); } else { loaded ++; result.photolinks = m.photolinks; } if (! m.tags) { myAdFw.getTracks(m.id, function(er,da){ //console.log("Result from loadMoviesData:"); //console.log("Data: ", da); //console.log("Store:", myAdFw.store); loaded ++; //console.log("State", loaded); result.tags = da; if (cb && loaded == 2) cb(m, result); }); } else { loaded ++; result.tags = m.tags; } if (cb && loaded == 2) cb(m, data); } /** Create the movie screen: * Movies List * Player * Controls * Photolinks List */ function showMovie(cb) { //console.log("Begin showMovie ..."); telllWipeScreen($("#popup-movies-list"), null, function(){ myAdFw.showMoviesList(function (m) { myAdFw.store.tags = []; myAdFw.store.photolinks = []; // TODO: this hack bypass tws photolinks and trackmotions data // from loadMovieData, using the default tags for the 3 demo movies // in vars trackms and myPhotolinks //loadMovieData(m, function(movie, data){ // myAdFw.store.tags = data.tags.trackmotions; // myAdFw.store.photolinks = data.photolinks.photolinks; // if (! myAdFw.store.tags || ! myAdFw.store.tags.length) { // myAdFw.store.tags = trackms; // } // if (! myAdFw.store.photolinks || ! myAdFw.store.photolinks.length) { // myAdFw.store.photolinks = myPhotolinks; // } //}); myAdFw.store.tags = trackms; myAdFw.store.photolinks = myPhotolinks; console.log(m); m.photolinks = []; m.tags = []; if (m.id == 2) { for (var i = 29; i < 41; i++){ m.photolinks.push(myPhotolinks[i]); m.tags.push(trackms[i]); } } else if (m.id == 3){ for (var i = 0; i < 11; i++){ m.photolinks.push(myPhotolinks[i]); m.tags.push(trackms[i]); } } else if (m.id == 101){ for (var i = 11; i < 29; i++){ m.photolinks.push(myPhotolinks[i]); m.tags.push(trackms[i]); } } else { } myAdFw.store.tags = m.tags; myAdFw.store.photolinks = m.photolinks; ////// end hack //// var mp = myAdFw.showMoviePage(myAdFw.movie, function (mp, movie) { myAdFw.moviePageView = mp; }); mp.on("playnow", function (m) { myAdFw.showMockPlayer(function (mp) { myPlayer = mp; ////////////////////////////////////////////////////////// // instance the tagplayer myAdFw.showTagPlayer(myAdFw.moviePlayerView, function (tp) { tp.on("tag", function () { var offset = tp.actualPhotolink - highlightedPhotolink; scrollPhotolinksPanel(offset); if ($("input#automatic-photolink").prop('checked')){ sendPhotolink(tp.actualPhotolink, 'silent'); } }); //tp.on("send", function () { //console.log("Click tag: ", this); //}); }); ///////////////////////////////////////////////////// console.log(m); telllPopup($('#movie-player'), "Playing " + m.t.store.imdb.Title, function (myId) { // rebind close button $("#"+myId).find("button.close").on("click", function(){ $("#bottom-menu").fadeIn(); $("div#photolinks-list-widget").detach(); closeClickbox(); }); // create a timeline button var $tlbtn = $("<button class='favorite-blue-min'>Open Clickbox timeline</button>"); //.on('click', function(){ // showClickboxTimeline(); //}); var $tlbtnFrm = $("<div id='timeline-btn-frm'>Show timeline</div>").append($tlbtn).on('click', function(){ showClickboxTimeline(); }); $("#" + myId).find(".popup-titlebar").append($tlbtnFrm); // create a sliding titlebar $("#" + myId).find(".popup-titlebar").wrapAll("<div class='tpp-slide'><div class='tpp-slide-panel'></div></div>"); $("#movie-player").css({ position: 'fixed', top: '0px' }); $(".tpp-slide").css({ height: '40px', width: '100%', 'z-index': 'inherit', position: 'fixed', top: '0px' }); $(".tpp-slide-panel").stop().slideToggle(); $(".tpp-slide").on('mouseleave', function (e) { $(".tpp-slide-panel").stop().slideUp(); }); $(".tpp-slide").on('mouseenter', function (e) { $(".tpp-slide-panel").stop().slideDown(); }); }); /////////////////////////////////////// /** the photolinks list and panel ************************/ var list = myAdFw.showPhotolinksList(); list.once("open", function (pl) { // TODO hack to bypass data from tws about tags console.log(pl); console.log(myAdFw.movie); myAdFw.movie.tags = myAdFw.store.tags; myAdFw.movie.photolinks = myAdFw.store.photolinks; //createPhotolinksPanel(pl); createPhotolinksPanel(myAdFw.store); }); ////////////////////////////////////// // player listeners if (prjkPlayer) { launchPrjkPlayer(m, function (prjk) { if (cb) cb(myAdFw.movie, prjk); }); } else { adaptMockPlayer(); // put mock controls on panel $("div#mock-buttons").appendTo("div.popup-titlebar"); $("div#mock-buttons").css({ "float": "right", //"clear": "both" }); // hide mock dull stuff $("#title-pos").hide(); if (cb) cb(m, myPlayer); } // tag behaviors $("div.tag-label").on("click", function(e){ var ap = parseInt($(e.target).attr('id_photolink')); sendPhotolink(ap); }); checkMovieConsistency(); ////////////////////////////////////// }); }); }); }); // format movies list setTimeout(function () { formatMoviesList(); }, 600); //console.log("Ending showMovie"); } /** * @param movie {iData} * @param cb {function} its called after all setup tasks */ function launchPrjkPlayer(movie, cb) { //console.log("Launching PRJK"); /////////////////////////////////////// /** the pk movie player *********************/ projekktor('#telll-movie', { volume: 0.8, playerFlashMP4: 'js/projekktor/swf/StrobeMediaPlayback/StrobeMediaPlayback.swf', playerFlashMP3: 'js/projekktor/swf/StrobeMediaPlayback/StrobeMediaPlayback.swf', width: $('window').width(), height: $('window').height(), disallowSkip: false, //platforms: ['browser', 'flash'], //platforms: ['flash'], controls: true, enableFullscreen: false, useYTIframeAPI: true, }, function (player) { //console.log("PPlayer running callback..."); thePlayer = player; // reformat player $("#bottom-menu").fadeOut(); reformatPkPlayer(); $("div#mock-buttons").appendTo("div.popup-titlebar"); $("div#mock-buttons").css({ "float": "right", //"clear": "both" }); // rebind mock buttons $("div#mock-buttons button.pause").on("click", function () { thePlayer.setPause(); }); $("div#mock-buttons button.play").on("click", function () { thePlayer.setPlay(); }); $("div#mock-buttons button.stop").on("click", function () { thePlayer.setStop(); }); // hide mock dull stuff $("#title-pos").hide(); player.addListener('time', timeListener); player.addListener('state', stateListener); player.addListener('mouseenter', mouseEnterListener); player.addListener('touchstart', mouseEnterListener); player.addListener('mousedown', mouseDownListener); player.addListener('mouseleave', mouseLeaveListener); player.addListener('touchend', mouseLeaveListener); // is youtube? if (isYoutube) { var playlist = [{ 0: { src: "http://www.youtube.com/watch?v=ooWWBybEKHc", type: "video/youtube" } }]; player.setFile(playlist); player.setConfig({ platforms: ['flash'] }); player.setDebug(true); //console.log('Its Youtube'); //console.log(player); } // read state and reformat logo //console.log("Calling tagPlayerView.handleState", myAdFw.tagPlayerView); myAdFw.tagPlayerView.handleState(function (classe, i) { //console.log("Returning callback from tagPlayerView.handleState"); setTimeout(function () { if (!$(".logo-86x86").hasClass(classe[i])) { $.each(classe, function (tc) { $(".logo-86x86").removeClass(classe[tc]); }); $(".logo-86x86").removeAttr("style"); $(".logo-86x86").addClass(classe[i]); } }, 600); }); // Integrate PRJK controls with panel //$('.ppcontrols').appendTo($("#telll-controls")); //$('.ppcontrols').removeClass("active"); //$('.ppcontrols').addClass("inactive"); //player.setDebug(true); ////console.log("moviePlayer emit loaded!!"); //myAdFw.moviePlayerView.emit("loaded", movie); if (cb) cb(movie, player); }); ////////////////////////////////////// // Video behaviors // show labels when mouse over $("body *").on("touchstart", function(){tagBoomView();}); $("body *").on("mousemove", function(){tagBoomView();}); $("video").click(function(){tagBoomView();}); $("#movie-player").click(function(){tagBoomView();}); $("#telll-movie").click(function(){tagBoomView();}); $(".ppdisplay").click(function(){tagBoomView();}); var mouseDownListener = function () { tagBoomView(); //console.log("Toggle play/stop"); //sync MockPlayer if (myPlayer.state == "playing") { myAdFw.moviePlayerView.stop(); } else { myAdFw.moviePlayerView.play(); } }; var mouseEnterListener = function () { //tagDefaultView(); tagBoomView(); ////console.log("mouse over pk"); }; // hide labels 5 seconds after mouse out var mouseLeaveListener = function () { //tagNoneView(); }; // state listener callback var stateListener = function (state) { ////console.log(state); switch (state) { case 'PLAYING': // hide tags //tagDefaultView(); $('.ppcontrols').appendTo($(".ct-slide")); //$('.ppcontrols').appendTo($("#telll-controls")); //$('.ppcontrols').append($("#photolinks-list-widget")); break; case 'PAUSED': // sync player myAdFw.moviePlayerView.emit("pause", myAdFw.moviePlayerView.time); //sync MockPlayer myAdFw.moviePlayerView.state = "pause"; //sync MockPlayer tagNoneView(); break; case 'STOPPED': myAdFw.moviePlayerView.emit("stop", myAdFw.moviePlayerView.time); //sync MockPlayer myAdFw.moviePlayerView.state = "stop"; //sync MockPlayer highlightPhotolink(0); tagNoneView(); break; case 'COMPLETED': myAdFw.moviePlayerView.emit("ended", myAdFw.moviePlayerView.time); //sync MockPlayer myAdFw.moviePlayerView.state = "ended"; //sync MockPlayer showClickbox(); $("div.telll-popup").detach(); $("div#photolinks-list-widget").detach(); $("div#telll-tag-player-widget").detach(); $("div.popup-overlay").detach(); $("#" + moviePopupId + "-overlay").detach(); tagNoneView(); $("#bottom-menu").fadeIn(); break; } }; // time listener callback // triggered whenever playhead position changes (e.g. during playback) var timeListener = function (value) { var moviePosition = value; myAdFw.moviePlayerView.emit("timeupdate", value); //sync MockPlayer myAdFw.moviePlayerView.time = value; actualPhotolink = myAdFw.tagPlayerView.actualPhotolink || actualPhotolink; }; /** Behavior for * telll logo */ $('.logo-86x86').doubletap(function (e) { //console.log('Double Click!!!'); thePlayer.setPause(); // Show clickbox showClickbox(); }, function (e) { //console.log('Single Click!!!'); tagBoomView(); //telllDialog("Showing tag :)", 800); //sendPhotolink(actualPhotolink); }, 400); /** projekktor toolbar change * Adapt the panel (photolinksListWidget) */ $('.ppcontrols').on('cssClassChanged', function () { ////console.log("ppcontrols changed ..."); // setTimeOut(function(){ myAdFw.tagPlayerView.handleState(function (classe, i) { ////console.log("ppcontrols returned from handleState"); //if (! $(".logo-86x86").hasClass(classe[i])){ // remove any style from logo $.each(classe, function (tc) { $(".logo-86x86").removeClass(classe[tc]); }); $(".logo-86x86").removeAttr("style"); $(".logo-86x86").addClass(classe[i]); /*$(".logo-86x86").mouseover(function(){ $(".ct-slide-panel").show(); $("#photolinks-list-widget").removeClass("inactive"); $("#photolinks-list-widget").addClass("active"); });*/ $(".logo-86x86").on('mouseenter', function () { //telllDialog("Click on logo!!!", 800); $("#photolinks-list-widget").removeClass("inactive"); $("#photolinks-list-widget").addClass("active"); tagBoomView(); }); // its a joke but see if you like :) //$(".logo-86x86").on('mousemove', function (e) { //$(".ct-slide-panel").show(); //$("#photolinks-list-widget").removeClass("inactive"); //$("#photolinks-list-widget").addClass("active"); //tagBoomView(); //$('.logo-86x86').css({ // left: e.pageX - 15, // top: e.pageY - 15 //}); // }); if ($('.ppcontrols').hasClass('inactive')) { ////console.log('Controls inactive'); $("#telll-controls").css({ "height": '40px' }); } else { ////console.log('Controls active'); $("#telll-controls").css({ "height": '40px', "bottom": "38px" }); } //} }); // }, 200); }); /* $("div.ct-slide").on("mouseover", function(){ $('.ppcontrols').clearQueue(); $('.ppcontrols').removeClass("inactive"); $('.ppcontrols').addClass("active"); }); */ //console.log("Ended PRJK"); } // end launchPrjkPlayer /** Full window * Adjust viewport to full window */ function fullWindow() { $("#telll-player-frame").css('position', 'fixed'); $("#telll-player-frame").css('top', '0'); $("#telll-player-frame").css('left', '0'); $('#telll-movie').width($(window).width()); $('#telll-movie').height($(window).height()); $("#telll-player-frame").width($('#telll-movie').width()); $("#telll-player-frame").height($('#telll-movie').height()); $('#telll-pkt').width($('#telll-movie').width()); $('#telll-pkt').height($('#telll-movie').height()); theHeight = $(window).height(); } function formatMoviesList() { // width, height of widget and thumbs $(".telll-movies-list-widget").css({ width: "100%", height: "100%", opacity: 0 }); var thumbSize = { width: $("img.movie-thumb").width(), height: $("img.movie-thumb").height() }; var nThumbs = parseInt(($(window).width() / thumbSize.width)) || 1; var offSet = 14; var newThumbSize = { width: parseInt(($(window).width() / nThumbs)) - offSet || 1, height: parseInt((thumbSize.height * ($(window).width() / nThumbs / thumbSize.width) - offSet)) || 1 }; var newMargin = $(window).width() - ((newThumbSize.width + offSet) * nThumbs); ////console.log("Formating " + nThumbs + " elements ..."); ////console.log("From: ", thumbSize); ////console.log("To: ", newThumbSize); ////console.log("Window size ", $(window).width()); ////console.log("Thumbs size ", (newThumbSize.width + offSet) * nThumbs); $("img.movie-thumb").width(newThumbSize.width); $("div.telll-movie-element").width(newThumbSize.width); $("div.telll-movie-element").css({ "background-size": newThumbSize.width + "px " + newThumbSize.height + "px" }); $("div.movie-label").width(newThumbSize.width); $("img.movie-thumb").height(newThumbSize.height); $("div.telll-movie-element").height(newThumbSize.height); $("div.movie-label").height(newThumbSize.height); $("#telll-movies-list-frame").css("margin", newMargin + "px"); $("div.telll-movie-element:last").css("margin-bottom", "60px"); //$("#telll-movies-list-frame").width($(window).width -(newMargin*2)); ///////// //setTimeout(function(){ $(".telll-movies-list-widget").css({"opacity":"1"}); //}, 800); //$("#popup-movies-list").fadeIn(1000) } function checkMovieConsistency() { if ($('div[id="movie-player"]').size() > 1) { //console.log("Error", $('div[id="movie-player"]')); alert("Sorry, telll found an error, your page will be reloaded"); location.reload(); } } function reformatScreen() { centerStage(function(){centerStage()}); //centerStage(); adaptMockPlayer(); setPanelWidth(); $('#clickbox').height($(window).height()-40); } function centerStage(cb) { var height = $(window).height(); var stageSize; var marginTop; $("#telll-content").find("span.telll").first().css("font-size","100px"); $("#telll-content").css("font-size","16px"); $("div#menu").css({ "overflow": "inherit", "height": "100%" }); // reformat more on small screens if (height < 420){ // //console.log("reformat logo"); ////console.log($("#telll-content").find("span").first()); $("#telll-content").find("span.telll").first().css("font-size","50px"); $("#telll-content").css("font-size","12px"); $("div.boom-home").css({ "pading":"0px", "margin-bottom":"0px" }); } if (height < 321){ $("div#menu").css({ "overflow": "auto", "height": "140px" }); } stageSize = { width: $("div#telll-content").width()+$("div#menu").width(), //height: $("div#telll-content").height()+($("div.boom-home").height()*2) height: 350 // the sum of the widget higths TODO calculate it!!! }; marginTop = (height - stageSize.height - $("#bottom-menu").height())/2; if (marginTop < 0 ) marginTop = 0; $("div#telll-content").css("margin-top", marginTop + "px"); if (cb) cb(); } function reformatPkPlayer() { $(".telll-popup").css('position', 'fixed'); $(".telll-popup").css('top', '0'); $(".telll-popup").css('left', '0'); $('#movie-player').width($(window).width()); $('#movie-player').css("display", "block"); $('#movie-player').height($(window).height()); $(".telll-popup").width($('#movie-player').width()); $(".telll-popup").height($('#movie-player').height()); $('#telll-movie').width($('#movie-player').width()); $('#telll-movie').height($('#movie-player').height()); } // TODO: move it to the PhotolinksList class function setPanelWidth() { $('#panel-frame').width($(window).width()); $('#panel').width($(window).width() - 65); // set the number of icons to be displayed // this vat will be used by scrollPanel to phListSize = parseInt($("#panel").width() / ($(".frame-icon").width() + parseInt($('.frame-icon').css("margin-left")))); if (phListSize > myPhotolinks.length) phListSize = myPhotolinks.length; //center the panel in frame var iconWidth = $('.frame-icon').width() + parseInt($('.frame-icon').css("margin-left")); var iconsWidth = 0; $('.frame-icon').each(function (index) { iconsWidth += parseInt($(this).width(), 10); }); var offset = ($("#panel").width() - iconWidth * phListSize) / 2; //console.log("setPanelWidth: " + $("#panel").width() + " - " + iconWidth + " * " + phListSize + " = " + offset); $("#panel").css({ "margin-left": offset + "px", "width": ($("#panel").width() - offset) + "px" }); } /** * createPhotolinksPanel * TODO: move it to the PhotolinksList class * @param a {PhotolinksList} **/ function createPhotolinksPanel(a) { //console.log("Creating panel ..."); //console.log(a); // Fill panel with photolinks var photolinks = a.photolinks; //myPhotolinks = photolinks.concat(myPhotolinks); //myPhotolinks = photolinks.concat(myPhotolinks); // put myPhotolinks in store // TagPalyer uses a default photolinks list if store.photolinks is empty myAdFw.store.defaultPhotolinks = photolinks; if (photolinks.length > 0) $("#panel-slider").html(""); // clean panel for (var i = 0; i < photolinks.length; ++i) { ////console.log(photolinks[i]); var p = photolinks[i].photolink; p.thumb = photolinks[i].thumb; if (p.link.length === 0) { p.link = [{ title: "Telll Photolink" }]; } ////console.log(p); $("#panel-slider").append('<div class="frame-icon"><img class="photolink-icon" id="icon_' + p.id + '" src="' + p.thumb + '" id_photolink=' + p.id + '><label for="icon_' + p.id + '">' + p.link[0].title + '<label></div>'); } // set panel width setPanelWidth(); $("#photolinks-list-widget").css({ "bottom": '0px', "left": '0px' }); // trigger the closing popup from movie player and detach panel and tagplayer also $("#" + moviePopupId + " button.close").on("click", function () { $("#photolinks-list-widget").detach(); $("div#telll-tag-player-widget").detach(); }); // create a sliding control $("#telll-controls").wrapAll("<div class='ct-slide'><div class='ct-slide-panel'></div></div>"); $(".ct-slide").css({ height: '140px', width: '100%', 'z-index': 'inherit', position: 'absolute', bottom: '0px' }); //.on("mouseover", function(){ // $(".ct-slide-panel").show(); //}); $("#telll-controls").css({ "height": '65px' }); $("#telll-controls").show(); //$("#photolinks-list-widget").removeClass("active"); //$("#photolinks-list-widget").removeClass("inactive"); //$("#photolinks-list-widget").addClass("active"); //$(".ct-slide-panel").SlideDown("slow"); /*// close/open the panel $(".ct-slide-panel").stop().slideToggle(20, function(){ $("#photolinks-list-widget").addClass("inactive"); $("#photolinks-list-widget").removeClass("active"); });*/ $(".ct-slide").on('mouseenter', function (e) { $(".ct-slide-panel").fadeIn("slow", function () { $("#photolinks-list-widget").addClass("active"); $("#photolinks-list-widget").removeClass("inactive"); }); }); $(".ct-slide").on('mouseleave', function (e) { $(".ct-slide-panel").fadeOut("slow", function () { $("#photolinks-list-widget").addClass("inactive"); $("#photolinks-list-widget").removeClass("active"); }); }); $(".ct-slide").on('touchstart', function (e) { $(".ct-slide-panel").fadeIn("slow", function () { $("#photolinks-list-widget").addClass("active"); $("#photolinks-list-widget").removeClass("inactive"); }); }); $(".ct-slide").on('touchend', function (e) { $(".ct-slide-panel").fadeOut("slow", function () { $("#photolinks-list-widget").addClass("inactive"); $("#photolinks-list-widget").removeClass("active"); }); }); setTimeout(function () { $(".ct-slide-panel").fadeOut("slow", function () { $("#photolinks-list-widget").addClass("inactive"); $("#photolinks-list-widget").removeClass("active"); }); }, 5000); // mouse over show labels $(".frame-icon *").on("mouseover", function (e) { var thisid = $(this).attr('id'); $('label[for=' + thisid + ']').css("display", "inline"); tagBoomView(); }); $(".frame-icon *").on("mouseleave", function (e) { $('label').css("display", "none"); tagNoneView(); }); // touch : labels $(".frame-icon *").on("touchstart", function (e) { var thisid = $(this).attr('id'); tagBoomView(); $('label[for=' + thisid + ']').css("display", "inline"); }); $(".frame-icon *").on("touchend", function (e) { $('label').css("display", "none"); tagNoneView(); }); /* $(".frame-icon *").click(function() { sendPhotolink($(this).attr('id_photolink')); }); //$('.frame-icon *').dblclick(function (e) { */ $('.frame-icon *').doubletap(function (e) { //console.log('Double Click!!!'); thePlayer.setPause(); var ap = parseInt($(e.currentTarget).attr('id_photolink')); /////////////////////////////////////// // show dialog with photolinked webpage $('body').append('<div id="ph-dialog-' + ap + '"><iframe width="100%" height="100%" src="js/projekktor/themes/maccaco/buffering.gif"/></div>'); //path = '/cgi-bin/mirror.pl?url='+myPhotolinks[ap].link[0].url; //console.log(myPhotolinks); //console.log(e); //console.log($(e.srcElement).attr('id_photolink')); //console.log(ap); //console.log(myPhotolinks[ap]); var path = myPhotolinks[ap].photolink.link[0].url; //path = 'http://webapp.telll.me/cgi-bin/mirror.pl?url='+myPhotolinks[ap].photolink.link[0].url; $("#ph-dialog-" + ap + " iframe").attr('src', path); var linkPopup = telllPopup($("#ph-dialog-" + ap), myPhotolinks[ap].photolink.link[0].title); $("#ph-dialog-" + ap).css({ width: "100%", height: "100%" }); //$("<button id='show-in-movie'>Show in movie</button>").appendTo(".popup-titlebar"); $("<button id='show-in-movie'>Show in movie</button>").on("click", function () { //console.log("implement me please!"); telllDialog("Searching tag on movie ...", 2000); var position = trackms[ap].points[0].t; thePlayer.setPlay(); setTimeout(function () { $("#" + linkPopup).remove(); thePlayer.setPlayhead(Number(position.toString())); actualPhotolink = ap; }, 1500); }).appendTo("#" + linkPopup + " .popup-titlebar"); $("<button id='share-on-face'>Share on Facebook</button>").on("click", function () { //console.log("implement me please!"); telllDialog("Share on Facebook not yet implemented, sorry", 3000); }).appendTo("#" + linkPopup + " .popup-titlebar"); /* $("#ph-dialog-" + ap).dialog({ modal: true, width: '80%', height: theHeight - 5, title: myPhotolinks[ap].photolink.link[0].title, buttons: { "See in the movie": function() { var position = trackms[ap].points[0].t; $(this).dialog("close"); thePlayer.setPlay(); setTimeout(function() { thePlayer.setPlayhead(Number(position.toString())); actualPhotolink = ap; }, 500); $("<div data-role='popup' class='telll-popup'>Searching tag on movie ...</div>").appendTo('body'); $(".telll-popup").popup(); $(".telll-popup").popup("open", null); setTimeout(function() { $(".telll-popup").popup('close'); $(".telll-popup").detach(); }, 2000); } } }); $("#ph-dialog-" + ap).dialog("open"); */ ////////////////////////////////////////////////////////// }, function (e) { //console.log('Single Click!!!'); var ap = parseInt($(e.target).attr('id_photolink')); ////console.log('Sendind Photolink ... '+ap); ////console.log(e); sendPhotolink(ap); }, 400); /* $('img.photolink-icon').on('click', function(e) { //console.log('Single Click!!!'); var ap = parseInt($(e.target).attr('id_photolink')); ////console.log('Sendind Photolink ... '+ap); ////console.log(e); sendPhotolink(ap); }); */ $('#return-button').on('click', function (e) { scrollPhotolinksPanel(-1); }); $('#forward-button').on('click', function (e) { scrollPhotolinksPanel(1); }); //highlightPhotolink(0); //console.log("Panel created!!!"); } /* function highlightPhotolink(n) { pls = $("#panel").find('.frame-icon img'); ////console.log('---> ' + n); ////console.log(pls.eq(n)); pls.each(function(i) { ////console.log(pls.eq(i).attr('id_photolink')); //newSrc = pls.eq(i).find('img').attr('src').replace("_green.jpg", ".jpg"); //pls.eq(i).find('img').attr('src', newSrc); if (parseInt(pls.eq(i).attr('id_photolink')) != n) { pls.eq(i).css('opacity', '0.1'); } else { pls.eq(n).css('opacity', '1'); //console.log('highlighting ' + n); } }); // highlight actual photolink //newSrc = pls.eq(n).find('img').attr('src').replace(".jpg", "_green.jpg"); //pls.eq(n).find('img').attr('src', newSrc); //pls.eq(n).css({'width':'96px','height':'52px'}); } */ function scrollPhotolinksPanel(n) { //console.log("Scrolled by:"); //console.log(n); highlightedPhotolink += n; //console.log("Highlighted Photolink:"); //console.log(highlightedPhotolink); var pls = $("#panel").find('.frame-icon img'); //console.log(pls); // Catching some errors if (highlightedPhotolink > pls.length - 1) { highlightedPhotolink = parseInt(pls.length) - 1; } if (highlightedPhotolink < 0) { highlightedPhotolink = 0; } highlightPhotolink(highlightedPhotolink); // Scroll panel to position // claculate offset var ml = 0; //console.log("scroll pls:", pls); pls.each(function (i) { //console.log("scroll pls", i); if (parseInt(pls.eq(i).attr('id_photolink')) < highlightedPhotolink - Math.round(phListSize / 2) // && highlightedPhotolink < parseInt(pls.length) - Math.round(phListSize/2) ) { ml++; } }); var of = ml * phListElementWidth * -1; $('#panel-slider').animate({ 'margin-left': of + "px" }, 400, function () { //pls.eq(0).insertAfter(pls.eq(pls.length-1)); //pls.eq(0).css('margin-left',ml); //panelSliding = 0; //console.log('Panel scrolled by: ' + of); }); } /** Send photolink to clickbox * @param id */ function sendPhotolink(photolinkId, mode) { var plHtml = ""; var tag = myPhotolinks[photolinkId]; photolinksSent.push(tag); //for (var i = 0; i < photolinksSent.length; i++) { // plHtml += "<div class='photolink-list-element'><a href='" + photolinksSent[i].photolink.link[0].url + "'><span class='photolink-thumb'><img class='photolink-thumb-image' src='" + photolinksSent[i].thumb + "'></span><span class=photolink-title>" + photolinksSent[i].photolink.link[0].title + "</span><span class='photolink-description'>" + photolinksSent[i].photolink.link[0].description + "</span></a></div>"; //} //console.log("Sending photolink ... " + photolinkId); // clear some clickbox, open new and fill with html //$("#popup-clickbox").detach(); //myAdFw.showClickbox(); //$('#clickbox').html(plHtml); // send via cws var ret = myAdFw.cws.cmd.click_trackmotion({ api_key: "1234", auth_key: myAdFw.credentials.authKey, trackmotion: photolinkId, movie_id: myAdFw.movie.id, extra_data: escape('{"photolink":' + photolinkId + ', "title":"' + tag.photolink.title + '"' + ', "thumb":"' + tag.thumb + '"' + ', "link":"' + tag.photolink.link[0].url + '"' + ', "description":"' + btoa(escape(tag.photolink.description)) + '"' + ', "imdbPlot":"' + btoa(escape(myAdFw.store.imdb.Plot)) + '"' + //', "movie":' + myAdFw.movie.id + "}") // mock to use demo clickbox //extra_data:'{"photolinkbb":'+photolinkId+', "photolink":'+photolinkId +'}' }, function (resp) { ////console.log('Sent!'); if (mode != 'silent') { if (resp.error) { telllDialog("Error: " + resp.error, 3000); } else { telllDialog("Photolink sent!", 2000); } } }); } function highlightPhotolink(n) { var pls = $("#panel").find('.frame-icon img'); console.log('---> ' + n); console.log(pls.eq(n)); pls.each(function (i) { if (i != n) { pls.eq(i).css('opacity', '0.2'); } else { pls.eq(n).css('opacity', '1'); } }); } /** tagViews functions */ function tagDefaultView() { myAdFw.tagPlayerView.viewMode("default"); ////console.log("fade view in the tag"); //$("#telll-tag-player-widget").fadeIn(); $("#telll-tag-player-widget").attr("state","default"); } function tagNoneView() { myAdFw.tagPlayerView.viewMode("none"); $("#telll-tag-player-widget").attr("state","none"); ////console.log("not view the tag"); //$("#telll-tag-player-widget").fadeOut(); } function tagBoomView() { myAdFw.tagPlayerView.viewMode("boom"); $("#telll-tag-player-widget").attr("state","boom"); ////console.log("fade view in the tag"); //$("#telll-tag-player-widget").fadeOut(); //setTimeout(function(){ //$("#telll-tag-player-widget").removeClass("tgp-none").addClass("tgp-default").fadeOut(); ////console.log("view done", $("#telll-tag-player-widget")); //}, 800); } /** clickbox functions */ function closeClickbox() { $("#popup-clickbox").fadeOut("slow"); $("#popup-clickbox").removeClass("timeline"); } function showClickbox() { $("#popup-clickbox").fadeIn().css("z-index", 9999999); $("#popup-clickbox").removeClass("timeline"); } function showClickboxTimeline() { console.log("Open clickbox timeline"); $("#popup-clickbox").fadeIn().css("z-index", 9999999); $("#popup-clickbox").addClass("timeline"); } /** Player functions */ function adaptMockPlayer() { reformatPkPlayer(); $("div#movie-player").fadeIn(); $("video#telll-movie").fadeIn(); $("video#telll-movie").css("background", "black"); } function adaptApp() { adaptMockPlayer(); }
Telll/webapp
www/js/app.js
JavaScript
agpl-3.0
79,765
require 'test_helper' class BudgetRequestsControllerTest < ActionController::TestCase def setup @user1 = User.make login_as @user1 @budget_request = BudgetRequest.make end test "should get index" do get :index assert_response :success assert_not_nil assigns(:budget_requests) end test "should get CSV index" do get :index, :format => 'csv' assert_response :success assert_not_nil assigns(:budget_requests) end test "autocomplete" do lookup_instance = BudgetRequest.make get :index, :name => lookup_instance.name, :format => :autocomplete a = @response.body.de_json # try to deserialize the JSON to an array assert a.map{|elem| elem['value']}.include?(lookup_instance.id) end test "should confirm that name_exists" do get :index, :name => @budget_request.name, :format => :autocomplete a = @response.body.de_json # try to deserialize the JSON to an array assert a.map{|elem| elem['value']}.include?(@budget_request.id) end test "should get new" do get :new assert_response :success end test "should create budget_request" do assert_difference('BudgetRequest.count') do post :create, :budget_request => { :name => 'some random name for you', :request_id => 1 } end assert 201, @response.status assert @response.header["Location"] =~ /#{budget_request_path(assigns(:budget_request))}$/ end test "should show budget_request" do get :show, :id => @budget_request.to_param assert_response :success end test "should show budget_request with documents" do model_doc1 = ModelDocument.make(:documentable => @budget_request) model_doc2 = ModelDocument.make(:documentable => @budget_request) get :show, :id => @budget_request.to_param assert_response :success end test "should show budget_request with groups" do group = Group.make group_member1 = GroupMember.make :groupable => @budget_request, :group => group group_member2 = GroupMember.make :groupable => @budget_request, :group => group get :show, :id => @budget_request.to_param assert_response :success end test "should show budget_request with audits" do Audit.make :auditable_id => @budget_request.to_param, :auditable_type => @budget_request.class.name get :show, :id => @budget_request.to_param assert_response :success end test "should show budget_request audit" do get :show, :id => @budget_request.to_param, :audit_id => @budget_request.audits.first.to_param assert_response :success end test "should get edit" do get :edit, :id => @budget_request.to_param assert_response :success end test "should not be allowed to edit if somebody else is editing" do @budget_request.update_attributes :locked_until => (Time.now + 5.minutes), :locked_by_id => User.make.id get :edit, :id => @budget_request.to_param assert assigns(:not_editable) end test "should not be allowed to update if somebody else is editing" do @budget_request.update_attributes :locked_until => (Time.now + 5.minutes), :locked_by_id => User.make.id put :update, :id => @budget_request.to_param, :budget_request => {} assert assigns(:not_editable) end test "should update budget_request" do put :update, :id => @budget_request.to_param, :budget_request => {} assert flash[:info] assert 201, @response.status assert @response.header["Location"] =~ /#{budget_request_path(assigns(:budget_request))}$/ end test "should destroy budget_request" do delete :destroy, :id => @budget_request.to_param assert_not_nil @budget_request.reload().deleted_at end end
tendenci/recessart
vendor/gems/fluxx_grant/test/functional/budget_requests_controller_test.rb
Ruby
agpl-3.0
3,685
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.forms.rptcareplandetails; public interface IFormUILogicCode { // No methods yet. }
open-health-hub/openmaxims-linux
openmaxims_workspace/Nursing/src/ims/nursing/forms/rptcareplandetails/IFormUILogicCode.java
Java
agpl-3.0
1,807
/* * Copyright (C) 1994-2016 Altair Engineering, Inc. * For more information, contact Altair at www.altair.com. * * This file is part of the PBS Professional ("PBS Pro") software. * * Open Source License Information: * * PBS Pro 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. * * PBS Pro is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * Commercial License Information: * * The PBS Pro software is licensed under the terms of the GNU Affero General * Public License agreement ("AGPL"), except where a separate commercial license * agreement for PBS Pro version 14 or later has been executed in writing with Altair. * * Altair’s dual-license business model allows companies, individuals, and * organizations to create proprietary derivative works of PBS Pro and distribute * them - whether embedded or bundled with other software - under a commercial * license agreement. * * Use of Altair’s trademarks, including but not limited to "PBS™", * "PBS Professional®", and "PBS Pro™" and Altair’s logos is subject to Altair's * trademark licensing policies. * */ /** * @file dec_DelHookFile.c */ #include <pbs_config.h> /* the master config generated by configure */ #include <sys/types.h> #include <stdlib.h> #include "libpbs.h" #include "list_link.h" #include "server_limits.h" #include "attribute.h" #include "credential.h" #include "batch_request.h" #include "dis.h" /** * @brief * Decode data item(s) needed for a Delete Hook File request. * * Data item is: string hook filename * cnt str data * * @param[in] sock - communication channel * @param[in/out] preq - request structure to fill in * * @return int * @retval 0 for success * @retval non-zero otherwise */ int decode_DIS_DelHookFile(int sock, struct batch_request *preq) { int rc; if ((rc = disrfst(sock, MAXPATHLEN+1, preq->rq_ind.rq_hookfile.rq_filename)) != 0) return rc; return 0; }
vinodchitrali/pbspro
src/lib/Libifl/dec_DelHookFile.c
C
agpl-3.0
2,483
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.careuk.vo.beans; public class TheatreListBookingDetailVoBean extends ims.vo.ValueObjectBean { public TheatreListBookingDetailVoBean() { } public TheatreListBookingDetailVoBean(ims.careuk.vo.TheatreListBookingDetailVo vo) { this.tcitime = vo.getTCITime(); this.proceduretext = vo.getProcedureText(); this.theatretext = vo.getTheatreText(); this.los = vo.getLOS(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.careuk.vo.TheatreListBookingDetailVo vo) { this.tcitime = vo.getTCITime(); this.proceduretext = vo.getProcedureText(); this.theatretext = vo.getTheatreText(); this.los = vo.getLOS(); } public ims.careuk.vo.TheatreListBookingDetailVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.careuk.vo.TheatreListBookingDetailVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.careuk.vo.TheatreListBookingDetailVo vo = null; if(map != null) vo = (ims.careuk.vo.TheatreListBookingDetailVo)map.getValueObject(this); if(vo == null) { vo = new ims.careuk.vo.TheatreListBookingDetailVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public String getTCITime() { return this.tcitime; } public void setTCITime(String value) { this.tcitime = value; } public String getProcedureText() { return this.proceduretext; } public void setProcedureText(String value) { this.proceduretext = value; } public String getTheatreText() { return this.theatretext; } public void setTheatreText(String value) { this.theatretext = value; } public Integer getLOS() { return this.los; } public void setLOS(Integer value) { this.los = value; } private String tcitime; private String proceduretext; private String theatretext; private Integer los; }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/careuk/vo/beans/TheatreListBookingDetailVoBean.java
Java
agpl-3.0
3,576
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-15 06:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0034_auto_20170613_2039'), ] operations = [ migrations.AddField( model_name='siteconfiguration', name='base_cookie_domain', field=models.CharField(blank=True, default=b'', help_text='Base cookie domain used to share cookies across services.', max_length=255, verbose_name='Base Cookie Domain'), ), ]
edx/ecommerce
ecommerce/core/migrations/0035_siteconfiguration_base_cookie_domain.py
Python
agpl-3.0
562
<?php require dirname(dirname(__DIR__)).'/header.php'; ?> <div class="page-header"><h3>Checkin - Logs</h3></div> <table class="table table-hover"> <thead><tr> <th><?php echo $lang['USERS']; ?></th> <th><?php echo $lang['TIMES']; ?></th> <th>IP</th> <th>Header</th> </tr></thead> <tbody> <?php $result = $conn->query("SELECT firstname, lastname, remoteAddr, userAgent, time FROM checkinLogs LEFT JOIN logs ON indexIM = timestampID LEFT JOIN UserData ON userID = UserData.id"); echo $conn->error; while($row = $result->fetch_assoc()){ echo '<tr>'; echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>'; echo '<td>'.$row['time'].'</td>'; echo '<td>'.$row['remoteAddr'].'</td>'; echo '<td>'.$row['userAgent'].'</td>'; echo '</tr>'; } ?> </tbody> </table> <?php require dirname(dirname(__DIR__)).'/footer.php'; ?>
eitea/Connect
src/core/system/checkinLogs.php
PHP
agpl-3.0
910
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.forms.securitytokenadmin; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } public static class grd1SecTokenRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grd1SecTokenRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setexpirationReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isexpirationReadOnly() { return super.row.isReadOnly(0); } public void showexpirationOpened() { super.row.showOpened(0); } public void setTooltipForexpiration(String value) { super.row.setTooltip(0, value); } public String getexpiration() { return (String)super.row.get(0); } public void setexpiration(String value) { super.row.set(0, value); } public void setCellexpirationTooltip(String value) { super.row.setTooltip(0, value); } public void setsectokenReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean issectokenReadOnly() { return super.row.isReadOnly(1); } public void showsectokenOpened() { super.row.showOpened(1); } public void setTooltipForsectoken(String value) { super.row.setTooltip(1, value); } public String getsectoken() { return (String)super.row.get(1); } public void setsectoken(String value) { super.row.set(1, value); } public void setCellsectokenTooltip(String value) { super.row.setTooltip(1, value); } public ims.core.admin.vo.SecurityTokenRefVo getValue() { return (ims.core.admin.vo.SecurityTokenRefVo)super.row.getValue(); } public void setValue(ims.core.admin.vo.SecurityTokenRefVo value) { super.row.setValue(value); } } public static class grd1SecTokenRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grd1SecTokenRowCollection(GridRowCollection collection) { super(collection); } public grd1SecTokenRow get(int index) { return new grd1SecTokenRow(super.collection.get(index)); } public grd1SecTokenRow newRow() { return new grd1SecTokenRow(super.collection.newRow()); } public grd1SecTokenRow newRow(boolean autoSelect) { return new grd1SecTokenRow(super.collection.newRow(autoSelect)); } public grd1SecTokenRow newRowAt(int index) { return new grd1SecTokenRow(super.collection.newRowAt(index)); } public grd1SecTokenRow newRowAt(int index, boolean autoSelect) { return new grd1SecTokenRow(super.collection.newRowAt(index, autoSelect)); } } public static class grd1SecTokenGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } public ims.core.admin.vo.SecurityTokenRefVo[] getValues() { ims.core.admin.vo.SecurityTokenRefVo[] listOfValues = new ims.core.admin.vo.SecurityTokenRefVo[this.getRows().size()]; for(int x = 0; x < this.getRows().size(); x++) { listOfValues[x] = this.getRows().get(x).getValue(); } return listOfValues; } public ims.core.admin.vo.SecurityTokenRefVo getValue() { return (ims.core.admin.vo.SecurityTokenRefVo)super.grid.getValue(); } public void setValue(ims.core.admin.vo.SecurityTokenRefVo value) { super.grid.setValue(value); } public grd1SecTokenRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grd1SecTokenRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grd1SecTokenRowCollection getRows() { return new grd1SecTokenRowCollection(super.grid.getRows()); } public grd1SecTokenRow getRowByValue(ims.core.admin.vo.SecurityTokenRefVo value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grd1SecTokenRow(row); } public void setexpirationHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getexpirationHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setsectokenHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getsectokenHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); // Context Menus contextMenus = new ContextMenus(); contextMenus.contextMenuAddRemoveItems = factory.createMenu(startControlID.intValue() + 1); contextMenus.contextMenuAddRemoveItemsADDItem = factory.createMenuItem(startControlID.intValue() + 1, "Add", true, false, new Integer(102179), true, false); contextMenus.contextMenuAddRemoveItems.add(contextMenus.contextMenuAddRemoveItemsADDItem); contextMenus.contextMenuAddRemoveItemsREMOVEITEMItem = factory.createMenuItem(startControlID.intValue() + 2, "Remove", true, false, new Integer(102148), true, false); contextMenus.contextMenuAddRemoveItems.add(contextMenus.contextMenuAddRemoveItemsREMOVEITEMItem); form.registerMenu(contextMenus.contextMenuAddRemoveItems); // Panel Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 8, 0, 832, 32, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,"Security Token Administration", new Integer(1), ""})); // Label Controls RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 8, 40, 47, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.HIDDEN, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "For Date", new Integer(0), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 280, 40, 75, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.HIDDEN, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Search", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Date Controls RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 64, 40, 200, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), new Integer(-1), ControlState.HIDDEN, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null})); // Grid Controls RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 8, 40, 832, 584, ims.framework.enumerations.ControlAnchoring.ALL); Grid m_grd1SecTokenTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), new Integer(-1), ControlState.READONLY, ControlState.READONLY, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.TRUE, contextMenus.contextMenuAddRemoveItems, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grd1SecTokenTemp); grd1SecTokenGrid grd1SecToken = (grd1SecTokenGrid)GridFlyweightFactory.getInstance().createGridBridge(grd1SecTokenGrid.class, m_grd1SecTokenTemp); grd1SecToken.addStringColumn("Expiration", 0, 0, 250, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grd1SecToken.addStringColumn("Security Token", 0, 0, -1, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); super.addGrid(grd1SecToken); } public Button btnSearch() { return (Button)super.getControl(2); } public DateControl dte1() { return (DateControl)super.getControl(3); } public grd1SecTokenGrid grd1SecToken() { return (grd1SecTokenGrid)super.getGrid(0); } public final class ContextMenus implements java.io.Serializable { private static final long serialVersionUID = 1L; public final class AddRemoveItems implements java.io.Serializable { private static final long serialVersionUID = 1L; public static final int ADD = 1; public static final int REMOVEITEM = 2; } public void disableAllAddRemoveItemsMenuItems() { this.contextMenuAddRemoveItemsADDItem.setEnabled(false); this.contextMenuAddRemoveItemsREMOVEITEMItem.setEnabled(false); } public void hideAllAddRemoveItemsMenuItems() { this.contextMenuAddRemoveItemsADDItem.setVisible(false); this.contextMenuAddRemoveItemsREMOVEITEMItem.setVisible(false); } private Menu contextMenuAddRemoveItems; public MenuItem getAddRemoveItemsADDItem() { return this.contextMenuAddRemoveItemsADDItem; } private MenuItem contextMenuAddRemoveItemsADDItem; public MenuItem getAddRemoveItemsREMOVEITEMItem() { return this.contextMenuAddRemoveItemsREMOVEITEMItem; } private MenuItem contextMenuAddRemoveItemsREMOVEITEMItem; } private ContextMenus contextMenus; public ContextMenus getContextMenus() { return this.contextMenus; } private IReportField[] getFormReportFields() { if(this.context == null) return null; if(this.reportFields == null) this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields(); return this.reportFields; } private class ReportFields { public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { this.context = context; this.formInfo = formInfo; this.componentIdentifier = componentIdentifier; } public IReportField[] getReportFields() { String prefix = formInfo.getLocalVariablesPrefix(); IReportField[] fields = new IReportField[144]; fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient"); fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex"); fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob"); fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod"); fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion"); fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive"); fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin"); fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus"); fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN"); fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation"); fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath"); fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient"); fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant"); fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DEMENTIABREACHDATETIME", "DementiaBreachDateTime"); fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DEMENTIAWORKLISTSTATUS", "DementiaWorklistStatus"); fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MRNSTATUS", "MRNStatus"); fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-HASSCANNEDCASENOTEFOLDERS", "HasScannedCaseNoteFolders"); fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISCONFIDENTIAL", "IsConfidential"); fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFBIRTH", "TimeOfBirth"); fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-PATIENTCATEGORY", "PatientCategory"); fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient"); fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex"); fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob"); fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact"); fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty"); fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType"); fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime"); fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime"); fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext"); fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated"); fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp"); fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType"); fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive"); fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPAENDOSCOPIST", "IsHCPaEndoscopist"); fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context"); fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate"); fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime"); fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime"); fields[42] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType"); fields[43] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP"); fields[44] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare"); fields[45] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell"); fields[46] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty"); fields[47] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship"); fields[48] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate"); fields[49] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate"); fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote"); fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType"); fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline"); fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact"); fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote"); fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview"); fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[58] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime"); fields[59] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected"); fields[60] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed"); fields[61] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote"); fields[62] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime"); fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport"); fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext"); fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[66] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-ID", "ID_NAESReferral"); fields[67] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-DATEREFERRALRECEIVED", "DateReferralReceived"); fields[68] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-DATEOFSURGERY", "DateOfSurgery"); fields[69] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRINGHOSPITAL", "ReferringHospital"); fields[70] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRINGDOCTOR", "ReferringDoctor"); fields[71] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRALREASON", "ReferralReason"); fields[72] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-SECONDARYSURGERY", "SecondarySurgery"); fields[73] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-UNDERLYINGREASON", "UnderlyingReason"); fields[74] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-AFFECTEDEYE", "AffectedEye"); fields[75] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-IMPLANT", "Implant"); fields[76] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-IMPLANTTYPE", "ImplantType"); fields[77] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-INTERPRETERREQUIRED", "InterpreterRequired"); fields[78] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-LANGUAGE", "Language"); fields[79] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-LANGUAGEIFOTHER", "LanguageIfOther"); fields[80] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERREDBY", "ReferredBy"); fields[81] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-_6WEEKKPI", "SixWeekKPI"); fields[82] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-_3WEEKKPI", "ThreeWeekKPI"); fields[83] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-PREFERREDCLINIC", "PreferredClinic"); fields[84] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-NOTES", "Notes"); fields[85] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState"); fields[86] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission"); fields[87] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus"); fields[88] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode"); fields[89] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate"); fields[90] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[91] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview"); fields[92] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[93] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[94] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext"); fields[95] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[96] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-NOTETYPE", "NoteType"); fields[97] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-FORREVIEW", "ForReview"); fields[98] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[99] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-ID", "ID_ObservationForm"); fields[100] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-FORMTYPE", "FormType"); fields[101] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DETAILS", "Details"); fields[102] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DATETIMESTART", "DateTimeStart"); fields[103] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DATETIMESTOP", "DateTimeStop"); fields[104] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-ISSTOPPED", "IsStopped"); fields[105] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-CARECONTEXT", "CareContext"); fields[106] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-CLINICALCONTACT", "ClinicalContact"); fields[107] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-ID", "ID_MedicationOverview"); fields[108] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-TYPE", "Type"); fields[109] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-CARECONTEXT", "CareContext"); fields[110] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview"); fields[111] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-TYPE", "Type"); fields[112] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext"); fields[113] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview"); fields[114] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-TYPE", "Type"); fields[115] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext"); fields[116] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview"); fields[117] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-TYPE", "Type"); fields[118] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext"); fields[119] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ID", "ID_Urinalysis"); fields[120] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NOABNORMALITYDETECTED", "NoAbnormalityDetected"); fields[121] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-LEUCOCYTES", "Leucocytes"); fields[122] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-PROTEIN", "Protein"); fields[123] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-BLOOD", "Blood"); fields[124] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-KETONES", "Ketones"); fields[125] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ASCORBICACID", "AscorbicAcid"); fields[126] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-GLUCOSE", "Glucose"); fields[127] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-BILIRUBIN", "Bilirubin"); fields[128] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-UROBILINOGEN", "Urobilinogen"); fields[129] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NITRATE", "Nitrate"); fields[130] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-PH", "PH"); fields[131] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-SPECIFICGRAVITY", "SpecificGravity"); fields[132] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NOSAMPLE", "NoSample"); fields[133] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ISACTIVE", "IsActive"); fields[134] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-CARECONTEXT", "CareContext"); fields[135] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-ID", "ID_Patient"); fields[136] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-SEX", "Sex"); fields[137] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-DOB", "Dob"); fields[138] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-ID", "ID_Patient"); fields[139] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-SEX", "Sex"); fields[140] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-DOB", "Dob"); fields[141] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent"); fields[142] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails"); fields[143] = new ims.framework.ReportField(this.context, "_cvp_RefMan.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral"); return fields; } protected Context context = null; protected ims.framework.FormInfo formInfo; protected String componentIdentifier; } public String getUniqueIdentifier() { return null; } private Context context = null; private ims.framework.FormInfo formInfo = null; private String componentIdentifier; private IReportField[] reportFields = null; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Admin/src/ims/admin/forms/securitytokenadmin/GenForm.java
Java
agpl-3.0
37,379
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.forms.lookuptree; import java.io.Serializable; import ims.framework.Context; import ims.framework.FormName; import ims.framework.FormAccessLogic; public class BaseAccessLogic extends FormAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public final void setContext(Context context, FormName formName) { form = new CurrentForm(new GlobalContext(context), new CurrentForms()); engine = new CurrentEngine(formName); } public boolean isAccessible() { return true; } public boolean isReadOnly() { return false; } public CurrentEngine engine; public CurrentForm form; public final static class CurrentForm implements Serializable { private static final long serialVersionUID = 1L; CurrentForm(GlobalContext globalcontext, CurrentForms forms) { this.globalcontext = globalcontext; this.forms = forms; } public final GlobalContext getGlobalContext() { return globalcontext; } public final CurrentForms getForms() { return forms; } private GlobalContext globalcontext; private CurrentForms forms; } public final static class CurrentEngine implements Serializable { private static final long serialVersionUID = 1L; CurrentEngine(FormName formName) { this.formName = formName; } public final FormName getFormName() { return formName; } private FormName formName; } public static final class CurrentForms implements Serializable { private static final long serialVersionUID = 1L; protected final class LocalFormName extends FormName { private static final long serialVersionUID = 1L; protected LocalFormName(int value) { super(value); } } private CurrentForms() { Core = new CoreForms(); } public final class CoreForms implements Serializable { private static final long serialVersionUID = 1L; private CoreForms() { YesNoDialog = new LocalFormName(102107); OkCancelDialog = new LocalFormName(102129); TaxonomySearch = new LocalFormName(104102); } public final FormName YesNoDialog; public final FormName OkCancelDialog; public final FormName TaxonomySearch; } public CoreForms Core; } }
open-health-hub/openmaxims-linux
openmaxims_workspace/Admin/src/ims/admin/forms/lookuptree/BaseAccessLogic.java
Java
agpl-3.0
4,001
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class MeetingStatus extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public MeetingStatus() { super(); } public MeetingStatus(int id) { super(id, "", true); } public MeetingStatus(int id, String text, boolean active) { super(id, text, active, null, null, null); } public MeetingStatus(int id, String text, boolean active, MeetingStatus parent, Image image) { super(id, text, active, parent, image); } public MeetingStatus(int id, String text, boolean active, MeetingStatus parent, Image image, Color color) { super(id, text, active, parent, image, color); } public MeetingStatus(int id, String text, boolean active, MeetingStatus parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static MeetingStatus buildLookup(ims.vo.LookupInstanceBean bean) { return new MeetingStatus(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (MeetingStatus)super.getParentInstance(); } public MeetingStatus getParent() { return (MeetingStatus)super.getParentInstance(); } public void setParent(MeetingStatus parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); MeetingStatus[] typedChildren = new MeetingStatus[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (MeetingStatus)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof MeetingStatus) { super.addChild((MeetingStatus)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof MeetingStatus) { super.removeChild((MeetingStatus)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { MeetingStatusCollection result = new MeetingStatusCollection(); return result; } public static MeetingStatus[] getNegativeInstances() { return new MeetingStatus[] {}; } public static String[] getNegativeInstanceNames() { return new String[] {}; } public static MeetingStatus getNegativeInstance(String name) { if(name == null) return null; // No negative instances found return null; } public static MeetingStatus getNegativeInstance(Integer id) { if(id == null) return null; // No negative instances found return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1231012; }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/clinical/vo/lookups/MeetingStatus.java
Java
agpl-3.0
4,839
<?php /** * This view displays the organization tree and allows to attach and detach employees from sub-entities. * @copyright Copyright (c) 2014-2016 Benjamin BALET * @license http://opensource.org/licenses/AGPL-3.0 AGPL-3.0 * @link https://github.com/bbalet/jorani * @since 0.1.0 */ ?> <h2><?php echo lang('organization_index_title');?> &nbsp;<?php echo $help;?></h2> <div class="row-fluid"> <div class="span4"> <div class="input-append"> <input type="text" class="input-medium" placeholder="<?php echo lang('organization_index_field_search_placeholder');?>" id="txtSearch" /> <button id="cmdClearSearch" class="btn btn-primary"><i class="icon-remove icon-white"></i></button> <button id="cmdSearch" class="btn btn-primary"><i class="icon-search icon-white"></i>&nbsp;<?php echo lang('organization_index_button_search');?></button> </div> <div style="text-align: left;" id="organization"></div> </div> <div class="span8"> <h3><?php echo lang('organization_index_title_employees');?></h3> <table cellpadding="0" cellspacing="0" border="0" class="display" id="collaborators" width="100%"> <thead> <tr> <th><?php echo lang('organization_index_thead_id');?></th> <th><?php echo lang('organization_index_thead_firstname');?></th> <th><?php echo lang('organization_index_thead_lastname');?></th> <th><?php echo lang('organization_index_thead_email');?></th> </tr> </thead> <tbody> </tbody> </table> <br /> <button id="cmdAddEmployee" class="btn btn-primary"><?php echo lang('organization_index_button_add_employee');?></button> <button id="cmdRemoveEmployee" class="btn btn-primary"><?php echo lang('organization_index_button_remove_employee');?></button> <br /> <h3><?php echo lang('organization_index_title_supervisor');?></h3> <p><?php echo lang('organization_index_description_supervisor');?></p> <div class="input-append"> <input type="text" id="txtSupervisor" /> <button id="cmdDeleteSupervisor" class="btn btn-danger"><i class="icon-remove icon-white"></i></button> <button id="cmdSelectSupervisor" class="btn btn-primary"><?php echo lang('organization_index_button_select_supervisor');?></button> </div> <br /><br /> </div> </div> <div id="frmConfirmDelete" class="modal hide fade"> <div class="modal-header"> <a href="#" onclick="$('#frmConfirmDelete').modal('hide');" class="close">&times;</a> <h3><?php echo lang('organization_index_popup_delete_title');?></h3> </div> <div class="modal-body"> <p><?php echo lang('organization_index_popup_delete_description');?></p> <p><?php echo lang('organization_index_popup_delete_confirm');?></p> </div> <div class="modal-footer"> <a href="#" class="btn btn-danger" id="lnkDeleteEntity"><?php echo lang('organization_index_popup_delete_button_yes');?></a> <a href="#" onclick="$('#organization').jstree('refresh'); $('#frmConfirmDelete').modal('hide');" class="btn"><?php echo lang('organization_index_popup_delete_button_no');?></a> </div> </div> <div id="frmAddEmployee" class="modal hide fade"> <div class="modal-header"> <a href="#" onclick="$('#frmAddEmployee').modal('hide');" class="close">&times;</a> <h3><?php echo lang('organization_index_popup_add_title');?></h3> </div> <div class="modal-body" id="frmAddEmployeeBody"> <img src="<?php echo base_url();?>assets/images/loading.gif"> </div> <div class="modal-footer"> <a href="#" onclick="add_employee();" class="btn"><?php echo lang('organization_index_popup_add_button_ok');?></a> <a href="#" onclick="$('#frmAddEmployee').modal('hide');" class="btn"><?php echo lang('organization_index_popup_add_button_cancel');?></a> </div> </div> <div id="frmSelectSupervisor" class="modal hide fade"> <div class="modal-header"> <a href="#" onclick="$('#frmSelectSupervisor').modal('hide');" class="close">&times;</a> <h3><?php echo lang('organization_index_popup_supervisor_title');?></h3> </div> <div class="modal-body" id="frmSelectSupervisorBody"> <img src="<?php echo base_url();?>assets/images/loading.gif"> </div> <div class="modal-footer"> <a href="#" onclick="select_supervisor();" class="btn"><?php echo lang('organization_index_popup_supervisor_button_ok');?></a> <a href="#" onclick="$('#frmSelectSupervisor').modal('hide');" class="btn"><?php echo lang('organization_index_popup_supervisor_button_cancel');?></a> </div> </div> <div id="frmError" class="modal hide fade"> <div class="modal-header"> <a href="#" onclick="$('#frmError').modal('hide');" class="close">&times;</a> <h3><?php echo lang('organization_index_popup_error_title');?></h3> </div> <div class="modal-body" id="lblError"></div> <div class="modal-footer"> <a href="#" onclick="$('#frmError').modal('hide');" class="btn"><?php echo lang('organization_index_popup_error_button_ok');?></a> </div> </div> <div class="modal hide" id="frmModalAjaxWait" data-backdrop="static" data-keyboard="false"> <div class="modal-header"> <h1><?php echo lang('global_msg_wait');?></h1> </div> <div class="modal-body"> <img src="<?php echo base_url();?>assets/images/loading.gif" align="middle"> </div> </div> <link href="<?php echo base_url();?>assets/datatable/css/jquery.dataTables.min.css" rel="stylesheet"> <link href="<?php echo base_url();?>assets/datatable/select/css/select.dataTables.min.css" rel="stylesheet"> <link rel="stylesheet" href='<?php echo base_url(); ?>assets/jsTree/themes/default/style.css' type="text/css" media="screen, projection" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/jsTree/jstree.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>assets/datatable/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>assets/datatable/select/js/dataTables.select.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>assets/js/bootbox.min.js"></script> <script type="text/javascript"> //In order to manipulate datable object var oTable; //Mutex to prevent rename the root node var createMtx = false; function add_employee() { var employees = $('#employees').DataTable(); var id = employees.rows({selected: true}).data()[0][0]; var entity = $('#organization').jstree('get_selected')[0]; $.ajax({ type: "GET", url: "<?php echo base_url(); ?>organization/addemployee", data: { 'user': id, 'entity': entity } }) .done(function(msg) { //Update table of users $('#frmModalAjaxWait').modal('show'); oTable.ajax.url("<?php echo base_url(); ?>organization/employees?id=" + entity) .load(function() { $("#frmModalAjaxWait").modal('hide'); }, true); $("#frmAddEmployee").modal('hide'); }); } function select_supervisor() { $("#frmSelectSupervisor").modal('hide'); $('#frmModalAjaxWait').modal('show'); var employees = $('#employees').DataTable(); var id = employees.rows({selected: true}).data()[0][0]; var text = employees.rows({selected: true}).data()[0][1] + ' ' + employees.rows({selected: true}).data()[0][2]; var entity = $('#organization').jstree('get_selected')[0]; $.ajax({ type: "GET", url: "<?php echo base_url(); ?>organization/setsupervisor", data: { 'user': id, 'entity': entity } }) .done(function(msg) { //Update field with the name of employee (the supervisor) $('#txtSupervisor').val(text); $('#frmModalAjaxWait').modal('hide'); }); } function delete_supervisor() { $('#frmModalAjaxWait').modal('show'); var entity = $('#organization').jstree('get_selected')[0]; $.ajax({ type: "GET", url: "<?php echo base_url(); ?>organization/setsupervisor", data: { 'user': null, 'entity': entity } }) .done(function(msg) { //Update field with the name of employee (the supervisor) $('#txtSupervisor').val(""); $('#frmModalAjaxWait').modal('hide'); }); } $(function () { //On confirm the deletion of the node, launch heavy cascade deletion $("#lnkDeleteEntity").click(function() { $.ajax({ type: "GET", url: "<?php echo base_url(); ?>organization/delete", data: { 'entity': $('#frmConfirmDelete').data('id') } }) .done(function(msg) { $("#organization").jstree("select_node", "0"); $("#organization").jstree("refresh"); $("#frmConfirmDelete").modal('hide'); }); }); //Attach an employee to an entity $("#cmdAddEmployee").click(function() { if ($("#organization").jstree('get_selected').length == 1) { $("#frmAddEmployee").modal('show'); $("#frmAddEmployeeBody").load('<?php echo base_url(); ?>users/employees'); } else { $("#lblError").text("<?php echo lang('organization_index_error_msg_select_entity');?>"); $("#frmError").modal('show'); } }); //Select the supervisor of the entity $("#cmdSelectSupervisor").click(function() { if ($("#organization").jstree('get_selected').length == 1) { $("#frmSelectSupervisor").modal('show'); $("#frmSelectSupervisorBody").load('<?php echo base_url(); ?>users/employees'); } else { $("#lblError").text("<?php echo lang('organization_index_error_msg_select_entity');?>"); $("#frmError").modal('show'); } }); //Delete the supervisor of the entity $("#cmdDeleteSupervisor").click(function() { if ($("#organization").jstree('get_selected').length == 1) { delete_supervisor(); } else { $("#lblError").text("<?php echo lang('organization_index_error_msg_select_entity');?>"); $("#frmError").modal('show'); } }); //Remove an employee to an entity $("#cmdRemoveEmployee").click(function() { var id = oTable.rows({selected: true}).data()[0][0]; if (id != "") { if ($("#organization").jstree('get_selected').length == 1) { var entity = $('#organization').jstree('get_selected')[0]; $.ajax({ type: "GET", url: "<?php echo base_url(); ?>organization/delemployee", data: { 'user': id } }) .done(function( msg ) { //Update table of users $('#frmModalAjaxWait').modal('show'); oTable.ajax.url("<?php echo base_url(); ?>organization/employees?id=" + entity) .load(function() { $("#frmModalAjaxWait").modal('hide'); }, true); }); } else { $("#lblError").text("<?php echo lang('organization_index_error_msg_select_entity');?>"); $("#frmError").modal('show'); } } else { $("#lblError").text("<?php echo lang('organization_index_error_msg_select_employee');?>"); $("#frmError").modal('show'); $("#frmErrorEmployee").modal('show'); } }); //Load alert forms $("#frmAddEmployee").alert(); //Prevent to load always the same content (refreshed each time) $('#frmAddEmployee').on('hidden', function() { $( "#employees" ).remove(); $(this).removeData('modal'); }); $('#frmSelectSupervisor').on('hidden', function() { $( "#employees" ).remove(); $(this).removeData('modal'); }); //Search in the treeview $("#cmdSearch").click(function () { $("#organization").jstree("search", $("#txtSearch").val(), true, true); }); $("#txtSearch").keyup(function(e) { if (e.keyCode == 13) { $("#organization").jstree("search", $("#txtSearch").val(), true, true); } // enter key }); //Clear the Search option in the treeview $("#cmdClearSearch").click(function () { $("#organization").jstree("clear_search"); }); $(document).keyup(function(e) { if (e.keyCode == 27) { $("#organization").jstree("clear_search"); } // escape key }); //Transform the HTML table in a fancy datatable oTable = $('#collaborators').DataTable({ select: 'single', "oLanguage": { "sEmptyTable": "<?php echo lang('datatable_sEmptyTable');?>", "sInfo": "<?php echo lang('datatable_sInfo');?>", "sInfoEmpty": "<?php echo lang('datatable_sInfoEmpty');?>", "sInfoFiltered": "<?php echo lang('datatable_sInfoFiltered');?>", "sInfoPostFix": "<?php echo lang('datatable_sInfoPostFix');?>", "sInfoThousands": "<?php echo lang('datatable_sInfoThousands');?>", "sLengthMenu": "<?php echo lang('datatable_sLengthMenu');?>", "sLoadingRecords": "<?php echo lang('datatable_sLoadingRecords');?>", "sProcessing": "<?php echo lang('datatable_sProcessing');?>", "sSearch": "<?php echo lang('datatable_sSearch');?>", "sZeroRecords": "<?php echo lang('datatable_sZeroRecords');?>", "oPaginate": { "sFirst": "<?php echo lang('datatable_sFirst');?>", "sLast": "<?php echo lang('datatable_sLast');?>", "sNext": "<?php echo lang('datatable_sNext');?>", "sPrevious": "<?php echo lang('datatable_sPrevious');?>" }, "oAria": { "sSortAscending": "<?php echo lang('datatable_sSortAscending');?>", "sSortDescending": "<?php echo lang('datatable_sSortDescending');?>" } } }); //Initialize the tree of the organization $('#organization').jstree({ contextmenu: { items: function(n) { var tmp = $.jstree.defaults.contextmenu.items(); tmp.create.label = '<?php echo lang('treeview_context_menu_create');?>'; tmp.rename.label = '<?php echo lang('treeview_context_menu_rename');?>'; tmp.remove.label = '<?php echo lang('treeview_context_menu_remove');?>'; tmp.ccp.label = '<?php echo lang('treeview_context_menu_edit');?>'; tmp.ccp.submenu.copy.label = '<?php echo lang('treeview_context_menu_copy');?>'; tmp.ccp.submenu.cut.label = '<?php echo lang('treeview_context_menu_cut');?>'; tmp.ccp.submenu.paste.label = '<?php echo lang('treeview_context_menu_paste');?>'; return tmp; } }, rules: { deletable : [ "folder" ], creatable : [ "folder" ], draggable : [ "folder" ], dragrules : [ "folder * folder", "folder inside root" ], renameable : "all" }, core: { multiple : false, data: { url: function (node) { return node.id === '#' ? '<?php echo base_url(); ?>organization/root' : '<?php echo base_url(); ?>organization/children'; }, data: function (node) { return { 'id' : node.id }; } }, check_callback : true }, plugins: ["contextmenu", "dnd", "search", "state", "sort", "unique"] }) .on('delete_node.jstree', function (e, data) { var id = data.node.id; if (id == 0) { $("#lblError").text("<?php echo lang('organization_index_error_msg_delete_root');?>"); $("#frmError").modal('show'); $("#organization").jstree("refresh"); } else { $('#frmConfirmDelete').data('id', id).modal('show'); } }) .on('create_node.jstree', function (e, data) { createMtx = true; bootbox.prompt("<?php echo lang('organization_index_prompt_entity_name');?>", "<?php echo lang('organization_index_popup_node_button_cancel');?>", "<?php echo lang('organization_index_popup_node_button_ok');?>", function(result) { if ((result === null) || (result == '')) { //NULL or empty string has no effect data.instance.refresh(); } else { $.get('organization/create', { 'id' : data.node.parent, 'position' : data.position, 'text' : result }) .done(function (d) { data.instance.set_id(data.node, d.id); createMtx = false; }) .fail(function() { data.instance.refresh(); createMtx = false; }); } }); }) .on('rename_node.jstree', function(e, data) { if (!createMtx) { $.get('organization/rename', {'id': data.node.id, 'text': data.text}) .fail(function() { data.instance.refresh(); }); } }) .on('move_node.jstree', function(e, data) { e.preventDefault(); $.get('organization/move', {'id': data.node.id, 'parent': data.parent, 'position': data.position}) .fail(function() { data.instance.refresh(); }); }) .on('copy_node.jstree', function(e, data) { e.preventDefault(); $.get('organization/copy', {'id': data.original.id, 'parent': data.parent, 'position': data.position}) .always(function() { data.instance.refresh(); }); }) .on('changed.jstree', function(e, data) { if (data && data.selected && data.selected.length) { $('#frmModalAjaxWait').modal('show'); var isTableLoaded = false; oTable.ajax.url("<?php echo base_url(); ?>organization/employees?id=" + data.selected.join(':')) .load(function() { isTableLoaded = true; }, true); $.ajax({ type: "GET", url: "<?php echo base_url(); ?>organization/getsupervisor", data: { 'entity': data.selected.join(':') } }) .done(function(data) { //Update field with the name of employee (the supervisor) if (data != null && typeof data === 'object') { $('#txtSupervisor').val(data.username); } else { $('#txtSupervisor').val(""); } $.when(isTableLoaded, isTableLoaded).done(function() { $("#frmModalAjaxWait").modal('hide'); }); }); } }); }); </script>
mliebmanyoo/jorani
application/views/organization/index.php
PHP
agpl-3.0
20,675
--- github: eclipse/che googleplus: 'https://plus.google.com/103654360130207659246' logohandle: eclipse_che sort: eclipseche title: Eclipse Che twitter: eclipse_che website: 'https://che.eclipse.org/' ---
fileformat/vectorlogozone
www/logos/eclipse_che/index.md
Markdown
agpl-3.0
205
/*! grafana - v4.2.0 - 2017-03-22 * Copyright (c) 2017 Torkel Ödegaard; Licensed Apache-2.0 */ System.register(["./plugin_edit_ctrl","./plugin_page_ctrl","./plugin_list_ctrl","./import_list/import_list","./ds_edit_ctrl","./ds_list_ctrl"],function(a,b){"use strict";b&&b.id;return{setters:[function(a){},function(a){},function(a){},function(a){},function(a){},function(a){}],execute:function(){}}});
n0rad/housecream
public/app/features/plugins/all.js
JavaScript
agpl-3.0
401
class NotificationAcknowledgment < ActiveRecord::Base end
andrewroth/project_application_tool
app/models/notification_acknowledgment.rb
Ruby
agpl-3.0
58
# -- # Copyright (C) 2001-2017 OTRS AG, http://otrs.com/ # -- # This software comes with ABSOLUTELY NO WARRANTY. For details, see # the enclosed file COPYING for license information (AGPL). If you # did not receive this file, see http://www.gnu.org/licenses/agpl.txt. # -- package Kernel::GenericInterface::Transport::HTTP::REST; use strict; use warnings; use HTTP::Status; use MIME::Base64; use REST::Client; use URI::Escape; use Kernel::Config; use Kernel::System::VariableCheck qw(:all); our $ObjectManagerDisabled = 1; =head1 NAME Kernel::GenericInterface::Transport::REST - GenericInterface network transport interface for HTTP::REST =head1 PUBLIC INTERFACE =head2 new() usually, you want to create an instance of this by using Kernel::GenericInterface::Transport->new(); =cut sub new { my ( $Type, %Param ) = @_; # Allocate new hash for object. my $Self = {}; bless( $Self, $Type ); for my $Needed (qw(DebuggerObject TransportConfig)) { $Self->{$Needed} = $Param{$Needed} || die "Got no $Needed!"; } return $Self; } =head2 ProviderProcessRequest() Process an incoming web service request. This function has to read the request data from from the web server process. Based on the request the Operation to be used is determined. No out-bound communication is done here, except from continue requests. In case of an error, the resulting http error code and message are remembered for the response. my $Result = $TransportObject->ProviderProcessRequest(); $Result = { Success => 1, # 0 or 1 ErrorMessage => '', # in case of error Operation => 'DesiredOperation', # name of the operation to perform Data => { # data payload of request ... }, }; =cut sub ProviderProcessRequest { my ( $Self, %Param ) = @_; # Check transport config. if ( !IsHashRefWithData( $Self->{TransportConfig} ) ) { return $Self->_Error( Summary => 'REST Transport: Have no TransportConfig', HTTPError => 500, ); } if ( !IsHashRefWithData( $Self->{TransportConfig}->{Config} ) ) { return $Self->_Error( Summary => 'Rest Transport: Have no Config', HTTPError => 500, ); } my $Config = $Self->{TransportConfig}->{Config}; $Self->{KeepAlive} = $Config->{KeepAlive} || 0; if ( !IsHashRefWithData( $Config->{RouteOperationMapping} ) ) { return $Self->_Error( Summary => "HTTP::REST Can't find RouteOperationMapping in Config", HTTPError => 500, ); } my $EncodeObject = $Kernel::OM->Get('Kernel::System::Encode'); my $Operation; my %URIData; my $RequestURI = $ENV{REQUEST_URI} || $ENV{PATH_INFO}; $RequestURI =~ s{.*Webservice(?:ID)?\/[^\/]+(\/.*)$}{$1}xms; # Remove any query parameter from the URL # e.g. from /Ticket/1/2?UserLogin=user&Password=secret # to /Ticket/1/2?. $RequestURI =~ s{([^?]+)(.+)?}{$1}; # Remember the query parameters e.g. ?UserLogin=user&Password=secret. my $QueryParamsStr = $2 || ''; my %QueryParams; if ($QueryParamsStr) { # Remove question mark '?' in the beginning. substr $QueryParamsStr, 0, 1, ''; # Convert query parameters into a hash # e.g. from UserLogin=user&Password=secret # to ( # UserLogin => 'user', # Password => 'secret', # ); for my $QueryParam ( split /[;&]/, $QueryParamsStr ) { my ( $Key, $Value ) = split '=', $QueryParam; # Convert + characters to its encoded representation, see bug#11917. $Value =~ s{\+}{%20}g; # Unescape URI strings in query parameters. $Key = URI::Escape::uri_unescape($Key); $Value = URI::Escape::uri_unescape($Value); # Encode variables. $EncodeObject->EncodeInput( \$Key ); $EncodeObject->EncodeInput( \$Value ); if ( !defined $QueryParams{$Key} ) { $QueryParams{$Key} = $Value || ''; } # Elements specified multiple times will be added as array reference. elsif ( ref $QueryParams{$Key} eq '' ) { $QueryParams{$Key} = [ $QueryParams{$Key}, $Value ]; } else { push @{ $QueryParams{$Key} }, $Value; } } } my $RequestMethod = $ENV{'REQUEST_METHOD'} || 'GET'; ROUTE: for my $CurrentOperation ( sort keys %{ $Config->{RouteOperationMapping} } ) { next ROUTE if !IsHashRefWithData( $Config->{RouteOperationMapping}->{$CurrentOperation} ); my %RouteMapping = %{ $Config->{RouteOperationMapping}->{$CurrentOperation} }; if ( IsArrayRefWithData( $RouteMapping{RequestMethod} ) ) { next ROUTE if !grep { $RequestMethod eq $_ } @{ $RouteMapping{RequestMethod} }; } # Convert the configured route with the help of extended regexp patterns # to a regexp. This generated regexp is used to: # 1.) Determine the Operation for the request # 2.) Extract additional parameters from the RequestURI # For further information: http://perldoc.perl.org/perlre.html#Extended-Patterns # # For example, from the RequestURI: /Ticket/1/2 # and the route setting: /Ticket/:TicketID/:Other # %URIData will then contain: # ( # TicketID => 1, # Other => 2, # ); my $RouteRegEx = $RouteMapping{Route}; $RouteRegEx =~ s{:([^\/]+)}{(?<$1>[^\/]+)}xmsg; next ROUTE if !( $RequestURI =~ m{^ $RouteRegEx $}xms ); # Import URI params. for my $URIKey ( sort keys %+ ) { my $URIValue = $+{$URIKey}; # Unescape value $URIValue = URI::Escape::uri_unescape($URIValue); # Encode value. $EncodeObject->EncodeInput( \$URIValue ); # Add to URI data. $URIData{$URIKey} = $URIValue; } $Operation = $CurrentOperation; # Leave with the first matching regexp. last ROUTE; } # Combine query params with URIData params, URIData has more precedence. if (%QueryParams) { %URIData = ( %QueryParams, %URIData, ); } if ( !$Operation ) { return $Self->_Error( Summary => "HTTP::REST Error while determine Operation for request URI '$RequestURI'.", HTTPError => 500, ); } my $Length = $ENV{'CONTENT_LENGTH'}; # No length provided, return the information we have. if ( !$Length ) { return { Success => 1, Operation => $Operation, Data => { %URIData, RequestMethod => $RequestMethod, }, }; } # Request bigger than allowed. if ( IsInteger( $Config->{MaxLength} ) && $Length > $Config->{MaxLength} ) { return $Self->_Error( Summary => HTTP::Status::status_message(413), HTTPError => 413, ); } # Read request. my $Content; read STDIN, $Content, $Length; # If there is no STDIN data it might be caused by fastcgi already having read the request. # In this case we need to get the data from CGI. if ( !IsStringWithData($Content) && $RequestMethod ne 'GET' ) { my $ParamName = $RequestMethod . 'DATA'; $Content = $Kernel::OM->Get('Kernel::System::Web::Request')->GetParam( Param => $ParamName, ); } # Check if we have content. if ( !IsStringWithData($Content) ) { return $Self->_Error( Summary => 'Could not read input data', HTTPError => 500, ); } # Convert char-set if necessary. my $ContentCharset; if ( $ENV{'CONTENT_TYPE'} =~ m{ \A .* charset= ["']? ( [^"']+ ) ["']? \z }xmsi ) { $ContentCharset = $1; } if ( $ContentCharset && $ContentCharset !~ m{ \A utf [-]? 8 \z }xmsi ) { $Content = $EncodeObject->Convert2CharsetInternal( Text => $Content, From => $ContentCharset, ); } else { $EncodeObject->EncodeInput( \$Content ); } # Send received data to debugger. $Self->{DebuggerObject}->Debug( Summary => 'Received data by provider from remote system', Data => $Content, ); my $ContentDecoded = $Kernel::OM->Get('Kernel::System::JSON')->Decode( Data => $Content, ); if ( !$ContentDecoded ) { return $Self->_Error( Summary => 'Error while decoding request content.', HTTPError => 500, ); } my $ReturnData; if ( IsHashRefWithData($ContentDecoded) ) { $ReturnData = $ContentDecoded; @{$ReturnData}{ keys %URIData } = values %URIData; } elsif ( IsArrayRefWithData($ContentDecoded) ) { ELEMENT: for my $CurrentElement ( @{$ContentDecoded} ) { if ( IsHashRefWithData($CurrentElement) ) { @{$CurrentElement}{ keys %URIData } = values %URIData; } push @{$ReturnData}, $CurrentElement; } } else { return $Self->_Error( Summary => 'Unsupported request content structure.', HTTPError => 500, ); } # All OK - return data return { Success => 1, Operation => $Operation, Data => $ReturnData, }; } =head2 ProviderGenerateResponse() Generates response for an incoming web service request. In case of an error, error code and message are taken from environment (previously set on request processing). The HTTP code is set accordingly - C<200> for (syntactically) correct messages - C<4xx> for http errors - C<500> for content syntax errors my $Result = $TransportObject->ProviderGenerateResponse( Success => 1 Data => { # data payload for response, optional ... }, ); $Result = { Success => 1, # 0 or 1 ErrorMessage => '', # in case of error }; =cut sub ProviderGenerateResponse { my ( $Self, %Param ) = @_; # Do we have a http error message to return. if ( IsStringWithData( $Self->{HTTPError} ) && IsStringWithData( $Self->{HTTPMessage} ) ) { return $Self->_Output( HTTPCode => $Self->{HTTPError}, Content => $Self->{HTTPMessage}, ); } # Check data param. if ( defined $Param{Data} && ref $Param{Data} ne 'HASH' ) { return $Self->_Output( HTTPCode => 500, Content => 'Invalid data', ); } # Check success param. my $HTTPCode = 200; if ( !$Param{Success} ) { # Create Fault structure. my $FaultString = $Param{ErrorMessage} || 'Unknown'; $Param{Data} = { faultcode => 'Server', faultstring => $FaultString, }; # Override HTTPCode to 500. $HTTPCode = 500; } # Orepare data. my $JSONString = $Kernel::OM->Get('Kernel::System::JSON')->Encode( Data => $Param{Data}, ); if ( !$JSONString ) { return $Self->_Output( HTTPCode => 500, Content => 'Error while encoding return JSON structure.', ); } # No error - return output. return $Self->_Output( HTTPCode => $HTTPCode, Content => $JSONString, ); } =head2 RequesterPerformRequest() Prepare data payload as XML structure, generate an outgoing web service request, receive the response and return its data. my $Result = $TransportObject->RequesterPerformRequest( Operation => 'remote_op', # name of remote operation to perform Data => { # data payload for request ... }, ); $Result = { Success => 1, # 0 or 1 ErrorMessage => '', # in case of error Data => { ... }, }; =cut sub RequesterPerformRequest { my ( $Self, %Param ) = @_; # Check transport config. if ( !IsHashRefWithData( $Self->{TransportConfig} ) ) { return { Success => 0, ErrorMessage => 'REST Transport: Have no TransportConfig', }; } if ( !IsHashRefWithData( $Self->{TransportConfig}->{Config} ) ) { return { Success => 0, ErrorMessage => 'REST Transport: Have no Config', }; } my $Config = $Self->{TransportConfig}->{Config}; NEEDED: for my $Needed (qw(Host DefaultCommand Timeout)) { next NEEDED if IsStringWithData( $Config->{$Needed} ); return { Success => 0, ErrorMessage => "REST Transport: Have no $Needed in config", }; } # Check data param. if ( defined $Param{Data} && ref $Param{Data} ne 'HASH' ) { return { Success => 0, ErrorMessage => 'REST Transport: Invalid Data', }; } # Check operation param. if ( !IsStringWithData( $Param{Operation} ) ) { return { Success => 0, ErrorMessage => 'REST Transport: Need Operation', }; } # Create header container and add proper content type my $Headers = { 'Content-Type' => 'application/json; charset=UTF-8' }; # set up a REST session my $RestClient = REST::Client->new( { host => $Config->{Host}, timeout => $Config->{Timeout}, } ); if ( !$RestClient ) { my $ErrorMessage = "Error while creating REST client from 'REST::Client'."; # Log to debugger. $Self->{DebuggerObject}->Error( Summary => $ErrorMessage, ); return { Success => 0, ErrorMessage => $ErrorMessage, }; } # Add SSL options if configured. my %SSLOptions; if ( IsHashRefWithData( $Config->{SSL} ) && IsStringWithData( $Config->{SSL}->{UseSSL} ) && $Config->{SSL}->{UseSSL} eq 'Yes' ) { my %SSLOptionsMap = ( SSLCertificate => 'SSL_cert_file', SSLKey => 'SSL_key_file', SSLPassword => 'SSL_passwd_cb', SSLCAFile => 'SSL_ca_file', SSLCADir => 'SSL_ca_path', ); SSLOPTION: for my $SSLOption ( sort keys %SSLOptionsMap ) { next SSLOPTION if !IsStringWithData( $Config->{SSL}->{$SSLOption} ); if ( $SSLOption ne 'SSLPassword' ) { $RestClient->getUseragent()->ssl_opts( $SSLOptionsMap{$SSLOption} => $Config->{SSL}->{$SSLOption}, ); next SSLOPTION; } # Passwords needs a special treatment. $RestClient->getUseragent()->ssl_opts( $SSLOptionsMap{$SSLOption} => sub { $Config->{SSL}->{$SSLOption} }, ); } } # Add proxy options if configured. if ( IsHashRefWithData( $Config->{Proxy} ) && IsStringWithData( $Config->{Proxy}->{UseProxy} ) && $Config->{Proxy}->{UseProxy} eq 'Yes' ) { # Explicitly use no proxy (even if configured system wide). if ( IsStringWithData( $Config->{Proxy}->{ProxyExclude} ) && $Config->{Proxy}->{ProxyExclude} eq 'Yes' ) { $RestClient->getUseragent()->no_proxy(); } # Use proxy. elsif ( IsStringWithData( $Config->{Proxy}->{ProxyHost} ) ) { # Set host. $RestClient->getUseragent()->proxy( [ 'http', 'https', ], $Config->{Proxy}->{ProxyHost}, ); # Add proxy authentication. if ( IsStringWithData( $Config->{Proxy}->{ProxyUser} ) && IsStringWithData( $Config->{Proxy}->{ProxyPassword} ) ) { $Headers->{'Proxy-Authorization'} = 'Basic ' . encode_base64( $Config->{Proxy}->{ProxyUser} . ':' . $Config->{Proxy}->{ProxyPassword} ); } } } # Add authentication options if configured (hard wired to basic authentication at the moment). if ( IsHashRefWithData( $Config->{Authentication} ) && IsStringWithData( $Config->{Authentication}->{AuthType} ) && $Config->{Authentication}->{AuthType} eq 'BasicAuth' && IsStringWithData( $Config->{Authentication}->{BasicAuthUser} ) && IsStringWithData( $Config->{Authentication}->{BasicAuthPassword} ) ) { $Headers->{Authorization} = 'Basic ' . encode_base64( $Config->{Authentication}->{BasicAuthUser} . ':' . $Config->{Authentication}->{BasicAuthPassword} ); } my $RestCommand = $Config->{DefaultCommand}; if ( IsStringWithData( $Config->{InvokerControllerMapping}->{ $Param{Operation} }->{Command} ) ) { $RestCommand = $Config->{InvokerControllerMapping}->{ $Param{Operation} }->{Command}; } $RestCommand = uc $RestCommand; if ( !grep { $_ eq $RestCommand } qw(GET POST PUT PATCH DELETE HEAD OPTIONS CONNECT TRACE) ) { my $ErrorMessage = "'$RestCommand' is not a valid REST command."; # Log to debugger. $Self->{DebuggerObject}->Error( Summary => $ErrorMessage, ); return { Success => 0, ErrorMessage => $ErrorMessage, }; } if ( !IsHashRefWithData( $Config->{InvokerControllerMapping} ) || !IsHashRefWithData( $Config->{InvokerControllerMapping}->{ $Param{Operation} } ) || !IsStringWithData( $Config->{InvokerControllerMapping}->{ $Param{Operation} }->{Controller} ) ) { my $ErrorMessage = "REST Transport: Have no Invoker <-> Controller mapping for Invoker '$Param{Operation}'."; # Log to debugger. $Self->{DebuggerObject}->Error( Summary => $ErrorMessage, ); return { Success => 0, ErrorMessage => $ErrorMessage, }; } my @RequestParam; my $Controller = $Config->{InvokerControllerMapping}->{ $Param{Operation} }->{Controller}; # Remove any query parameters that might be in the config, # For example, from the controller: /Ticket/:TicketID/?:UserLogin&:Password # controller must remain /Ticket/:TicketID/ $Controller =~ s{([^?]+)(.+)?}{$1}; # Remember the query parameters e.g. ?:UserLogin&:Password. my $QueryParamsStr = $2 || ''; my @ParamsToDelete; # Replace any URI params with their actual value. # for example: from /Ticket/:TicketID/:Other # to /Ticket/1/2 (considering that $Param{Data} contains TicketID = 1 and Other = 2). for my $ParamName ( sort keys %{ $Param{Data} } ) { if ( $Controller =~ m{:$ParamName(?=/|\?|$)}msx ) { my $ParamValue = $Param{Data}->{$ParamName}; $ParamValue = URI::Escape::uri_escape_utf8($ParamValue); $Controller =~ s{:$ParamName(?=/|\?|$)}{$ParamValue}msxg; push @ParamsToDelete, $ParamName; } } $Self->{DebuggerObject}->Debug( Summary => "URI after interpolating URI params from outgoing data", Data => $Controller, ); if ($QueryParamsStr) { # Replace any query params with their actual value # for example: from ?UserLogin:UserLogin&Password=:Password # to ?UserLogin=user&Password=secret # (considering that $Param{Data} contains UserLogin = 'user' and Password = 'secret'). my $ReplaceFlag; for my $ParamName ( sort keys %{ $Param{Data} } ) { if ( $QueryParamsStr =~ m{:$ParamName(?=&|$)}msx ) { my $ParamValue = $Param{Data}->{$ParamName}; $ParamValue = URI::Escape::uri_escape_utf8($ParamValue); $QueryParamsStr =~ s{:$ParamName(?=&|$)}{$ParamValue}msxg; push @ParamsToDelete, $ParamName; $ReplaceFlag = 1; } } # Append query params in the URI. if ($ReplaceFlag) { $Controller .= $QueryParamsStr; $Self->{DebuggerObject}->Debug( Summary => "URI after interpolating Query params from outgoing data", Data => $Controller, ); } } # Remove already used params. for my $ParamName (@ParamsToDelete) { delete $Param{Data}->{$ParamName}; } # Get JSON and Encode object. my $JSONObject = $Kernel::OM->Get('Kernel::System::JSON'); my $EncodeObject = $Kernel::OM->Get('Kernel::System::Encode'); my $Body; if ( IsHashRefWithData( $Param{Data} ) ) { # POST, PUT and PATCH can have Data in the Body. if ( $RestCommand eq 'POST' || $RestCommand eq 'PUT' || $RestCommand eq 'PATCH' ) { $Self->{DebuggerObject}->Debug( Summary => "Remaining outgoing data to be sent", Data => $Param{Data}, ); $Param{Data} = $JSONObject->Encode( Data => $Param{Data}, ); # Make sure data is correctly encoded. $EncodeObject->EncodeOutput( \$Param{Data} ); } # Whereas GET and the others just have a the data added to the Query URI. else { my $QueryParams = $RestClient->buildQuery( %{ $Param{Data} } ); # Check if controller already have a question mark '?'. if ( $Controller =~ m{\?}msx ) { # Replace question mark '?' by an ampersand '&'. $QueryParams =~ s{\A\?}{&}; } $Controller .= $QueryParams; $Self->{DebuggerObject}->Debug( Summary => "URI after adding Query params from outgoing data", Data => $Controller, ); $Self->{DebuggerObject}->Debug( Summary => "Remaining outgoing data to be sent", Data => "No data is sent in the request body as $RestCommand command sets all" . " Data as query params", ); } } push @RequestParam, $Controller; if ( IsStringWithData( $Param{Data} ) ) { $Body = $Param{Data}; push @RequestParam, $Body; } # Add headers to request push @RequestParam, $Headers; $RestClient->$RestCommand(@RequestParam); my $ResponseCode = $RestClient->responseCode(); my $ResponseError; my $ErrorMessage = "Error while performing REST '$RestCommand' request to Controller '$Controller' on Host '" . $Config->{Host} . "'."; if ( !IsStringWithData($ResponseCode) ) { $ResponseError = $ErrorMessage; } if ( $ResponseCode !~ m{ \A 20 \d \z }xms ) { $ResponseError = $ErrorMessage . " Response code '$ResponseCode'."; } my $ResponseContent = $RestClient->responseContent(); if ( !IsStringWithData($ResponseContent) ) { $ResponseError .= ' No content provided.'; } # Return early in case an error on response. if ($ResponseError) { my $ResponseData = 'No content provided.'; if ( IsStringWithData($ResponseContent) ) { $ResponseData = "Response content: '$ResponseContent'"; } # log to debugger $Self->{DebuggerObject}->Error( Summary => $ResponseError, Data => $ResponseData, ); return { Success => 0, ErrorMessage => $ResponseError, }; } my $SizeExeeded = 0; { my $MaxSize = $Kernel::OM->Get('Kernel::Config')->Get('GenericInterface::Operation::ResponseLoggingMaxSize') || 200; $MaxSize = $MaxSize * 1024; use bytes; my $ByteSize = length($ResponseContent); if ( $ByteSize < $MaxSize ) { $Self->{DebuggerObject}->Debug( Summary => 'JSON data received from remote system', Data => $ResponseContent, ); } else { $SizeExeeded = 1; $Self->{DebuggerObject}->Debug( Summary => "JSON data received from remote system was too large for logging", Data => 'See SysConfig option GenericInterface::Operation::ResponseLoggingMaxSize to change the maximum.', ); } } $ResponseContent = $EncodeObject->Convert2CharsetInternal( Text => $ResponseContent, From => 'utf-8', ); # To convert the data into a hash, use the JSON module. my $Result = $JSONObject->Decode( Data => $ResponseContent, ); if ( !$Result ) { my $ResponseError = $ErrorMessage . ' Error while parsing JSON data.'; # Log to debugger. $Self->{DebuggerObject}->Error( Summary => $ResponseError, ); return { Success => 0, ErrorMessage => $ResponseError, }; } # All OK - return result. return { Success => 1, Data => $Result || undef, SizeExeeded => $SizeExeeded, }; } =begin Internal: =head2 _Output() Generate http response for provider and send it back to remote system. Environment variables are checked for potential error messages. Returns structure to be passed to provider. my $Result = $TransportObject->_Output( HTTPCode => 200, # http code to be returned, optional Content => 'response', # message content, XML response on normal execution ); $Result = { Success => 0, ErrorMessage => 'Message', # error message from given summary }; =cut sub _Output { my ( $Self, %Param ) = @_; # Check params. my $Success = 1; my $ErrorMessage; if ( defined $Param{HTTPCode} && !IsInteger( $Param{HTTPCode} ) ) { $Param{HTTPCode} = 500; $Param{Content} = 'Invalid internal HTTPCode'; $Success = 0; $ErrorMessage = 'Invalid internal HTTPCode'; } elsif ( defined $Param{Content} && !IsString( $Param{Content} ) ) { $Param{HTTPCode} = 500; $Param{Content} = 'Invalid Content'; $Success = 0; $ErrorMessage = 'Invalid Content'; } # Prepare protocol. my $Protocol = defined $ENV{SERVER_PROTOCOL} ? $ENV{SERVER_PROTOCOL} : 'HTTP/1.0'; # FIXME: according to SOAP::Transport::HTTP the previous should only be used # for IIS to imitate nph- behavior # for all other browser 'Status:' should be used here # this breaks apache though # prepare data $Param{Content} ||= ''; $Param{HTTPCode} ||= 500; my $ContentType; if ( $Param{HTTPCode} eq 200 ) { $ContentType = 'application/json'; } else { $ContentType = 'text/plain'; } # Calculate content length (based on the bytes length not on the characters length). my $ContentLength = bytes::length( $Param{Content} ); # Log to debugger. my $DebugLevel; if ( $Param{HTTPCode} eq 200 ) { $DebugLevel = 'debug'; } else { $DebugLevel = 'error'; } $Self->{DebuggerObject}->DebugLog( DebugLevel => $DebugLevel, Summary => "Returning provider data to remote system (HTTP Code: $Param{HTTPCode})", Data => $Param{Content}, ); # Set keep-alive. my $Connection = $Self->{KeepAlive} ? 'Keep-Alive' : 'close'; # prepare additional headers my $AdditionalHeaderStrg = ''; if ( IsHashRefWithData( $Self->{TransportConfig}->{Config}->{AdditionalHeaders} ) ) { my %AdditionalHeaders = %{ $Self->{TransportConfig}->{Config}->{AdditionalHeaders} }; for my $AdditionalHeader ( sort keys %AdditionalHeaders ) { $AdditionalHeaderStrg .= $AdditionalHeader . ': ' . ( $AdditionalHeaders{$AdditionalHeader} || '' ) . "\r\n"; } } # In the constructor of this module STDIN and STDOUT are set to binmode without any additional # layer (according to the documentation this is the same as set :raw). Previous solutions for # binary responses requires the set of :raw or :utf8 according to IO layers. # with that solution Windows OS requires to set the :raw layer in binmode, see #bug#8466. # while in *nix normally was better to set :utf8 layer in binmode, see bug#8558, otherwise # XML parser complains about it... ( but under special circumstances :raw layer was needed # instead ). # # This solution to set the binmode in the constructor and then :utf8 layer before the response # is sent apparently works in all situations. ( Linux circumstances to requires :raw was no # reproducible, and not tested in this solution). binmode STDOUT, ':utf8'; ## no critic # Print data to http - '\r' is required according to HTTP RFCs. my $StatusMessage = HTTP::Status::status_message( $Param{HTTPCode} ); print STDOUT "$Protocol $Param{HTTPCode} $StatusMessage\r\n"; print STDOUT "Content-Type: $ContentType; charset=UTF-8\r\n"; print STDOUT "Content-Length: $ContentLength\r\n"; print STDOUT "Connection: $Connection\r\n"; print STDOUT $AdditionalHeaderStrg; print STDOUT "\r\n"; print STDOUT $Param{Content}; return { Success => $Success, ErrorMessage => $ErrorMessage, }; } =head2 _Error() Take error parameters from request processing. Error message is written to debugger, written to environment for response. Error is generated to be passed to provider/requester. my $Result = $TransportObject->_Error( Summary => 'Message', # error message HTTPError => 500, # http error code, optional ); $Result = { Success => 0, ErrorMessage => 'Message', # error message from given summary }; =cut sub _Error { my ( $Self, %Param ) = @_; # check needed params if ( !IsString( $Param{Summary} ) ) { return $Self->_Error( Summary => 'Need Summary!', HTTPError => 500, ); } # Log to debugger. $Self->{DebuggerObject}->Error( Summary => $Param{Summary}, ); # Remember data for response. if ( IsStringWithData( $Param{HTTPError} ) ) { $Self->{HTTPError} = $Param{HTTPError}; $Self->{HTTPMessage} = $Param{Summary}; } # Return to provider/requester. return { Success => 0, ErrorMessage => $Param{Summary}, }; } 1; =end Internal: =head1 TERMS AND CONDITIONS This software is part of the OTRS project (L<http://otrs.org/>). This software comes with ABSOLUTELY NO WARRANTY. For details, see the enclosed file COPYING for license information (AGPL). If you did not receive this file, see L<http://www.gnu.org/licenses/agpl.txt>. =cut
xhoy/otrs
Kernel/GenericInterface/Transport/HTTP/REST.pm
Perl
agpl-3.0
31,430
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:23 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Rory Fitzpatrick */ public class IncludeAlertInDischargeReportsVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.IncludeAlertInDischargeReportsVo copy(ims.core.vo.IncludeAlertInDischargeReportsVo valueObjectDest, ims.core.vo.IncludeAlertInDischargeReportsVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_IncludeAlertInDischargeReport(valueObjectSrc.getID_IncludeAlertInDischargeReport()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // CareContext valueObjectDest.setCareContext(valueObjectSrc.getCareContext()); // Alert valueObjectDest.setAlert(valueObjectSrc.getAlert()); // IncludeInReport valueObjectDest.setIncludeInReport(valueObjectSrc.getIncludeInReport()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.clinical.domain.objects.IncludeAlertInDischargeReport objects. */ public static ims.core.vo.IncludeAlertInDischargeReportsVoCollection createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(java.util.Set domainObjectSet) { return createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.clinical.domain.objects.IncludeAlertInDischargeReport objects. */ public static ims.core.vo.IncludeAlertInDischargeReportsVoCollection createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.IncludeAlertInDischargeReportsVoCollection voList = new ims.core.vo.IncludeAlertInDischargeReportsVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject = (ims.core.clinical.domain.objects.IncludeAlertInDischargeReport) iterator.next(); ims.core.vo.IncludeAlertInDischargeReportsVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.clinical.domain.objects.IncludeAlertInDischargeReport objects. */ public static ims.core.vo.IncludeAlertInDischargeReportsVoCollection createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(java.util.List domainObjectList) { return createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.clinical.domain.objects.IncludeAlertInDischargeReport objects. */ public static ims.core.vo.IncludeAlertInDischargeReportsVoCollection createIncludeAlertInDischargeReportsVoCollectionFromIncludeAlertInDischargeReport(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.IncludeAlertInDischargeReportsVoCollection voList = new ims.core.vo.IncludeAlertInDischargeReportsVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject = (ims.core.clinical.domain.objects.IncludeAlertInDischargeReport) domainObjectList.get(i); ims.core.vo.IncludeAlertInDischargeReportsVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.clinical.domain.objects.IncludeAlertInDischargeReport set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractIncludeAlertInDischargeReportSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.IncludeAlertInDischargeReportsVoCollection voCollection) { return extractIncludeAlertInDischargeReportSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractIncludeAlertInDischargeReportSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.IncludeAlertInDischargeReportsVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.core.vo.IncludeAlertInDischargeReportsVo vo = voCollection.get(i); ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject = IncludeAlertInDischargeReportsVoAssembler.extractIncludeAlertInDischargeReport(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.clinical.domain.objects.IncludeAlertInDischargeReport list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractIncludeAlertInDischargeReportList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.IncludeAlertInDischargeReportsVoCollection voCollection) { return extractIncludeAlertInDischargeReportList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractIncludeAlertInDischargeReportList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.IncludeAlertInDischargeReportsVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.core.vo.IncludeAlertInDischargeReportsVo vo = voCollection.get(i); ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject = IncludeAlertInDischargeReportsVoAssembler.extractIncludeAlertInDischargeReport(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.clinical.domain.objects.IncludeAlertInDischargeReport object. * @param domainObject ims.core.clinical.domain.objects.IncludeAlertInDischargeReport */ public static ims.core.vo.IncludeAlertInDischargeReportsVo create(ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.clinical.domain.objects.IncludeAlertInDischargeReport object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.IncludeAlertInDischargeReportsVo create(DomainObjectMap map, ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.IncludeAlertInDischargeReportsVo valueObject = (ims.core.vo.IncludeAlertInDischargeReportsVo) map.getValueObject(domainObject, ims.core.vo.IncludeAlertInDischargeReportsVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.IncludeAlertInDischargeReportsVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.IncludeAlertInDischargeReport */ public static ims.core.vo.IncludeAlertInDischargeReportsVo insert(ims.core.vo.IncludeAlertInDischargeReportsVo valueObject, ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.IncludeAlertInDischargeReport */ public static ims.core.vo.IncludeAlertInDischargeReportsVo insert(DomainObjectMap map, ims.core.vo.IncludeAlertInDischargeReportsVo valueObject, ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_IncludeAlertInDischargeReport(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // CareContext if (domainObject.getCareContext() != null) { if(domainObject.getCareContext() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCareContext(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(id, -1)); } else { valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(domainObject.getCareContext().getId(), domainObject.getCareContext().getVersion())); } } // Alert if (domainObject.getAlert() != null) { if(domainObject.getAlert() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getAlert(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setAlert(new ims.core.clinical.vo.PatientAlertRefVo(id, -1)); } else { valueObject.setAlert(new ims.core.clinical.vo.PatientAlertRefVo(domainObject.getAlert().getId(), domainObject.getAlert().getVersion())); } } // IncludeInReport valueObject.setIncludeInReport( domainObject.isIncludeInReport() ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.clinical.domain.objects.IncludeAlertInDischargeReport extractIncludeAlertInDischargeReport(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.IncludeAlertInDischargeReportsVo valueObject) { return extractIncludeAlertInDischargeReport(domainFactory, valueObject, new HashMap()); } public static ims.core.clinical.domain.objects.IncludeAlertInDischargeReport extractIncludeAlertInDischargeReport(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.IncludeAlertInDischargeReportsVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_IncludeAlertInDischargeReport(); ims.core.clinical.domain.objects.IncludeAlertInDischargeReport domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.clinical.domain.objects.IncludeAlertInDischargeReport)domMap.get(valueObject); } // ims.core.vo.IncludeAlertInDischargeReportsVo ID_IncludeAlertInDischargeReport field is unknown domainObject = new ims.core.clinical.domain.objects.IncludeAlertInDischargeReport(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_IncludeAlertInDischargeReport()); if (domMap.get(key) != null) { return (ims.core.clinical.domain.objects.IncludeAlertInDischargeReport)domMap.get(key); } domainObject = (ims.core.clinical.domain.objects.IncludeAlertInDischargeReport) domainFactory.getDomainObject(ims.core.clinical.domain.objects.IncludeAlertInDischargeReport.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_IncludeAlertInDischargeReport()); ims.core.admin.domain.objects.CareContext value1 = null; if ( null != valueObject.getCareContext() ) { if (valueObject.getCareContext().getBoId() == null) { if (domMap.get(valueObject.getCareContext()) != null) { value1 = (ims.core.admin.domain.objects.CareContext)domMap.get(valueObject.getCareContext()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getCareContext(); } else { value1 = (ims.core.admin.domain.objects.CareContext)domainFactory.getDomainObject(ims.core.admin.domain.objects.CareContext.class, valueObject.getCareContext().getBoId()); } } domainObject.setCareContext(value1); ims.core.clinical.domain.objects.PatientAlert value2 = null; if ( null != valueObject.getAlert() ) { if (valueObject.getAlert().getBoId() == null) { if (domMap.get(valueObject.getAlert()) != null) { value2 = (ims.core.clinical.domain.objects.PatientAlert)domMap.get(valueObject.getAlert()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value2 = domainObject.getAlert(); } else { value2 = (ims.core.clinical.domain.objects.PatientAlert)domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientAlert.class, valueObject.getAlert().getBoId()); } } domainObject.setAlert(value2); domainObject.setIncludeInReport(valueObject.getIncludeInReport()); return domainObject; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/IncludeAlertInDischargeReportsVoAssembler.java
Java
agpl-3.0
20,649
import re from django.core.management import call_command from django_webtest import WebTest from .auth import TestUserMixin from .settings import SettingsMixin from popolo.models import Person from .uk_examples import UK2015ExamplesMixin class TestSearchView(TestUserMixin, SettingsMixin, UK2015ExamplesMixin, WebTest): def setUp(self): super(TestSearchView, self).setUp() call_command('rebuild_index', verbosity=0, interactive=False) def test_search_page(self): # we have to create the candidate by submitting the form as otherwise # we're not making sure the index update hook fires response = self.app.get('/search?q=Elizabeth') # have to use re to avoid matching search box self.assertFalse( re.search( r'''<a[^>]*>Elizabeth''', response.text ) ) self.assertFalse( re.search( r'''<a[^>]*>Mr Darcy''', response.text ) ) response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', user=self.user, ) form = response.forms['new-candidate-form'] form['name'] = 'Mr Darcy' form['email'] = 'darcy@example.com' form['source'] = 'Testing adding a new person to a post' form['party_gb_2015'] = self.labour_party_extra.base_id form.submit() response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', user=self.user, ) form = response.forms['new-candidate-form'] form['name'] = 'Elizabeth Bennet' form['email'] = 'lizzie@example.com' form['source'] = 'Testing adding a new person to a post' form['party_gb_2015'] = self.labour_party_extra.base_id form.submit() response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', user=self.user, ) form = response.forms['new-candidate-form'] form['name'] = "Charlotte O'Lucas" # testers license form['email'] = 'charlotte@example.com' form['source'] = 'Testing adding a new person to a post' form['party_gb_2015'] = self.labour_party_extra.base_id form.submit() # check searching finds them response = self.app.get('/search?q=Elizabeth') self.assertTrue( re.search( r'''<a[^>]*>Elizabeth''', response.text ) ) self.assertFalse( re.search( r'''<a[^>]*>Mr Darcy''', response.text ) ) response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', user=self.user, ) form = response.forms['new-candidate-form'] form['name'] = 'Elizabeth Jones' form['email'] = 'e.jones@example.com' form['source'] = 'Testing adding a new person to a post' form['party_gb_2015'] = self.labour_party_extra.base_id form.submit() response = self.app.get('/search?q=Elizabeth') self.assertTrue( re.search( r'''<a[^>]*>Elizabeth Bennet''', response.text ) ) self.assertTrue( re.search( r'''<a[^>]*>Elizabeth Jones''', response.text ) ) person = Person.objects.get(name='Elizabeth Jones') response = self.app.get( '/person/{0}/update'.format(person.id), user=self.user, ) form = response.forms['person-details'] form['name'] = 'Lizzie Jones' form['source'] = "Some source of this information" form.submit() response = self.app.get('/search?q=Elizabeth') self.assertTrue( re.search( r'''<a[^>]*>Elizabeth Bennet''', response.text ) ) self.assertFalse( re.search( r'''<a[^>]*>Elizabeth Jones''', response.text ) ) # check that searching for names with apostrophe works response = self.app.get("/search?q=O'Lucas") self.assertTrue( re.search( r'''<a[^>]*>Charlotte''', response.text ) )
mysociety/yournextrepresentative
candidates/tests/test_search.py
Python
agpl-3.0
4,466
#ifndef QGCPX4SENSORCALIBRATION_H #define QGCPX4SENSORCALIBRATION_H #include <QWidget> #include <UASInterface.h> #include <QAction> namespace Ui { class QGCPX4SensorCalibration; } class QGCPX4SensorCalibration : public QWidget { Q_OBJECT public: explicit QGCPX4SensorCalibration(QWidget *parent = 0); ~QGCPX4SensorCalibration(); public slots: /** * @brief Set currently active UAS * @param uas the current active UAS */ void setActiveUAS(UASInterface* uas); /** * @brief Handle text message from current active UAS * @param uasid * @param componentid * @param severity * @param text */ void handleTextMessage(int uasid, int componentid, int severity, QString text); void gyroButtonClicked(); void magButtonClicked(); void accelButtonClicked(); void diffPressureButtonClicked(); /** * @brief Hand context menu event * @param event */ virtual void contextMenuEvent(QContextMenuEvent* event); void setAutopilotOrientation(int index); void setGpsOrientation(int index); void parameterChanged(int uas, int component, QString parameterName, QVariant value); protected slots: void setInstructionImage(const QString &path); void setAutopilotImage(const QString &path); void setGpsImage(const int index); void setAutopilotImage(const int index); void setGpsImage(const QString &path); protected: UASInterface* activeUAS; QAction* clearAction; QPixmap instructionIcon; QPixmap autopilotIcon; QPixmap gpsIcon; virtual void resizeEvent(QResizeEvent* event); void setMagCalibrated(bool calibrated); void setGyroCalibrated(bool calibrated); void setAccelCalibrated(bool calibrated); void setDiffPressureCalibrated(bool calibrated); void updateIcons(); private: Ui::QGCPX4SensorCalibration *ui; }; #endif // QGCPX4SENSORCALIBRATION_H
josephlewis42/UDenverQGC2
src/ui/px4_configuration/QGCPX4SensorCalibration.h
C
agpl-3.0
1,940
<?php $mod_strings = array_merge($mod_strings, array( 'LBL_SECURITYGROUPS_SUBPANEL_TITLE' => "Gruppi di Sicurezza", 'LBL_PRIMARY_GROUP' => "Gruppo Primario", ) ); ?>
diogo827/SuiteCRM
custom/Extension/modules/Users/Ext/Language/it_it.SecurityGroups.php
PHP
agpl-3.0
202
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ccosched.forms.pattreatmentplan; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); Core = new CoreContext(context); CcoSched = new CcoSchedContext(context); } public final class CoreContext implements Serializable { private static final long serialVersionUID = 1L; private CoreContext(ims.framework.Context context) { this.context = context; } public boolean getPatientShortIsNotNull() { return !cx_CorePatientShort.getValueIsNull(context); } public ims.core.vo.PatientShort getPatientShort() { return (ims.core.vo.PatientShort)cx_CorePatientShort.getValue(context); } private ims.framework.ContextVariable cx_CorePatientShort = new ims.framework.ContextVariable("Core.PatientShort", "_cvp_Core.PatientShort"); public boolean getEpisodeofCareShortIsNotNull() { return !cx_CoreEpisodeofCareShort.getValueIsNull(context); } public ims.core.vo.EpisodeofCareShortVo getEpisodeofCareShort() { return (ims.core.vo.EpisodeofCareShortVo)cx_CoreEpisodeofCareShort.getValue(context); } private ims.framework.ContextVariable cx_CoreEpisodeofCareShort = new ims.framework.ContextVariable("Core.EpisodeofCareShort", "_cvp_Core.EpisodeofCareShort"); private ims.framework.Context context; } public final class CcoSchedContext implements Serializable { private static final long serialVersionUID = 1L; private CcoSchedContext(ims.framework.Context context) { this.context = context; TreatmentPlan = new TreatmentPlanContext(context); ActionUpdate = new ActionUpdateContext(context); ActivityView = new ActivityViewContext(context); CancelledAppointments = new CancelledAppointmentsContext(context); Rebooking = new RebookingContext(context); } public final class TreatmentPlanContext implements Serializable { private static final long serialVersionUID = 1L; private TreatmentPlanContext(ims.framework.Context context) { this.context = context; } public boolean getActionIDIsNotNull() { return !cx_CcoSchedTreatmentPlanActionID.getValueIsNull(context); } public String getActionID() { return (String)cx_CcoSchedTreatmentPlanActionID.getValue(context); } public void setActionID(String value) { cx_CcoSchedTreatmentPlanActionID.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanActionID = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.ActionID", "_cv_CcoSched.TreatmentPlan.ActionID"); public boolean getIgnoreActionID2IsNotNull() { return !cx_CcoSchedTreatmentPlanIgnoreActionID2.getValueIsNull(context); } public Boolean getIgnoreActionID2() { return (Boolean)cx_CcoSchedTreatmentPlanIgnoreActionID2.getValue(context); } public void setIgnoreActionID2(Boolean value) { cx_CcoSchedTreatmentPlanIgnoreActionID2.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanIgnoreActionID2 = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.IgnoreActionID2", "_cv_CcoSched.TreatmentPlan.IgnoreActionID2"); public boolean getFurtherAppointmentIsNotNull() { return !cx_CcoSchedTreatmentPlanFurtherAppointment.getValueIsNull(context); } public Boolean getFurtherAppointment() { return (Boolean)cx_CcoSchedTreatmentPlanFurtherAppointment.getValue(context); } public void setFurtherAppointment(Boolean value) { cx_CcoSchedTreatmentPlanFurtherAppointment.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanFurtherAppointment = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.FurtherAppointment", "_cv_CcoSched.TreatmentPlan.FurtherAppointment"); public boolean getTreatmentPlanUpdateScreenModeIsNotNull() { return !cx_CcoSchedTreatmentPlanTreatmentPlanUpdateScreenMode.getValueIsNull(context); } public Boolean getTreatmentPlanUpdateScreenMode() { return (Boolean)cx_CcoSchedTreatmentPlanTreatmentPlanUpdateScreenMode.getValue(context); } public void setTreatmentPlanUpdateScreenMode(Boolean value) { cx_CcoSchedTreatmentPlanTreatmentPlanUpdateScreenMode.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanTreatmentPlanUpdateScreenMode = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.TreatmentPlanUpdateScreenMode", "_cv_CcoSched.TreatmentPlan.TreatmentPlanUpdateScreenMode"); public boolean getActionModeIsNotNull() { return !cx_CcoSchedTreatmentPlanActionMode.getValueIsNull(context); } public Boolean getActionMode() { return (Boolean)cx_CcoSchedTreatmentPlanActionMode.getValue(context); } public void setActionMode(Boolean value) { cx_CcoSchedTreatmentPlanActionMode.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanActionMode = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.ActionMode", "_cv_CcoSched.TreatmentPlan.ActionMode"); public boolean getActionUpdateModeIsNotNull() { return !cx_CcoSchedTreatmentPlanActionUpdateMode.getValueIsNull(context); } public Integer getActionUpdateMode() { return (Integer)cx_CcoSchedTreatmentPlanActionUpdateMode.getValue(context); } public void setActionUpdateMode(Integer value) { cx_CcoSchedTreatmentPlanActionUpdateMode.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanActionUpdateMode = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.ActionUpdateMode", "_cv_CcoSched.TreatmentPlan.ActionUpdateMode"); public boolean getTreatmentPlanUpdateModeIsNotNull() { return !cx_CcoSchedTreatmentPlanTreatmentPlanUpdateMode.getValueIsNull(context); } public Integer getTreatmentPlanUpdateMode() { return (Integer)cx_CcoSchedTreatmentPlanTreatmentPlanUpdateMode.getValue(context); } public void setTreatmentPlanUpdateMode(Integer value) { cx_CcoSchedTreatmentPlanTreatmentPlanUpdateMode.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanTreatmentPlanUpdateMode = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.TreatmentPlanUpdateMode", "_cv_CcoSched.TreatmentPlan.TreatmentPlanUpdateMode"); public boolean getSelectedPlanIsNotNull() { return !cx_CcoSchedTreatmentPlanSelectedPlan.getValueIsNull(context); } public ims.dto.client.Sd_comp_plan getSelectedPlan() { return (ims.dto.client.Sd_comp_plan)cx_CcoSchedTreatmentPlanSelectedPlan.getValue(context); } public void setSelectedPlan(ims.dto.client.Sd_comp_plan value) { cx_CcoSchedTreatmentPlanSelectedPlan.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedTreatmentPlanSelectedPlan = new ims.framework.ContextVariable("CcoSched.TreatmentPlan.SelectedPlan", "_cv_CcoSched.TreatmentPlan.SelectedPlan"); private ims.framework.Context context; } public final class ActionUpdateContext implements Serializable { private static final long serialVersionUID = 1L; private ActionUpdateContext(ims.framework.Context context) { this.context = context; } public boolean getActionInsertedIdIsNotNull() { return !cx_CcoSchedActionUpdateActionInsertedId.getValueIsNull(context); } public String getActionInsertedId() { return (String)cx_CcoSchedActionUpdateActionInsertedId.getValue(context); } public void setActionInsertedId(String value) { cx_CcoSchedActionUpdateActionInsertedId.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedActionUpdateActionInsertedId = new ims.framework.ContextVariable("CcoSched.ActionUpdate.ActionInsertedId", "_cv_CcoSched.ActionUpdate.ActionInsertedId"); public boolean getTreatmentPlanActionsIsNotNull() { return !cx_CcoSchedActionUpdateTreatmentPlanActions.getValueIsNull(context); } public ims.ccosched.vo.PatTreatPlanActionVoCollection getTreatmentPlanActions() { return (ims.ccosched.vo.PatTreatPlanActionVoCollection)cx_CcoSchedActionUpdateTreatmentPlanActions.getValue(context); } public void setTreatmentPlanActions(ims.ccosched.vo.PatTreatPlanActionVoCollection value) { cx_CcoSchedActionUpdateTreatmentPlanActions.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedActionUpdateTreatmentPlanActions = new ims.framework.ContextVariable("CcoSched.ActionUpdate.TreatmentPlanActions", "_cv_CcoSched.ActionUpdate.TreatmentPlanActions"); private ims.framework.Context context; } public final class ActivityViewContext implements Serializable { private static final long serialVersionUID = 1L; private ActivityViewContext(ims.framework.Context context) { this.context = context; } public boolean getActionIDIsNotNull() { return !cx_CcoSchedActivityViewActionID.getValueIsNull(context); } public String getActionID() { return (String)cx_CcoSchedActivityViewActionID.getValue(context); } public void setActionID(String value) { cx_CcoSchedActivityViewActionID.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedActivityViewActionID = new ims.framework.ContextVariable("CcoSched.ActivityView.ActionID", "_cv_CcoSched.ActivityView.ActionID"); private ims.framework.Context context; } public final class CancelledAppointmentsContext implements Serializable { private static final long serialVersionUID = 1L; private CancelledAppointmentsContext(ims.framework.Context context) { this.context = context; } public boolean getRebookAppointmentDetailIsNotNull() { return !cx_CcoSchedCancelledAppointmentsRebookAppointmentDetail.getValueIsNull(context); } public String getRebookAppointmentDetail() { return (String)cx_CcoSchedCancelledAppointmentsRebookAppointmentDetail.getValue(context); } public void setRebookAppointmentDetail(String value) { cx_CcoSchedCancelledAppointmentsRebookAppointmentDetail.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedCancelledAppointmentsRebookAppointmentDetail = new ims.framework.ContextVariable("CcoSched.CancelledAppointments.RebookAppointmentDetail", "_cv_CcoSched.CancelledAppointments.RebookAppointmentDetail"); private ims.framework.Context context; } public final class RebookingContext implements Serializable { private static final long serialVersionUID = 1L; private RebookingContext(ims.framework.Context context) { this.context = context; } public boolean getRebookingSucceededIsNotNull() { return !cx_CcoSchedRebookingRebookingSucceeded.getValueIsNull(context); } public Boolean getRebookingSucceeded() { return (Boolean)cx_CcoSchedRebookingRebookingSucceeded.getValue(context); } public void setRebookingSucceeded(Boolean value) { cx_CcoSchedRebookingRebookingSucceeded.setValue(context, value); } private ims.framework.ContextVariable cx_CcoSchedRebookingRebookingSucceeded = new ims.framework.ContextVariable("CcoSched.Rebooking.RebookingSucceeded", "_cv_CcoSched.Rebooking.RebookingSucceeded"); private ims.framework.Context context; } public TreatmentPlanContext TreatmentPlan; public ActionUpdateContext ActionUpdate; public ActivityViewContext ActivityView; public CancelledAppointmentsContext CancelledAppointments; public RebookingContext Rebooking; private ims.framework.Context context; } public boolean getPatTreatmentPlanActionIsNotNull() { return !cx_PatTreatmentPlanAction.getValueIsNull(context); } public ims.ccosched.vo.PatTreatPlanActionVo getPatTreatmentPlanAction() { return (ims.ccosched.vo.PatTreatPlanActionVo)cx_PatTreatmentPlanAction.getValue(context); } public void setPatTreatmentPlanAction(ims.ccosched.vo.PatTreatPlanActionVo value) { cx_PatTreatmentPlanAction.setValue(context, value); } private ims.framework.ContextVariable cx_PatTreatmentPlanAction = new ims.framework.ContextVariable("PatTreatmentPlanAction", "_cv_PatTreatmentPlanAction"); public boolean getPatTreatmentPlanIsNotNull() { return !cx_PatTreatmentPlan.getValueIsNull(context); } public ims.ccosched.vo.PatTreatmentPlanLiteVo getPatTreatmentPlan() { return (ims.ccosched.vo.PatTreatmentPlanLiteVo)cx_PatTreatmentPlan.getValue(context); } public void setPatTreatmentPlan(ims.ccosched.vo.PatTreatmentPlanLiteVo value) { cx_PatTreatmentPlan.setValue(context, value); } private ims.framework.ContextVariable cx_PatTreatmentPlan = new ims.framework.ContextVariable("PatTreatmentPlan", "_cv_PatTreatmentPlan"); public CoreContext Core; public CcoSchedContext CcoSched; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/CcoSched/src/ims/ccosched/forms/pattreatmentplan/GlobalContext.java
Java
agpl-3.0
15,317
/* pygame - Python Game Library Copyright (C) 2000-2001 Pete Shinners This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Pete Shinners pete@shinners.org */ #include <Python.h> #if defined(HAVE_SNPRINTF) /* also defined in SDL_ttf (SDL.h) */ #undef HAVE_SNPRINTF /* remove GCC macro redefine warning */ #endif #include <SDL_ttf.h> /* test font initialization */ #define FONT_INIT_CHECK() \ if(!(*(int*)PyFONT_C_API[2])) \ return RAISE(pgExc_SDLError, "font system not initialized") #define PYGAMEAPI_FONT_FIRSTSLOT 0 #define PYGAMEAPI_FONT_NUMSLOTS 3 typedef struct { PyObject_HEAD TTF_Font* font; PyObject* weakreflist; } PyFontObject; #define PyFont_AsFont(x) (((PyFontObject*)x)->font) #ifndef PYGAMEAPI_FONT_INTERNAL #define PyFont_Check(x) ((x)->ob_type == (PyTypeObject*)PyFONT_C_API[0]) #define PyFont_Type (*(PyTypeObject*)PyFONT_C_API[0]) #define PyFont_New (*(PyObject*(*)(TTF_Font*))PyFONT_C_API[1]) /*slot 2 taken by FONT_INIT_CHECK*/ #define import_pygame_font() \ _IMPORT_PYGAME_MODULE(font, FONT, PyFONT_C_API) static void* PyFONT_C_API[PYGAMEAPI_FONT_NUMSLOTS] = {NULL}; #endif
mark-me/Pi-Jukebox
venv/Include/site/python3.7/pygame/font.h
C
agpl-3.0
1,836
import os import django from unipath import Path BASE_DIR = Path(os.path.abspath(__file__)) BOOKTYPE_SITE_NAME = '' BOOKTYPE_SITE_DIR = 'tests' THIS_BOOKTYPE_SERVER = '' BOOKTYPE_URL = '' BOOKTYPE_ROOT = BASE_DIR.parent STATIC_ROOT = BASE_DIR.parent.child("static") STATIC_URL = '{}/static/'.format(BOOKTYPE_URL) DATA_ROOT = BASE_DIR.parent.child("data") DATA_URL = '{}/data/'.format(BOOKTYPE_URL) MEDIA_ROOT = DATA_ROOT MEDIA_URL = DATA_URL # DEBUG DEBUG = TEMPLATE_DEBUG = True # PROFILE PROFILE_ACTIVE = 'test' if django.VERSION[:2] < (1, 6): TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_TOP_LEVEL = BASE_DIR.parent.parent.child('lib') TEST_DISCOVER_PATTERN = 'test*.py' ROOT_URLCONF = 'urls' SOUTH_TESTS_MIGRATE = False SKIP_SOUTH_TESTS = True SECRET_KEY = 'enc*ln*vp^o2p1p6of8ip9v5_tt6r#fh2-!-@pl0ur^6ul6e)l' COVER_IMAGE_UPLOAD_DIR = 'cover_images/' PROFILE_IMAGE_UPLOAD_DIR = 'profile_images/' # E-MAIL EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # CACHES CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # DATABASE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '' } } # REDIS REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 0 REDIS_PASSWORD = None MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.transaction.TransactionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'booktype.apps.core.middleware.SecurityMiddleware', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_results', # list of booki apps 'booki.editor', 'booktypecontrol', # needed for translation engine 'booktype', # list of booktype apps 'booktype.apps.core', 'booktype.apps.portal', 'booktype.apps.loadsave', 'booktype.apps.importer', 'booktype.apps.convert', 'booktype.apps.edit', 'booktype.apps.reader', 'booktype.apps.account', 'booktype.apps.themes', 'booki.messaging', 'sputnik', ) if django.VERSION[:2] < (1, 6): INSTALLED_APPS += ('discover_runner', ) if django.VERSION[:2] < (1, 7): INSTALLED_APPS += ('south', ) # this is for pep8 standard_format = { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" } # LOGGING LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': standard_format, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', } }, 'loggers': { 'django': { 'handlers': ['null'], 'propagate': True, 'level': 'WARN', }, 'django.db.backends': { 'handlers': ['null'], 'level': 'DEBUG', 'propagate': False, }, 'django.request': { 'handlers': ['null'], 'level': 'ERROR', 'propagate': True, }, 'booktype': { 'handlers': ['null'], 'level': 'INFO' } } } # READ CONFIGURAION # from booki.utils import config # # try: # BOOKTYPE_CONFIG = config.loadConfiguration() # except config.ConfigurationError: # BOOKTYPE_CONFIG = {} BOOKTYPE_NAME = BOOKTYPE_SITE_NAME BOOKI_NAME = BOOKTYPE_NAME BOOKI_ROOT = BOOKTYPE_ROOT BOOKI_URL = BOOKTYPE_URL THIS_BOOKI_SERVER = THIS_BOOKTYPE_SERVER BOOKI_MAINTENANCE_MODE = False
eos87/Booktype
tests/settings.py
Python
agpl-3.0
4,257
<%inherit file="../admin_dashboard_base.html" /> <%namespace name='static' file='../../static_content.html'/> <%! from django.conf import settings from django.core.urlresolvers import reverse from openedx.core.djangolib.markup import HTML %> <%block name="headextra"> <link href="${static.url('admin_dash/css/site-config.min.css')}" rel="stylesheet"> </%block> <%block name="content"> <div class="domain-details" id="domain-details"> <div class="x_panel"> <div class="x_title"> <h2>Domain Details</h2> <div class="clearfix"></div> </div> <div class="x_content"> <div class="error hidden alert alert-danger"> <strong class="message"></strong> </div> <form id="domain-config-form" class="form-horizontal form-label-left" data-toggle="validator"> <input type="hidden" id="csrf_token" name="csrfmiddlewaretoken" value="${csrf_token}"> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Platform Name</label> <div class="col-md-7 col-sm-7 col-xs-12"> <input type="text" id="platform-name" name="platform_name" class="form-control col-md-7 col-xs-12" value="${platform_name}" required> <div class="help-block with-errors"></div> </div> <div class="help_link control-label col-md-2 col-sm-2"> <span data-toggle="tooltip" data-placement="bottom" title="Changes Platform Name"><i class="fa fa-question-circle" aria-hidden="true"></i></span> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Site Name</label> <div class="col-md-7 col-sm-7 col-xs-12"> <input type="text" id="domain" name="domain" class="form-control col-md-7 col-xs-12" value="${domain}" required> <div class="help-block with-errors"></div> </div> <div class="help_link control-label col-md-2 col-sm-2"> <span data-toggle="tooltip" data-placement="bottom" title="Change Site Name"><i class="fa fa-question-circle" aria-hidden="true"></i></span> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Payment Support Email</label> <div class="col-md-7 col-sm-7 col-xs-12"> <input type="email" id="payment_support_email" name="payment_support_email" class="form-control col-md-7 col-xs-12" value="${payment_support_email}" required> <div class="help-block with-errors"></div> </div> <div class="help_link control-label col-md-2 col-sm-2"> <span data-toggle="tooltip" data-placement="bottom" title="Support Email For Payment queries"><i class="fa fa-question-circle" aria-hidden="true"></i></span> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Email From</label> <div class="col-md-7 col-sm-7 col-xs-12"> <input type="email" id="email_from_address" name="email_from_address" class="form-control col-md-7 col-xs-12" value="${email_from_address}" required> <div class="help-block with-errors"></div> </div> <div class="help_link control-label col-md-2 col-sm-2"> <span data-toggle="tooltip" data-placement="bottom" title="The email from which the mail will be sent to users."><i class="fa fa-question-circle" aria-hidden="true"></i></span> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Course Email From</label> <div class="col-md-7 col-sm-7 col-xs-12"> <input type="email" id="course_email_from_addr" name="course_email_from_addr" class="form-control col-md-7 col-xs-12" value="${course_email_from_addr}" required> <div class="help-block with-errors"></div> </div> <div class="help_link control-label col-md-2 col-sm-2"> <span data-toggle="tooltip" data-placement="bottom" title="Course details Email"><i class="fa fa-question-circle" aria-hidden="true"></i></span> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Google Analytics Account</label> <div class="col-md-7 col-sm-7 col-xs-12"> <input type="text" id="google_analytics_account" name="google_analytics_account" class="form-control col-md-7 col-xs-12" value="${google_analytics_account}"> </div> <div class="help_link control-label col-md-2 col-sm-2"> <span><a href="https://analytics.google.com/analytics/web/provision/?authuser=0#provision/SignUp/" target="_blank">Learn More!</a></span> </div> </div> <div class="ln_solid"></div> <div class="form-group"> <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3"> <button type="button" class="btn btn-success" id="domain-config">Save Changes</button> </div> </div> </form> </div> </div> </div> </%block> <%block name="js_extra"> <script src="${static.url('admin_dash/js/validator.js')}"></script> <script src="${static.url('admin_dash/js/configuration.js')}"></script> </%block>
synergeticsedx/deployment-wipro
themes/synergetics-theme/lms/templates/admin_dash/configuration/domain_content.html
HTML
agpl-3.0
6,175
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinicaladmin.forms.oncologycontacttypes; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); } }
open-health-hub/openmaxims-linux
openmaxims_workspace/ClinicalAdmin/src/ims/clinicaladmin/forms/oncologycontacttypes/GlobalContext.java
Java
agpl-3.0
2,020
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.cliniclistnotespulling; public interface IFormUILogicCode { // No methods yet. }
open-health-hub/openmaxims-linux
openmaxims_workspace/Clinical/src/ims/clinical/forms/cliniclistnotespulling/IFormUILogicCode.java
Java
agpl-3.0
1,812
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.correspondence.forms.userprofile; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } public static class grdConsultantRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdConsultantRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setColConsultantImageReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isColConsultantImageReadOnly() { return super.row.isReadOnly(0); } public void showColConsultantImageOpened() { super.row.showOpened(0); } public ims.framework.utils.Image getColConsultantImage() { return (ims.framework.utils.Image)super.row.get(0); } public void setColConsultantImage(ims.framework.utils.Image value) { super.row.set(0, value); } public void setCellColConsultantImageTooltip(String value) { super.row.setTooltip(0, value); } public void setcolConsultantReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean iscolConsultantReadOnly() { return super.row.isReadOnly(1); } public void showcolConsultantOpened() { super.row.showOpened(1); } public String getcolConsultant() { return (String)super.row.get(1); } public void setcolConsultant(String value) { super.row.set(1, value); } public void setCellcolConsultantTooltip(String value) { super.row.setTooltip(1, value); } public void setcolAccessReadOnly(boolean value) { super.row.setReadOnly(2, value); } public boolean iscolAccessReadOnly() { return super.row.isReadOnly(2); } public void showcolAccessOpened() { super.row.showOpened(2); } public ims.correspondence.vo.lookups.Access getcolAccess() { return (ims.correspondence.vo.lookups.Access)super.row.get(2); } public void setcolAccess(ims.correspondence.vo.lookups.Access value) { super.row.set(2, value, true); } public void setCellcolAccessTooltip(String value) { super.row.setTooltip(2, value); } public ims.vo.ValueObject getValue() { return (ims.vo.ValueObject)super.row.getValue(); } public void setValue(ims.vo.ValueObject value) { super.row.setValue(value); } } public static class grdConsultantRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdConsultantRowCollection(GridRowCollection collection) { super(collection); } public grdConsultantRow get(int index) { return new grdConsultantRow(super.collection.get(index)); } public grdConsultantRow newRow() { return new grdConsultantRow(super.collection.newRow()); } public grdConsultantRow newRow(boolean autoSelect) { return new grdConsultantRow(super.collection.newRow(autoSelect)); } public grdConsultantRow newRowAt(int index) { return new grdConsultantRow(super.collection.newRowAt(index)); } public grdConsultantRow newRowAt(int index, boolean autoSelect) { return new grdConsultantRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdConsultantGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addImageColumn(String caption, int captionAlignment, int alignment, int width, boolean canGrow, int sortOrder) { super.grid.addImageColumn(caption, captionAlignment, alignment, width, canGrow, sortOrder); } private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } private void addComboBoxColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, boolean autoPostBack, boolean bold, boolean canGrow, int maxDropDownItems) { super.grid.addComboBoxColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, autoPostBack, bold, canGrow, maxDropDownItems); } public ims.vo.ValueObject[] getValues() { ims.vo.ValueObject[] listOfValues = new ims.vo.ValueObject[this.getRows().size()]; for(int x = 0; x < this.getRows().size(); x++) { listOfValues[x] = this.getRows().get(x).getValue(); } return listOfValues; } public ims.vo.ValueObject getValue() { return (ims.vo.ValueObject)super.grid.getValue(); } public void setValue(ims.vo.ValueObject value) { super.grid.setValue(value); } public grdConsultantRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdConsultantRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdConsultantRowCollection getRows() { return new grdConsultantRowCollection(super.grid.getRows()); } public grdConsultantRow getRowByValue(ims.vo.ValueObject value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdConsultantRow(row); } public void setColConsultantImageHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getColConsultantImageHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setcolConsultantHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getcolConsultantHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } public void setcolAccessHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(2, value); } public String getcolAccessHeaderTooltip() { return super.grid.getColumnHeaderTooltip(2); } public GridComboBox colAccessComboBox() { return new GridComboBox(super.grid, 2); } } public static class grdUsersRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdUsersRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setcolUserNameReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean iscolUserNameReadOnly() { return super.row.isReadOnly(0); } public void showcolUserNameOpened() { super.row.showOpened(0); } public String getcolUserName() { return (String)super.row.get(0); } public void setcolUserName(String value) { super.row.set(0, value); } public void setCellcolUserNameTooltip(String value) { super.row.setTooltip(0, value); } public void setcolRealNameReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean iscolRealNameReadOnly() { return super.row.isReadOnly(1); } public void showcolRealNameOpened() { super.row.showOpened(1); } public String getcolRealName() { return (String)super.row.get(1); } public void setcolRealName(String value) { super.row.set(1, value); } public void setCellcolRealNameTooltip(String value) { super.row.setTooltip(1, value); } public ims.admin.vo.AppUserShortVo getValue() { return (ims.admin.vo.AppUserShortVo)super.row.getValue(); } public void setValue(ims.admin.vo.AppUserShortVo value) { super.row.setValue(value); } } public static class grdUsersRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdUsersRowCollection(GridRowCollection collection) { super(collection); } public grdUsersRow get(int index) { return new grdUsersRow(super.collection.get(index)); } public grdUsersRow newRow() { return new grdUsersRow(super.collection.newRow()); } public grdUsersRow newRow(boolean autoSelect) { return new grdUsersRow(super.collection.newRow(autoSelect)); } public grdUsersRow newRowAt(int index) { return new grdUsersRow(super.collection.newRowAt(index)); } public grdUsersRow newRowAt(int index, boolean autoSelect) { return new grdUsersRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdUsersGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } public ims.admin.vo.AppUserShortVoCollection getValues() { ims.admin.vo.AppUserShortVoCollection listOfValues = new ims.admin.vo.AppUserShortVoCollection(); for(int x = 0; x < this.getRows().size(); x++) { listOfValues.add(this.getRows().get(x).getValue()); } return listOfValues; } public ims.admin.vo.AppUserShortVo getValue() { return (ims.admin.vo.AppUserShortVo)super.grid.getValue(); } public void setValue(ims.admin.vo.AppUserShortVo value) { super.grid.setValue(value); } public grdUsersRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdUsersRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdUsersRowCollection getRows() { return new grdUsersRowCollection(super.grid.getRows()); } public grdUsersRow getRowByValue(ims.admin.vo.AppUserShortVo value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdUsersRow(row); } public void setcolUserNameHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getcolUserNameHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setcolRealNameHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getcolRealNameHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } } public static class grdSpecialtyRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdSpecialtyRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setcolSpecialtyImageReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean iscolSpecialtyImageReadOnly() { return super.row.isReadOnly(0); } public void showcolSpecialtyImageOpened() { super.row.showOpened(0); } public ims.framework.utils.Image getcolSpecialtyImage() { return (ims.framework.utils.Image)super.row.get(0); } public void setcolSpecialtyImage(ims.framework.utils.Image value) { super.row.set(0, value); } public void setCellcolSpecialtyImageTooltip(String value) { super.row.setTooltip(0, value); } public void setcolSpecialtyReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean iscolSpecialtyReadOnly() { return super.row.isReadOnly(1); } public void showcolSpecialtyOpened() { super.row.showOpened(1); } public String getcolSpecialty() { return (String)super.row.get(1); } public void setcolSpecialty(String value) { super.row.set(1, value); } public void setCellcolSpecialtyTooltip(String value) { super.row.setTooltip(1, value); } public void setcolAccessReadOnly(boolean value) { super.row.setReadOnly(2, value); } public boolean iscolAccessReadOnly() { return super.row.isReadOnly(2); } public void showcolAccessOpened() { super.row.showOpened(2); } public ims.correspondence.vo.lookups.Access getcolAccess() { return (ims.correspondence.vo.lookups.Access)super.row.get(2); } public void setcolAccess(ims.correspondence.vo.lookups.Access value) { super.row.set(2, value, true); } public void setCellcolAccessTooltip(String value) { super.row.setTooltip(2, value); } public Object getValue() { return super.row.getValue(); } public void setValue(Object value) { super.row.setValue(value); } } public static class grdSpecialtyRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdSpecialtyRowCollection(GridRowCollection collection) { super(collection); } public grdSpecialtyRow get(int index) { return new grdSpecialtyRow(super.collection.get(index)); } public grdSpecialtyRow newRow() { return new grdSpecialtyRow(super.collection.newRow()); } public grdSpecialtyRow newRow(boolean autoSelect) { return new grdSpecialtyRow(super.collection.newRow(autoSelect)); } public grdSpecialtyRow newRowAt(int index) { return new grdSpecialtyRow(super.collection.newRowAt(index)); } public grdSpecialtyRow newRowAt(int index, boolean autoSelect) { return new grdSpecialtyRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdSpecialtyGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addImageColumn(String caption, int captionAlignment, int alignment, int width, boolean canGrow, int sortOrder) { super.grid.addImageColumn(caption, captionAlignment, alignment, width, canGrow, sortOrder); } private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } private void addComboBoxColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, boolean autoPostBack, boolean bold, boolean canGrow, int maxDropDownItems) { super.grid.addComboBoxColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, autoPostBack, bold, canGrow, maxDropDownItems); } public Object[] getValues() { Object[] listOfValues = new Object[this.getRows().size()]; for(int x = 0; x < this.getRows().size(); x++) { listOfValues[x] = this.getRows().get(x).getValue(); } return listOfValues; } public Object getValue() { return super.grid.getValue(); } public void setValue(Object value) { super.grid.setValue(value); } public grdSpecialtyRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdSpecialtyRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdSpecialtyRowCollection getRows() { return new grdSpecialtyRowCollection(super.grid.getRows()); } public grdSpecialtyRow getRowByValue(Object value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdSpecialtyRow(row); } public void setcolSpecialtyImageHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getcolSpecialtyImageHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setcolSpecialtyHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getcolSpecialtyHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } public void setcolAccessHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(2, value); } public String getcolAccessHeaderTooltip() { return super.grid.getColumnHeaderTooltip(2); } public GridComboBox colAccessComboBox() { return new GridComboBox(super.grid, 2); } } public static class grdClinicRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdClinicRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setcolClinicImageReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean iscolClinicImageReadOnly() { return super.row.isReadOnly(0); } public void showcolClinicImageOpened() { super.row.showOpened(0); } public ims.framework.utils.Image getcolClinicImage() { return (ims.framework.utils.Image)super.row.get(0); } public void setcolClinicImage(ims.framework.utils.Image value) { super.row.set(0, value); } public void setCellcolClinicImageTooltip(String value) { super.row.setTooltip(0, value); } public void setcolClinicReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean iscolClinicReadOnly() { return super.row.isReadOnly(1); } public void showcolClinicOpened() { super.row.showOpened(1); } public String getcolClinic() { return (String)super.row.get(1); } public void setcolClinic(String value) { super.row.set(1, value); } public void setCellcolClinicTooltip(String value) { super.row.setTooltip(1, value); } public void setcolAccessReadOnly(boolean value) { super.row.setReadOnly(2, value); } public boolean iscolAccessReadOnly() { return super.row.isReadOnly(2); } public void showcolAccessOpened() { super.row.showOpened(2); } public ims.correspondence.vo.lookups.Access getcolAccess() { return (ims.correspondence.vo.lookups.Access)super.row.get(2); } public void setcolAccess(ims.correspondence.vo.lookups.Access value) { super.row.set(2, value, true); } public void setCellcolAccessTooltip(String value) { super.row.setTooltip(2, value); } public ims.vo.ValueObject getValue() { return (ims.vo.ValueObject)super.row.getValue(); } public void setValue(ims.vo.ValueObject value) { super.row.setValue(value); } } public static class grdClinicRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdClinicRowCollection(GridRowCollection collection) { super(collection); } public grdClinicRow get(int index) { return new grdClinicRow(super.collection.get(index)); } public grdClinicRow newRow() { return new grdClinicRow(super.collection.newRow()); } public grdClinicRow newRow(boolean autoSelect) { return new grdClinicRow(super.collection.newRow(autoSelect)); } public grdClinicRow newRowAt(int index) { return new grdClinicRow(super.collection.newRowAt(index)); } public grdClinicRow newRowAt(int index, boolean autoSelect) { return new grdClinicRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdClinicGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addImageColumn(String caption, int captionAlignment, int alignment, int width, boolean canGrow, int sortOrder) { super.grid.addImageColumn(caption, captionAlignment, alignment, width, canGrow, sortOrder); } private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } private void addComboBoxColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, boolean autoPostBack, boolean bold, boolean canGrow, int maxDropDownItems) { super.grid.addComboBoxColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, autoPostBack, bold, canGrow, maxDropDownItems); } public ims.vo.ValueObject[] getValues() { ims.vo.ValueObject[] listOfValues = new ims.vo.ValueObject[this.getRows().size()]; for(int x = 0; x < this.getRows().size(); x++) { listOfValues[x] = this.getRows().get(x).getValue(); } return listOfValues; } public ims.vo.ValueObject getValue() { return (ims.vo.ValueObject)super.grid.getValue(); } public void setValue(ims.vo.ValueObject value) { super.grid.setValue(value); } public grdClinicRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdClinicRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdClinicRowCollection getRows() { return new grdClinicRowCollection(super.grid.getRows()); } public grdClinicRow getRowByValue(ims.vo.ValueObject value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdClinicRow(row); } public void setcolClinicImageHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getcolClinicImageHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setcolClinicHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getcolClinicHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } public void setcolAccessHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(2, value); } public String getcolAccessHeaderTooltip() { return super.grid.getColumnHeaderTooltip(2); } public GridComboBox colAccessComboBox() { return new GridComboBox(super.grid, 2); } } private void validateContext(ims.framework.Context context) { if(context == null) return; } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { validateContext(context); } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class)); super.setLocalContext(new LocalContext(context, form.getFormInfo(), componentIdentifier)); // Panel Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 8, 208, 272, 384, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT,"Consultant", new Integer(2), ""})); RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 204, 24, 424, 179, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,"User Search", new Integer(2), ""})); RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 288, 208, 272, 384, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Specialty", new Integer(2), ""})); RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 568, 208, 272, 384, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT); super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT,"Clinic", new Integer(2), ""})); // Label Controls RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 220, 48, 88, 13, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Real Surame:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 674, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), new Integer(startTabIndex.intValue() + 13), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Save", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 754, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), new Integer(startTabIndex.intValue() + 12), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 16, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), new Integer(startTabIndex.intValue() + 14), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Edit", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 519, 43, 75, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1008), new Integer(anchoringHelper9.getX()), new Integer(anchoringHelper9.getY()), new Integer(anchoringHelper9.getWidth()), new Integer(anchoringHelper9.getHeight()), new Integer(startTabIndex.intValue() + 10), ControlState.ENABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Search", Boolean.FALSE, null, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // TextBox Controls RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 311, 45, 192, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), new Integer(startTabIndex.intValue() + 9), ControlState.ENABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(0), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); // Grid Controls RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 16, 266, 256, 310, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT); Grid m_grdConsultantTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), new Integer(-1), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT,Boolean.FALSE, Boolean.FALSE, new Integer(24), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdConsultantTemp); grdConsultantGrid grdConsultant = (grdConsultantGrid)GridFlyweightFactory.getInstance().createGridBridge(grdConsultantGrid.class, m_grdConsultantTemp); grdConsultant.addImageColumn(" ", 0, 0, 32, true, 0); grdConsultant.addStringColumn("Name", 0, 0, 150, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdConsultant.addComboBoxColumn("Access", 0, 0, -1, false, true, false, false, true, -1); super.addGrid(grdConsultant); RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 216, 72, 376, 120, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); Grid m_grdUsersTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), new Integer(startTabIndex.intValue() + 15), ControlState.READONLY, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdUsersTemp); grdUsersGrid grdUsers = (grdUsersGrid)GridFlyweightFactory.getInstance().createGridBridge(grdUsersGrid.class, m_grdUsersTemp); grdUsers.addStringColumn("User Name", 0, 0, 120, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdUsers.addStringColumn("Real Name", 0, 0, 200, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); super.addGrid(grdUsers); RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 296, 264, 256, 310, ims.framework.enumerations.ControlAnchoring.ALL); Grid m_grdSpecialtyTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper13.getX()), new Integer(anchoringHelper13.getY()), new Integer(anchoringHelper13.getWidth()), new Integer(anchoringHelper13.getHeight()), new Integer(-1), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.FALSE, Boolean.FALSE, new Integer(24), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdSpecialtyTemp); grdSpecialtyGrid grdSpecialty = (grdSpecialtyGrid)GridFlyweightFactory.getInstance().createGridBridge(grdSpecialtyGrid.class, m_grdSpecialtyTemp); grdSpecialty.addImageColumn(" ", 0, 0, 32, true, 0); grdSpecialty.addStringColumn("Specialty", 0, 0, 150, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdSpecialty.addComboBoxColumn("Access", 0, 0, -1, false, true, false, false, true, -1); super.addGrid(grdSpecialty); RuntimeAnchoring anchoringHelper14 = new RuntimeAnchoring(designSize, runtimeSize, 576, 264, 256, 310, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT); Grid m_grdClinicTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1013), new Integer(anchoringHelper14.getX()), new Integer(anchoringHelper14.getY()), new Integer(anchoringHelper14.getWidth()), new Integer(anchoringHelper14.getHeight()), new Integer(-1), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT,Boolean.FALSE, Boolean.FALSE, new Integer(24), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdClinicTemp); grdClinicGrid grdClinic = (grdClinicGrid)GridFlyweightFactory.getInstance().createGridBridge(grdClinicGrid.class, m_grdClinicTemp); grdClinic.addImageColumn(" ", 0, 0, 32, true, 0); grdClinic.addStringColumn("Clinic", 0, 0, 150, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdClinic.addComboBoxColumn("Access", 0, 0, -1, false, true, false, false, true, -1); super.addGrid(grdClinic); // Image Buttons Controls RuntimeAnchoring anchoringHelper15 = new RuntimeAnchoring(designSize, runtimeSize, 248, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1014), new Integer(anchoringHelper15.getX()), new Integer(anchoringHelper15.getY()), new Integer(anchoringHelper15.getWidth()), new Integer(anchoringHelper15.getHeight()), new Integer(startTabIndex.intValue() + 3), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, this.getImages().Core.ClearEnabled16, this.getImages().Core.ClearDisabled16, "Remove access from all consultants", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper16 = new RuntimeAnchoring(designSize, runtimeSize, 216, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1015), new Integer(anchoringHelper16.getX()), new Integer(anchoringHelper16.getY()), new Integer(anchoringHelper16.getWidth()), new Integer(anchoringHelper16.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, this.getImages().Core.AnswerBox_No, this.getImages().Core.AnswerBox_No, "Grant R/O access from all consultants", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper17 = new RuntimeAnchoring(designSize, runtimeSize, 184, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1016), new Integer(anchoringHelper17.getX()), new Integer(anchoringHelper17.getY()), new Integer(anchoringHelper17.getWidth()), new Integer(anchoringHelper17.getHeight()), new Integer(-1), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, this.getImages().Core.AnswerBox_Yes, this.getImages().Core.AnswerBox_Yes, "Grant R/W access to all consultants", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper18 = new RuntimeAnchoring(designSize, runtimeSize, 528, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1017), new Integer(anchoringHelper18.getX()), new Integer(anchoringHelper18.getY()), new Integer(anchoringHelper18.getWidth()), new Integer(anchoringHelper18.getHeight()), new Integer(startTabIndex.intValue() + 5), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.ClearEnabled16, this.getImages().Core.ClearDisabled16, "Remove access from all specialties", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper19 = new RuntimeAnchoring(designSize, runtimeSize, 496, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1018), new Integer(anchoringHelper19.getX()), new Integer(anchoringHelper19.getY()), new Integer(anchoringHelper19.getWidth()), new Integer(anchoringHelper19.getHeight()), new Integer(startTabIndex.intValue() + 4), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.AnswerBox_No, this.getImages().Core.AnswerBox_No, "Grant R/O access from all specialties", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper20 = new RuntimeAnchoring(designSize, runtimeSize, 464, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1019), new Integer(anchoringHelper20.getX()), new Integer(anchoringHelper20.getY()), new Integer(anchoringHelper20.getWidth()), new Integer(anchoringHelper20.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.AnswerBox_Yes, this.getImages().Core.AnswerBox_Yes, "Grant R/W access to all specialties", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper21 = new RuntimeAnchoring(designSize, runtimeSize, 808, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1020), new Integer(anchoringHelper21.getX()), new Integer(anchoringHelper21.getY()), new Integer(anchoringHelper21.getWidth()), new Integer(anchoringHelper21.getHeight()), new Integer(startTabIndex.intValue() + 8), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.ClearEnabled16, this.getImages().Core.ClearDisabled16, "Remove all access from all clinics", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper22 = new RuntimeAnchoring(designSize, runtimeSize, 776, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1021), new Integer(anchoringHelper22.getX()), new Integer(anchoringHelper22.getY()), new Integer(anchoringHelper22.getWidth()), new Integer(anchoringHelper22.getHeight()), new Integer(startTabIndex.intValue() + 7), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.AnswerBox_No, this.getImages().Core.AnswerBox_No, "Grant R/O access from all clinics", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper23 = new RuntimeAnchoring(designSize, runtimeSize, 744, 232, 24, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1022), new Integer(anchoringHelper23.getX()), new Integer(anchoringHelper23.getY()), new Integer(anchoringHelper23.getWidth()), new Integer(anchoringHelper23.getHeight()), new Integer(startTabIndex.intValue() + 6), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.AnswerBox_Yes, this.getImages().Core.AnswerBox_Yes, "Grant R/W access to all clinics", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); } public Images getImages() { return (Images)super.getImageReferences(); } public Button btnSave() { return (Button)super.getControl(5); } public Button btnCancel() { return (Button)super.getControl(6); } public Button btnUpdate() { return (Button)super.getControl(7); } public Button btnSearch() { return (Button)super.getControl(8); } public TextBox txtUserName() { return (TextBox)super.getControl(9); } public grdConsultantGrid grdConsultant() { return (grdConsultantGrid)super.getGrid(0); } public grdUsersGrid grdUsers() { return (grdUsersGrid)super.getGrid(1); } public grdSpecialtyGrid grdSpecialty() { return (grdSpecialtyGrid)super.getGrid(2); } public grdClinicGrid grdClinic() { return (grdClinicGrid)super.getGrid(3); } public ImageButton imbClearAllConsultants() { return (ImageButton)super.getControl(14); } public ImageButton imbGrantROAllConsultants() { return (ImageButton)super.getControl(15); } public ImageButton imbSelectAllConsultants() { return (ImageButton)super.getControl(16); } public ImageButton imbClearAllSpecialies() { return (ImageButton)super.getControl(17); } public ImageButton imbGrantROAllSpecialties() { return (ImageButton)super.getControl(18); } public ImageButton imbSelectAllSpecialties() { return (ImageButton)super.getControl(19); } public ImageButton imbClearClinics() { return (ImageButton)super.getControl(20); } public ImageButton imbGrantROAllClinics() { return (ImageButton)super.getControl(21); } public ImageButton imbSelectAllClinics() { return (ImageButton)super.getControl(22); } public static class Images implements java.io.Serializable { private static final long serialVersionUID = 1L; private final class ImageHelper extends ims.framework.utils.ImagePath { private static final long serialVersionUID = 1L; private ImageHelper(int id, String path, Integer width, Integer height) { super(id, path, width, height); } } private Images() { Core = new CoreImages(); Admin = new AdminImages(); } public final class CoreImages implements java.io.Serializable { private static final long serialVersionUID = 1L; private CoreImages() { AnswerBox_No = new ImageHelper(102100, "Images/Core/answer_no.png", new Integer(10), new Integer(10)); AnswerBox_Yes = new ImageHelper(102101, "Images/Core/answer_yes.png", new Integer(10), new Integer(10)); ClearEnabled16 = new ImageHelper(102168, "Images/Core/Clear.gif", new Integer(16), new Integer(16)); ClearDisabled16 = new ImageHelper(102167, "Images/Core/ClearDisabled16.gif", new Integer(16), new Integer(16)); } public final ims.framework.utils.Image AnswerBox_No; public final ims.framework.utils.Image AnswerBox_Yes; public final ims.framework.utils.Image ClearEnabled16; public final ims.framework.utils.Image ClearDisabled16; } public final class AdminImages implements java.io.Serializable { private static final long serialVersionUID = 1L; private AdminImages() { Location = new ImageHelper(103104, "Images/Admin/location.png", new Integer(16), new Integer(16)); Service = new ImageHelper(103110, "Images/Admin/clinical_service.png", new Integer(16), new Integer(16)); MemberOfStaff = new ImageHelper(103133, "Images/Admin/User-Offline.gif", new Integer(16), new Integer(16)); } public final ims.framework.utils.Image Location; public final ims.framework.utils.Image Service; public final ims.framework.utils.Image MemberOfStaff; } public final CoreImages Core; public final AdminImages Admin; } public LocalContext getLocalContext() { return (LocalContext)super.getLocalCtx(); } public class LocalContext extends ContextBridge { private static final long serialVersionUID = 1L; public LocalContext(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { super.setContext(context); String prefix = formInfo.getLocalVariablesPrefix(); cxl_SelectedUser = new ims.framework.ContextVariable("SelectedUser", prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier + ""); cxl_SelectedInstance = new ims.framework.ContextVariable("SelectedInstance", prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedInstance_" + componentIdentifier + ""); } public boolean getSelectedUserIsNotNull() { return !cxl_SelectedUser.getValueIsNull(context); } public ims.admin.vo.AppUserShortVo getSelectedUser() { return (ims.admin.vo.AppUserShortVo)cxl_SelectedUser.getValue(context); } public void setSelectedUser(ims.admin.vo.AppUserShortVo value) { cxl_SelectedUser.setValue(context, value); } private ims.framework.ContextVariable cxl_SelectedUser = null; public boolean getSelectedInstanceIsNotNull() { return !cxl_SelectedInstance.getValueIsNull(context); } public ims.correspondence.vo.UserAccessVo getSelectedInstance() { return (ims.correspondence.vo.UserAccessVo)cxl_SelectedInstance.getValue(context); } public void setSelectedInstance(ims.correspondence.vo.UserAccessVo value) { cxl_SelectedInstance.setValue(context, value); } private ims.framework.ContextVariable cxl_SelectedInstance = null; } private IReportField[] getFormReportFields() { if(this.context == null) return null; if(this.reportFields == null) this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields(); return this.reportFields; } private class ReportFields { public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { this.context = context; this.formInfo = formInfo; this.componentIdentifier = componentIdentifier; } public IReportField[] getReportFields() { String prefix = formInfo.getLocalVariablesPrefix(); IReportField[] fields = new IReportField[85]; fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient"); fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex"); fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob"); fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod"); fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion"); fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive"); fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin"); fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus"); fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN"); fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation"); fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath"); fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient"); fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant"); fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient"); fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex"); fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob"); fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact"); fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty"); fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType"); fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime"); fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime"); fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext"); fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated"); fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp"); fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType"); fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive"); fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context"); fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate"); fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime"); fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime"); fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType"); fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP"); fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare"); fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell"); fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty"); fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship"); fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate"); fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate"); fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote"); fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType"); fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline"); fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact"); fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote"); fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview"); fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime"); fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected"); fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed"); fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote"); fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime"); fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport"); fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext"); fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState"); fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission"); fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus"); fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode"); fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate"); fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview"); fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext"); fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent"); fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails"); fields[70] = new ims.framework.ReportField(this.context, "_cvp_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral"); fields[71] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-ID", "ID_AppUser"); fields[72] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-USERNAME", "Username"); fields[73] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-PASSWORD", "Password"); fields[74] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-ENCODEDPASSWORD", "EncodedPassword"); fields[75] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-THEME", "Theme"); fields[76] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-PWDEXPDATE", "PwdExpDate"); fields[77] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-EFFECTIVEFROM", "EffectiveFrom"); fields[78] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-EFFECTIVETO", "EffectiveTo"); fields[79] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-ISACTIVE", "IsActive"); fields[80] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-DEBUGMODE", "DebugMode"); fields[81] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-LDAPUSERNAME", "LDAPUsername"); fields[82] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedUser_" + componentIdentifier, "BO-1021100004-LDAPPASSWORD", "LDAPPassword"); fields[83] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedInstance_" + componentIdentifier, "BO-1053100011-ID", "ID_UserAccess"); fields[84] = new ims.framework.ReportField(this.context, prefix + "_lv_Correspondence.UserProfile.__internal_x_context__SelectedInstance_" + componentIdentifier, "BO-1053100011-APPUSER", "AppUser"); return fields; } protected Context context = null; protected ims.framework.FormInfo formInfo; protected String componentIdentifier; } public String getUniqueIdentifier() { return null; } private Context context = null; private ims.framework.FormInfo formInfo = null; private String componentIdentifier; private IReportField[] reportFields = null; }
open-health-hub/openmaxims-linux
openmaxims_workspace/Correspondence/src/ims/correspondence/forms/userprofile/GenForm.java
Java
agpl-3.0
65,221
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package info.ineighborhood.cardme.vcard.types; import info.ineighborhood.cardme.util.Util; import info.ineighborhood.cardme.vcard.EncodingType; import info.ineighborhood.cardme.vcard.VCardType; import info.ineighborhood.cardme.vcard.features.SortStringFeature; import info.ineighborhood.cardme.vcard.types.parameters.ParameterTypeStyle; /** * Copyright (c) 2004, Neighborhood Technologies * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Neighborhood Technologies nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * * @author George El-Haddad * <br/> * Feb 4, 2010 * */ public class SortStringType extends Type implements SortStringFeature { private String sortString = null; public SortStringType() { this(null); } public SortStringType(String sortString) { super(EncodingType.EIGHT_BIT, ParameterTypeStyle.PARAMETER_VALUE_LIST); setSortString(sortString); } /** * {@inheritDoc} */ public String getSortString() { return sortString; } /** * {@inheritDoc} */ public void setSortString(String sortString) { this.sortString = sortString; } /** * {@inheritDoc} */ public void clearSortString() { sortString = null; } /** * {@inheritDoc} */ public boolean hasSortString() { return sortString != null; } /** * {@inheritDoc} */ @Override public String getTypeString() { return VCardType.SORT_STRING.getType(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if(obj != null) { if(obj instanceof SortStringType) { if(this == obj || ((SortStringType)obj).hashCode() == this.hashCode()) { return true; } else { return false; } } else { return false; } } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return Util.generateHashCode(toString()); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()); sb.append("[ "); if(encodingType != null) { sb.append(encodingType.getType()); sb.append(","); } if(sortString != null) { sb.append(sortString); sb.append(","); } if(super.id != null) { sb.append(super.id); sb.append(","); } sb.deleteCharAt(sb.length()-1); //Remove last comma. sb.append(" ]"); return sb.toString(); } /** * {@inheritDoc} */ @Override public SortStringFeature clone() { SortStringType cloned = new SortStringType(); if(sortString != null) { cloned.setSortString(new String(sortString)); } cloned.setParameterTypeStyle(getParameterTypeStyle()); cloned.setEncodingType(getEncodingType()); cloned.setID(getID()); return cloned; } }
FullMetal210/milton2
external/cardme/src/main/java/info/ineighborhood/cardme/vcard/types/SortStringType.java
Java
agpl-3.0
5,126
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.therapies.homeandenvironmentalvisit.vo; /** * Linked to therapies.homeAndEnvironmentalVisit.EnvironmentalVisit business object (ID: 1019100096). */ public class EnvironmentalVisitRefVo extends ims.vo.ValueObjectRef implements ims.domain.IDomainGetter { private static final long serialVersionUID = 1L; public EnvironmentalVisitRefVo() { } public EnvironmentalVisitRefVo(Integer id, int version) { super(id, version); } public final boolean getID_EnvironmentalVisitIsNotNull() { return this.id != null; } public final Integer getID_EnvironmentalVisit() { return this.id; } public final void setID_EnvironmentalVisit(Integer value) { this.id = value; } public final int getVersion_EnvironmentalVisit() { return this.version; } public Object clone() { return new EnvironmentalVisitRefVo(this.id, this.version); } public final EnvironmentalVisitRefVo toEnvironmentalVisitRefVo() { if(this.id == null) return this; return new EnvironmentalVisitRefVo(this.id, this.version); } public boolean equals(Object obj) { if(!(obj instanceof EnvironmentalVisitRefVo)) return false; EnvironmentalVisitRefVo compareObj = (EnvironmentalVisitRefVo)obj; if(this.id != null && compareObj.getBoId() != null) return this.id.equals(compareObj.getBoId()); if(this.id != null && compareObj.getBoId() == null) return false; if(this.id == null && compareObj.getBoId() != null) return false; return super.equals(obj); } public int hashCode() { if(this.id != null) return this.id.intValue(); return super.hashCode(); } public boolean isValidated() { return true; } public String[] validate() { return null; } public String getBoClassName() { return "ims.therapies.homeandenvironmentalvisit.domain.objects.EnvironmentalVisit"; } public Class getDomainClass() { return ims.therapies.homeandenvironmentalvisit.domain.objects.EnvironmentalVisit.class; } public String getIItemText() { return toString(); } public String toString() { return this.getClass().toString() + " (ID: " + (this.id == null ? "null" : this.id.toString()) + ")"; } public int compareTo(Object obj) { if (obj == null) return -1; if (!(obj instanceof EnvironmentalVisitRefVo)) throw new ClassCastException("A EnvironmentalVisitRefVo object cannot be compared an Object of type " + obj.getClass().getName()); if (this.id == null) return 1; if (((EnvironmentalVisitRefVo)obj).getBoId() == null) return -1; return this.id.compareTo(((EnvironmentalVisitRefVo)obj).getBoId()); } // this method is not needed. It is here for compatibility purpose only. public int compareTo(Object obj, boolean caseInsensitive) { if(caseInsensitive); // this is to avoid Eclipse warning return compareTo(obj); } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ID_ENVIRONMENTALVISIT")) return getID_EnvironmentalVisit(); return super.getFieldValueByFieldName(fieldName); } }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/therapies/homeandenvironmentalvisit/vo/EnvironmentalVisitRefVo.java
Java
agpl-3.0
4,946
# Reed-Solomon [![Go Reference](https://pkg.go.dev/badge/github.com/klauspost/reedsolomon.svg)](https://pkg.go.dev/github.com/klauspost/reedsolomon) [![Build Status][3]][4] [3]: https://travis-ci.org/klauspost/reedsolomon.svg?branch=master [4]: https://travis-ci.org/klauspost/reedsolomon Reed-Solomon Erasure Coding in Go, with speeds exceeding 1GB/s/cpu core implemented in pure Go. This is a Go port of the [JavaReedSolomon](https://github.com/Backblaze/JavaReedSolomon) library released by [Backblaze](http://backblaze.com), with some additional optimizations. For an introduction on erasure coding, see the post on the [Backblaze blog](https://www.backblaze.com/blog/reed-solomon/). Package home: https://github.com/klauspost/reedsolomon Godoc: https://pkg.go.dev/github.com/klauspost/reedsolomon?tab=doc # Installation To get the package use the standard: ```bash go get -u github.com/klauspost/reedsolomon ``` Using Go modules recommended. # Changes ## 2021 * Add progressive shard encoding. * Wider AVX2 loops * Limit concurrency on AVX2, since we are likely memory bound. * Allow 0 parity shards. * Allow disabling inversion cache. * Faster AVX2 encoding. ## May 2020 * ARM64 optimizations, up to 2.5x faster. * Added [WithFastOneParityMatrix](https://pkg.go.dev/github.com/klauspost/reedsolomon?tab=doc#WithFastOneParityMatrix) for faster operation with 1 parity shard. * Much better performance when using a limited number of goroutines. * AVX512 is now using multiple cores. * Stream processing overhaul, big speedups in most cases. * AVX512 optimizations ## March 6, 2019 The pure Go implementation is about 30% faster. Minor tweaks to assembler implementations. ## February 8, 2019 AVX512 accelerated version added for Intel Skylake CPUs. This can give up to a 4x speed improvement as compared to AVX2. See [here](https://github.com/klauspost/reedsolomon#performance-on-avx512) for more details. ## December 18, 2018 Assembly code for ppc64le has been contributed, this boosts performance by about 10x on this platform. ## November 18, 2017 Added [WithAutoGoroutines](https://godoc.org/github.com/klauspost/reedsolomon#WithAutoGoroutines) which will attempt to calculate the optimal number of goroutines to use based on your expected shard size and detected CPU. ## October 1, 2017 * [Cauchy Matrix](https://godoc.org/github.com/klauspost/reedsolomon#WithCauchyMatrix) is now an option. Thanks to [templexxx](https://github.com/templexxx) for the basis of this. * Default maximum number of [goroutines](https://godoc.org/github.com/klauspost/reedsolomon#WithMaxGoroutines) has been increased for better multi-core scaling. * After several requests the Reconstruct and ReconstructData now slices of zero length but sufficient capacity to be used instead of allocating new memory. ## August 26, 2017 * The [`Encoder()`](https://godoc.org/github.com/klauspost/reedsolomon#Encoder) now contains an `Update` function contributed by [chenzhongtao](https://github.com/chenzhongtao). * [Frank Wessels](https://github.com/fwessels) kindly contributed ARM 64 bit assembly, which gives a huge performance boost on this platform. ## July 20, 2017 `ReconstructData` added to [`Encoder`](https://godoc.org/github.com/klauspost/reedsolomon#Encoder) interface. This can cause compatibility issues if you implement your own Encoder. A simple workaround can be added: ```Go func (e *YourEnc) ReconstructData(shards [][]byte) error { return ReconstructData(shards) } ``` You can of course also do your own implementation. The [`StreamEncoder`](https://godoc.org/github.com/klauspost/reedsolomon#StreamEncoder) handles this without modifying the interface. This is a good lesson on why returning interfaces is not a good design. # Usage This section assumes you know the basics of Reed-Solomon encoding. A good start is this [Backblaze blog post](https://www.backblaze.com/blog/reed-solomon/). This package performs the calculation of the parity sets. The usage is therefore relatively simple. First of all, you need to choose your distribution of data and parity shards. A 'good' distribution is very subjective, and will depend a lot on your usage scenario. A good starting point is above 5 and below 257 data shards (the maximum supported number), and the number of parity shards to be 2 or above, and below the number of data shards. To create an encoder with 10 data shards (where your data goes) and 3 parity shards (calculated): ```Go enc, err := reedsolomon.New(10, 3) ``` This encoder will work for all parity sets with this distribution of data and parity shards. The error will only be set if you specify 0 or negative values in any of the parameters, or if you specify more than 256 data shards. If you will primarily be using it with one shard size it is recommended to use [`WithAutoGoroutines(shardSize)`](https://pkg.go.dev/github.com/klauspost/reedsolomon?tab=doc#WithAutoGoroutines) as an additional parameter. This will attempt to calculate the optimal number of goroutines to use for the best speed. It is not required that all shards are this size. The you send and receive data is a simple slice of byte slices; `[][]byte`. In the example above, the top slice must have a length of 13. ```Go data := make([][]byte, 13) ``` You should then fill the 10 first slices with *equally sized* data, and create parity shards that will be populated with parity data. In this case we create the data in memory, but you could for instance also use [mmap](https://github.com/edsrzf/mmap-go) to map files. ```Go // Create all shards, size them at 50000 each for i := range input { data[i] := make([]byte, 50000) } // Fill some data into the data shards for i, in := range data[:10] { for j:= range in { in[j] = byte((i+j)&0xff) } } ``` To populate the parity shards, you simply call `Encode()` with your data. ```Go err = enc.Encode(data) ``` The only cases where you should get an error is, if the data shards aren't of equal size. The last 3 shards now contain parity data. You can verify this by calling `Verify()`: ```Go ok, err = enc.Verify(data) ``` The final (and important) part is to be able to reconstruct missing shards. For this to work, you need to know which parts of your data is missing. The encoder *does not know which parts are invalid*, so if data corruption is a likely scenario, you need to implement a hash check for each shard. If a byte has changed in your set, and you don't know which it is, there is no way to reconstruct the data set. To indicate missing data, you set the shard to nil before calling `Reconstruct()`: ```Go // Delete two data shards data[3] = nil data[7] = nil // Reconstruct the missing shards err := enc.Reconstruct(data) ``` The missing data and parity shards will be recreated. If more than 3 shards are missing, the reconstruction will fail. If you are only interested in the data shards (for reading purposes) you can call `ReconstructData()`: ```Go // Delete two data shards data[3] = nil data[7] = nil // Reconstruct just the missing data shards err := enc.ReconstructData(data) ``` So to sum up reconstruction: * The number of data/parity shards must match the numbers used for encoding. * The order of shards must be the same as used when encoding. * You may only supply data you know is valid. * Invalid shards should be set to nil. For complete examples of an encoder and decoder see the [examples folder](https://github.com/klauspost/reedsolomon/tree/master/examples). # Splitting/Joining Data You might have a large slice of data. To help you split this, there are some helper functions that can split and join a single byte slice. ```Go bigfile, _ := ioutil.Readfile("myfile.data") // Split the file split, err := enc.Split(bigfile) ``` This will split the file into the number of data shards set when creating the encoder and create empty parity shards. An important thing to note is that you have to *keep track of the exact input size*. If the size of the input isn't divisible by the number of data shards, extra zeros will be inserted in the last shard. To join a data set, use the `Join()` function, which will join the shards and write it to the `io.Writer` you supply: ```Go // Join a data set and write it to io.Discard. err = enc.Join(io.Discard, data, len(bigfile)) ``` # Progressive encoding It is possible to encode individual shards using EncodeIdx: ```Go // EncodeIdx will add parity for a single data shard. // Parity shards should start out as 0. The caller must zero them. // Data shards must be delivered exactly once. There is no check for this. // The parity shards will always be updated and the data shards will remain the same. EncodeIdx(dataShard []byte, idx int, parity [][]byte) error ``` This allows progressively encoding the parity by sending individual data shards. There is no requirement on shards being delivered in order, but when sent in order it allows encoding shards one at the time, effectively allowing the operation to be streaming. The result will be the same as encoding all shards at once. There is a minor speed penalty using this method, so send shards at once if they are available. ## Example ```Go func test() { // Create an encoder with 7 data and 3 parity slices. enc, _ := reedsolomon.New(7, 3) // This will be our output parity. parity := make([][]byte, 3) for i := range parity { parity[i] = make([]byte, 10000) } for i := 0; i < 7; i++ { // Send data shards one at the time. _ = enc.EncodeIdx(make([]byte, 10000), i, parity) } // parity now contains parity, as if all data was sent in one call. } ``` # Streaming/Merging It might seem like a limitation that all data should be in memory, but an important property is that *as long as the number of data/parity shards are the same, you can merge/split data sets*, and they will remain valid as a separate set. ```Go // Split the data set of 50000 elements into two of 25000 splitA := make([][]byte, 13) splitB := make([][]byte, 13) // Merge into a 100000 element set merged := make([][]byte, 13) for i := range data { splitA[i] = data[i][:25000] splitB[i] = data[i][25000:] // Concatenate it to itself merged[i] = append(make([]byte, 0, len(data[i])*2), data[i]...) merged[i] = append(merged[i], data[i]...) } // Each part should still verify as ok. ok, err := enc.Verify(splitA) if ok && err == nil { log.Println("splitA ok") } ok, err = enc.Verify(splitB) if ok && err == nil { log.Println("splitB ok") } ok, err = enc.Verify(merge) if ok && err == nil { log.Println("merge ok") } ``` This means that if you have a data set that may not fit into memory, you can split processing into smaller blocks. For the best throughput, don't use too small blocks. This also means that you can divide big input up into smaller blocks, and do reconstruction on parts of your data. This doesn't give the same flexibility of a higher number of data shards, but it will be much more performant. # Streaming API There has been added support for a streaming API, to help perform fully streaming operations, which enables you to do the same operations, but on streams. To use the stream API, use [`NewStream`](https://godoc.org/github.com/klauspost/reedsolomon#NewStream) function to create the encoding/decoding interfaces. You can use [`WithConcurrentStreams`](https://godoc.org/github.com/klauspost/reedsolomon#WithConcurrentStreams) to ready an interface that reads/writes concurrently from the streams. You can specify the size of each operation using [`WithStreamBlockSize`](https://godoc.org/github.com/klauspost/reedsolomon#WithStreamBlockSize). This will set the size of each read/write operation. Input is delivered as `[]io.Reader`, output as `[]io.Writer`, and functionality corresponds to the in-memory API. Each stream must supply the same amount of data, similar to how each slice must be similar size with the in-memory API. If an error occurs in relation to a stream, a [`StreamReadError`](https://godoc.org/github.com/klauspost/reedsolomon#StreamReadError) or [`StreamWriteError`](https://godoc.org/github.com/klauspost/reedsolomon#StreamWriteError) will help you determine which stream was the offender. There is no buffering or timeouts/retry specified. If you want to add that, you need to add it to the Reader/Writer. For complete examples of a streaming encoder and decoder see the [examples folder](https://github.com/klauspost/reedsolomon/tree/master/examples). # Advanced Options You can modify internal options which affects how jobs are split between and processed by goroutines. To create options, use the WithXXX functions. You can supply options to `New`, `NewStream`. If no Options are supplied, default options are used. Example of how to supply options: ```Go enc, err := reedsolomon.New(10, 3, WithMaxGoroutines(25)) ``` # Performance Performance depends mainly on the number of parity shards. In rough terms, doubling the number of parity shards will double the encoding time. Here are the throughput numbers with some different selections of data and parity shards. For reference each shard is 1MB random data, and 16 CPU cores are used for encoding. | Data | Parity | Go MB/s | SSSE3 MB/s | AVX2 MB/s | |------|--------|---------|------------|-----------| | 5 | 2 | 14287 | 66355 | 108755 | | 8 | 8 | 5569 | 34298 | 70516 | | 10 | 4 | 6766 | 48237 | 93875 | | 50 | 20 | 1540 | 12130 | 22090 | The throughput numbers here is the size of the encoded data and parity shards. If `runtime.GOMAXPROCS()` is set to a value higher than 1, the encoder will use multiple goroutines to perform the calculations in `Verify`, `Encode` and `Reconstruct`. Example of performance scaling on AMD Ryzen 3950X - 16 physical cores, 32 logical cores, AVX 2. The example uses 10 blocks with 1MB data each and 4 parity blocks. | Threads | Speed | |---------|------------| | 1 | 9979 MB/s | | 2 | 18870 MB/s | | 4 | 33697 MB/s | | 8 | 51531 MB/s | | 16 | 59204 MB/s | Benchmarking `Reconstruct()` followed by a `Verify()` (=`all`) versus just calling `ReconstructData()` (=`data`) gives the following result: ``` benchmark all MB/s data MB/s speedup BenchmarkReconstruct10x2x10000-8 2011.67 10530.10 5.23x BenchmarkReconstruct50x5x50000-8 4585.41 14301.60 3.12x BenchmarkReconstruct10x2x1M-8 8081.15 28216.41 3.49x BenchmarkReconstruct5x2x1M-8 5780.07 28015.37 4.85x BenchmarkReconstruct10x4x1M-8 4352.56 14367.61 3.30x BenchmarkReconstruct50x20x1M-8 1364.35 4189.79 3.07x BenchmarkReconstruct10x4x16M-8 1484.35 5779.53 3.89x ``` # Performance on AVX512 The performance on AVX512 has been accelerated for Intel CPUs. This gives speedups on a per-core basis typically up to 2x compared to AVX2 as can be seen in the following table: ``` [...] ``` This speedup has been achieved by computing multiple parity blocks in parallel as opposed to one after the other. In doing so it is possible to minimize the memory bandwidth required for loading all data shards. At the same time the calculations are performed in the 512-bit wide ZMM registers and the surplus of ZMM registers (32 in total) is used to keep more data around (most notably the matrix coefficients). # Performance on ARM64 NEON By exploiting NEON instructions the performance for ARM has been accelerated. Below are the performance numbers for a single core on an EC2 m6g.16xlarge (Graviton2) instance (Amazon Linux 2): ``` BenchmarkGalois128K-64 119562 10028 ns/op 13070.78 MB/s BenchmarkGalois1M-64 14380 83424 ns/op 12569.22 MB/s BenchmarkGaloisXor128K-64 96508 12432 ns/op 10543.29 MB/s BenchmarkGaloisXor1M-64 10000 100322 ns/op 10452.13 MB/s ``` # Performance on ppc64le The performance for ppc64le has been accelerated. This gives roughly a 10x performance improvement on this architecture as can been seen below: ``` benchmark old MB/s new MB/s speedup BenchmarkGalois128K-160 948.87 8878.85 9.36x BenchmarkGalois1M-160 968.85 9041.92 9.33x BenchmarkGaloisXor128K-160 862.02 7905.00 9.17x BenchmarkGaloisXor1M-160 784.60 6296.65 8.03x ``` # asm2plan9s [asm2plan9s](https://github.com/fwessels/asm2plan9s) is used for assembling the AVX2 instructions into their BYTE/WORD/LONG equivalents. # Links * [Backblaze Open Sources Reed-Solomon Erasure Coding Source Code](https://www.backblaze.com/blog/reed-solomon/). * [JavaReedSolomon](https://github.com/Backblaze/JavaReedSolomon). Compatible java library by Backblaze. * [ocaml-reed-solomon-erasure](https://gitlab.com/darrenldl/ocaml-reed-solomon-erasure). Compatible OCaml implementation. * [reedsolomon-c](https://github.com/jannson/reedsolomon-c). C version, compatible with output from this package. * [Reed-Solomon Erasure Coding in Haskell](https://github.com/NicolasT/reedsolomon). Haskell port of the package with similar performance. * [reed-solomon-erasure](https://github.com/darrenldl/reed-solomon-erasure). Compatible Rust implementation. * [go-erasure](https://github.com/somethingnew2-0/go-erasure). A similar library using cgo, slower in my tests. * [Screaming Fast Galois Field Arithmetic](http://www.snia.org/sites/default/files2/SDC2013/presentations/NewThinking/EthanMiller_Screaming_Fast_Galois_Field%20Arithmetic_SIMD%20Instructions.pdf). Basis for SSE3 optimizations. # License This code, as the original [JavaReedSolomon](https://github.com/Backblaze/JavaReedSolomon) is published under an MIT license. See LICENSE file for more information.
admpub/nging
vendor/github.com/klauspost/reedsolomon/README.md
Markdown
agpl-3.0
18,206
#include "m3u8_builder.h" #include "hls_muxer.h" #include "../common.h" // macros #define MAX_SEGMENT_COUNT (10 * 1024) // more than 1 day when using 10 sec segments #define M3U8_HEADER_PART1 "#EXTM3U\n#EXT-X-TARGETDURATION:%d\n#EXT-X-ALLOW-CACHE:YES\n#EXT-X-PLAYLIST-TYPE:VOD\n" #define M3U8_HEADER_PART2 "#EXT-X-VERSION:%d\n#EXT-X-MEDIA-SEQUENCE:1\n" // constants static const u_char m3u8_header[] = "#EXTM3U\n"; static const u_char m3u8_footer[] = "#EXT-X-ENDLIST\n"; static const char m3u8_stream_inf_video[] = "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=%uD,RESOLUTION=%uDx%uD,CODECS=\"%V"; static const char m3u8_stream_inf_audio[] = "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=%uD,CODECS=\"%V"; static const u_char m3u8_stream_inf_suffix[] = "\"\n"; static const char byte_range_tag_format[] = "#EXT-X-BYTERANGE:%uD@%uD\n"; static const u_char m3u8_url_suffix[] = ".m3u8\n"; // typedefs typedef struct { u_char* p; vod_str_t required_tracks; vod_str_t* base_url; vod_str_t* segment_file_name_prefix; } write_segment_context_t; static int m3u8_builder_get_int_print_len(int n) { int res = 1; while (n >= 10) { res++; n /= 10; } return res; } // Notes: // 1. not using vod_sprintf in order to avoid the use of floats // 2. scale must be a power of 10 static u_char* m3u8_builder_format_double(u_char* p, uint32_t n, uint32_t scale) { int cur_digit; int int_n = n / scale; int fraction = n % scale; p = vod_sprintf(p, "%d", int_n); if (scale == 1) { return p; } *p++ = '.'; for (;;) { scale /= 10; if (scale == 0) { break; } cur_digit = fraction / scale; *p++ = cur_digit + '0'; fraction -= cur_digit * scale; } return p; } static vod_status_t m3u8_builder_build_required_tracks_string( request_context_t* request_context, bool_t include_file_index, mpeg_metadata_t* mpeg_metadata, vod_str_t* required_tracks) { mpeg_stream_metadata_t* cur_stream; u_char* p; size_t result_size; result_size = mpeg_metadata->streams.nelts * (sizeof("-v") - 1 + m3u8_builder_get_int_print_len(mpeg_metadata->max_track_index + 1)); if (include_file_index) { result_size += sizeof("-f") - 1 + m3u8_builder_get_int_print_len(mpeg_metadata->first_stream->file_info.file_index + 1); } p = vod_alloc(request_context->pool, result_size + 1); if (p == NULL) { vod_log_debug0(VOD_LOG_DEBUG_LEVEL, request_context->log, 0, "m3u8_builder_build_required_tracks_string: vod_alloc failed"); return VOD_ALLOC_FAILED; } required_tracks->data = p; if (include_file_index) { p = vod_sprintf(p, "-f%uD", mpeg_metadata->first_stream->file_info.file_index + 1); } for (cur_stream = mpeg_metadata->first_stream; cur_stream < mpeg_metadata->last_stream; cur_stream++) { *p++ = '-'; switch (cur_stream->media_info.media_type) { case MEDIA_TYPE_VIDEO: *p++ = 'v'; break; case MEDIA_TYPE_AUDIO: *p++ = 'a'; break; default: continue; } p = vod_sprintf(p, "%uD", cur_stream->track_index + 1); } required_tracks->len = p - required_tracks->data; if (required_tracks->len > result_size) { vod_log_error(VOD_LOG_ERR, request_context->log, 0, "m3u8_builder_build_required_tracks_string: result length %uz exceeded allocated length %uz", required_tracks->len, result_size); return VOD_UNEXPECTED; } return VOD_OK; } static u_char* m3u8_builder_append_segment_name( u_char* p, vod_str_t* base_url, vod_str_t* segment_file_name_prefix, uint32_t segment_index, vod_str_t* required_tracks) { p = vod_copy(p, base_url->data, base_url->len); p = vod_copy(p, segment_file_name_prefix->data, segment_file_name_prefix->len); *p++ = '-'; p = vod_sprintf(p, "%uD", segment_index + 1); p = vod_copy(p, required_tracks->data, required_tracks->len); p = vod_copy(p, ".ts\n", sizeof(".ts\n") - 1); return p; } static u_char* m3u8_builder_append_extinf_tag(u_char* p, uint32_t duration, uint32_t scale) { p = vod_copy(p, "#EXTINF:", sizeof("#EXTINF:") - 1); p = m3u8_builder_format_double(p, duration, scale); *p++ = ','; *p++ = '\n'; return p; } static void m3u8_builder_append_iframe_string(void* context, uint32_t segment_index, uint32_t frame_duration, uint32_t frame_start, uint32_t frame_size) { write_segment_context_t* ctx = (write_segment_context_t*)context; ctx->p = m3u8_builder_append_extinf_tag(ctx->p, frame_duration, 1000); ctx->p = vod_sprintf(ctx->p, byte_range_tag_format, frame_size, frame_start); ctx->p = m3u8_builder_append_segment_name( ctx->p, ctx->base_url, ctx->segment_file_name_prefix, segment_index, &ctx->required_tracks); } vod_status_t m3u8_builder_build_iframe_playlist( request_context_t* request_context, m3u8_config_t* conf, vod_str_t* base_url, bool_t include_file_index, segmenter_conf_t* segmenter_conf, mpeg_metadata_t* mpeg_metadata, vod_str_t* result) { write_segment_context_t ctx; size_t iframe_length; size_t result_size; hls_muxer_state_t muxer_state; bool_t simulation_supported; vod_status_t rc; uint32_t segment_count; // initialize the muxer rc = hls_muxer_init(&muxer_state, request_context, 0, mpeg_metadata, NULL, NULL, NULL, &simulation_supported); if (rc != VOD_OK) { return rc; } if (!simulation_supported) { vod_log_error(VOD_LOG_ERR, request_context->log, 0, "m3u8_builder_build_iframe_playlist: simulation not supported for this file, cant create iframe playlist"); return VOD_BAD_REQUEST; } // build the required tracks string rc = m3u8_builder_build_required_tracks_string( request_context, include_file_index, mpeg_metadata, &ctx.required_tracks); if (rc != VOD_OK) { return rc; } // calculate the required buffer length segment_count = segmenter_conf->get_segment_count(segmenter_conf, mpeg_metadata->duration_millis); if (segment_count == INVALID_SEGMENT_COUNT) { vod_log_error(VOD_LOG_ERR, request_context->log, 0, "m3u8_builder_build_iframe_playlist: segment count is invalid"); return VOD_BAD_DATA; } iframe_length = sizeof("#EXTINF:.000,\n") - 1 + m3u8_builder_get_int_print_len(DIV_CEIL(mpeg_metadata->duration_millis, 1000)) + sizeof(byte_range_tag_format) + VOD_INT32_LEN + m3u8_builder_get_int_print_len(MAX_FRAME_SIZE) - (sizeof("%uD%uD") - 1) + base_url->len + conf->segment_file_name_prefix.len + 1 + m3u8_builder_get_int_print_len(segment_count) + ctx.required_tracks.len + sizeof(".ts\n") - 1; result_size = conf->iframes_m3u8_header_len + iframe_length * mpeg_metadata->video_key_frame_count + sizeof(m3u8_footer); // allocate the buffer result->data = vod_alloc(request_context->pool, result_size); if (result->data == NULL) { vod_log_debug0(VOD_LOG_DEBUG_LEVEL, request_context->log, 0, "m3u8_builder_build_iframe_playlist: vod_alloc failed"); return VOD_ALLOC_FAILED; } // fill out the buffer ctx.p = vod_copy(result->data, conf->iframes_m3u8_header, conf->iframes_m3u8_header_len); if (mpeg_metadata->video_key_frame_count > 0) { ctx.base_url = base_url; ctx.segment_file_name_prefix = &conf->segment_file_name_prefix; rc = hls_muxer_simulate_get_iframes(&muxer_state, segmenter_conf, mpeg_metadata, m3u8_builder_append_iframe_string, &ctx); if (rc != VOD_OK) { return rc; } } ctx.p = vod_copy(ctx.p, m3u8_footer, sizeof(m3u8_footer) - 1); result->len = ctx.p - result->data; if (result->len > result_size) { vod_log_error(VOD_LOG_ERR, request_context->log, 0, "m3u8_builder_build_iframe_playlist: result length %uz exceeded allocated length %uz", result->len, result_size); return VOD_UNEXPECTED; } return VOD_OK; } vod_status_t m3u8_builder_build_index_playlist( request_context_t* request_context, m3u8_config_t* conf, vod_str_t* base_url, vod_str_t* segments_base_url, bool_t include_file_index, bool_t encryption_enabled, segmenter_conf_t* segmenter_conf, mpeg_metadata_t* mpeg_metadata, vod_str_t* result) { segment_durations_t segment_durations; segment_duration_item_t* cur_item; segment_duration_item_t* last_item; vod_str_t extinf; uint32_t segment_index; uint32_t last_segment_index; vod_str_t required_tracks; uint32_t scale; size_t segment_length; size_t result_size; vod_status_t rc; u_char* p; // build the required tracks string rc = m3u8_builder_build_required_tracks_string( request_context, include_file_index, mpeg_metadata, &required_tracks); if (rc != VOD_OK) { return rc; } // get the segment durations rc = segmenter_conf->get_segment_durations( request_context, segmenter_conf, mpeg_metadata->longest_stream, MEDIA_TYPE_COUNT, &segment_durations); if (rc != VOD_OK) { return rc; } // get the required buffer length segment_length = sizeof("#EXTINF:.000,\n") - 1 + m3u8_builder_get_int_print_len(DIV_CEIL(mpeg_metadata->duration_millis, 1000)) + segments_base_url->len + conf->segment_file_name_prefix.len + 1 + m3u8_builder_get_int_print_len(segment_durations.segment_count) + required_tracks.len + sizeof(".ts\n") - 1; result_size = sizeof(M3U8_HEADER_PART1) + VOD_INT64_LEN + sizeof(M3U8_HEADER_PART2) + VOD_INT64_LEN + segment_length * segment_durations.segment_count + sizeof(m3u8_footer); if (encryption_enabled) { result_size += sizeof(encryption_key_tag_prefix) - 1 + base_url->len + conf->encryption_key_file_name.len + sizeof("-f") - 1 + VOD_INT32_LEN + sizeof(encryption_key_tag_postfix) - 1; } // allocate the buffer result->data = vod_alloc(request_context->pool, result_size); if (result->data == NULL) { vod_log_debug0(VOD_LOG_DEBUG_LEVEL, request_context->log, 0, "m3u8_builder_build_index_playlist: vod_alloc failed"); return VOD_ALLOC_FAILED; } // write the header p = vod_sprintf( result->data, M3U8_HEADER_PART1, (segmenter_conf->max_segment_duration + 500) / 1000); if (encryption_enabled) { p = vod_copy(p, encryption_key_tag_prefix, sizeof(encryption_key_tag_prefix) - 1); p = vod_copy(p, base_url->data, base_url->len); p = vod_copy(p, conf->encryption_key_file_name.data, conf->encryption_key_file_name.len); if (include_file_index) { p = vod_sprintf(p, "-f%uD", mpeg_metadata->first_stream->file_info.file_index + 1); } p = vod_copy(p, encryption_key_tag_postfix, sizeof(encryption_key_tag_postfix)-1); } p = vod_sprintf( p, M3U8_HEADER_PART2, conf->m3u8_version); // write the segments scale = conf->m3u8_version >= 3 ? 1000 : 1; last_item = segment_durations.items + segment_durations.item_count; for (cur_item = segment_durations.items; cur_item < last_item; cur_item++) { segment_index = cur_item->segment_index; last_segment_index = segment_index + cur_item->repeat_count; // write the first segment extinf.data = p; p = m3u8_builder_append_extinf_tag(p, rescale_time(cur_item->duration, segment_durations.timescale, scale), scale); extinf.len = p - extinf.data; p = m3u8_builder_append_segment_name(p, segments_base_url, &conf->segment_file_name_prefix, segment_index, &required_tracks); segment_index++; // write any additional segments for (; segment_index < last_segment_index; segment_index++) { p = vod_copy(p, extinf.data, extinf.len); p = m3u8_builder_append_segment_name(p, segments_base_url, &conf->segment_file_name_prefix, segment_index, &required_tracks); } } // write the footer p = vod_copy(p, m3u8_footer, sizeof(m3u8_footer) - 1); result->len = p - result->data; if (result->len > result_size) { vod_log_error(VOD_LOG_ERR, request_context->log, 0, "m3u8_builder_build_index_playlist: result length %uz exceeded allocated length %uz", result->len, result_size); return VOD_UNEXPECTED; } return VOD_OK; } vod_status_t m3u8_builder_build_master_playlist( request_context_t* request_context, m3u8_config_t* conf, vod_str_t* base_url, bool_t include_file_index, mpeg_metadata_t* mpeg_metadata, vod_str_t* result) { WALK_STREAMS_BY_FILES_VARS(cur_file_streams); mpeg_stream_metadata_t* stream; media_info_t* video; media_info_t* audio = NULL; uint32_t bitrate; u_char* p; size_t max_video_stream_inf; size_t max_audio_stream_inf; size_t result_size; // calculate the result size max_video_stream_inf = sizeof(m3u8_stream_inf_video) - 1 + 3 * VOD_INT32_LEN + MAX_CODEC_NAME_SIZE + MAX_CODEC_NAME_SIZE + 1 + sizeof(m3u8_stream_inf_suffix) - 1; max_audio_stream_inf = sizeof(m3u8_stream_inf_audio) + VOD_INT32_LEN + MAX_CODEC_NAME_SIZE + sizeof(m3u8_stream_inf_suffix) - 1; result_size = sizeof(m3u8_header) + mpeg_metadata->stream_count[MEDIA_TYPE_VIDEO] * max_video_stream_inf + mpeg_metadata->stream_count[MEDIA_TYPE_AUDIO] * max_audio_stream_inf; WALK_STREAMS_BY_FILES_START(cur_file_streams, mpeg_metadata) stream = (cur_file_streams[MEDIA_TYPE_VIDEO] != NULL ? cur_file_streams[MEDIA_TYPE_VIDEO] : cur_file_streams[MEDIA_TYPE_AUDIO]); if (base_url->len != 0) { result_size += base_url->len; result_size += stream->file_info.uri.len + 1; } result_size += conf->index_file_name_prefix.len; result_size += sizeof("-f-v-a") - 1 + VOD_INT32_LEN * 3; result_size += sizeof(m3u8_url_suffix) - 1; WALK_STREAMS_BY_FILES_END(cur_file_streams, mpeg_metadata) // allocate the buffer result->data = vod_alloc(request_context->pool, result_size); if (result->data == NULL) { vod_log_debug0(VOD_LOG_DEBUG_LEVEL, request_context->log, 0, "m3u8_builder_build_master_playlist: vod_alloc failed (2)"); return VOD_ALLOC_FAILED; } // write the header p = vod_copy(result->data, m3u8_header, sizeof(m3u8_header) - 1); // write the streams WALK_STREAMS_BY_FILES_START(cur_file_streams, mpeg_metadata) // write the stream information if (cur_file_streams[MEDIA_TYPE_VIDEO] != NULL) { stream = cur_file_streams[MEDIA_TYPE_VIDEO]; video = &stream->media_info; bitrate = video->bitrate; if (cur_file_streams[MEDIA_TYPE_AUDIO] != NULL) { audio = &cur_file_streams[MEDIA_TYPE_AUDIO]->media_info; bitrate += audio->bitrate; } p = vod_sprintf(p, m3u8_stream_inf_video, bitrate, (uint32_t)video->u.video.width, (uint32_t)video->u.video.height, &video->codec_name); if (cur_file_streams[MEDIA_TYPE_AUDIO] != NULL) { *p++ = ','; p = vod_copy(p, audio->codec_name.data, audio->codec_name.len); } } else { stream = cur_file_streams[MEDIA_TYPE_AUDIO]; audio = &stream->media_info; p = vod_sprintf(p, m3u8_stream_inf_audio, audio->bitrate, &audio->codec_name); } p = vod_copy(p, m3u8_stream_inf_suffix, sizeof(m3u8_stream_inf_suffix) - 1); // write the stream url if (base_url->len != 0) { // absolute url only p = vod_copy(p, base_url->data, base_url->len); p = vod_copy(p, stream->file_info.uri.data, stream->file_info.uri.len); *p++ = '/'; } p = vod_copy(p, conf->index_file_name_prefix.data, conf->index_file_name_prefix.len); if (base_url->len == 0 && include_file_index) { p = vod_sprintf(p, "-f%uD", stream->file_info.file_index + 1); } if (cur_file_streams[MEDIA_TYPE_VIDEO] != NULL) { p = vod_sprintf(p, "-v%uD", cur_file_streams[MEDIA_TYPE_VIDEO]->track_index + 1); } if (cur_file_streams[MEDIA_TYPE_AUDIO] != NULL) { p = vod_sprintf(p, "-a%uD", cur_file_streams[MEDIA_TYPE_AUDIO]->track_index + 1); } p = vod_copy(p, m3u8_url_suffix, sizeof(m3u8_url_suffix) - 1); WALK_STREAMS_BY_FILES_END(cur_file_streams, mpeg_metadata) result->len = p - result->data; if (result->len > result_size) { vod_log_error(VOD_LOG_ERR, request_context->log, 0, "m3u8_builder_build_master_playlist: result length %uz exceeded allocated length %uz", result->len, result_size); return VOD_UNEXPECTED; } return VOD_OK; } void m3u8_builder_init_config( m3u8_config_t* conf, uint32_t max_segment_duration) { conf->m3u8_version = 3; conf->iframes_m3u8_header_len = vod_snprintf( conf->iframes_m3u8_header, sizeof(conf->iframes_m3u8_header) - 1, iframes_m3u8_header_format, DIV_CEIL(max_segment_duration, 1000)) - conf->iframes_m3u8_header; }
jessp01/nginx-vod-module
vod/hls/m3u8_builder.c
C
agpl-3.0
15,990
"""This module implements functions for querying properties of the operating system or for the specific process the code is running in. """ import os import sys import re import multiprocessing import subprocess try: from subprocess import check_output as _execute_program except ImportError: def _execute_program(*popenargs, **kwargs): # Replicates check_output() implementation from Python 2.7+. # Should only be used for Python 2.6. if 'stdout' in kwargs: raise ValueError( 'stdout argument not allowed, it will be overridden.') process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise subprocess.CalledProcessError(retcode, cmd, output=output) return output try: import resource except ImportError: pass def logical_processor_count(): """Returns the number of logical processors in the system. """ # The multiprocessing module provides support for Windows, # BSD systems (including MacOS X) and systems which support # the POSIX API for querying the number of CPUs. try: return multiprocessing.cpu_count() except NotImplementedError: pass # For Jython, we need to query the Java runtime environment. try: from java.lang import Runtime runtime = Runtime.getRuntime() res = runtime.availableProcessors() if res > 0: return res except ImportError: pass # Assuming that Solaris will support POSIX API for querying # the number of CPUs. Just in case though, work it out by # looking at the devices corresponding to the available CPUs. try: pseudoDevices = os.listdir('/devices/pseudo/') expr = re.compile('^cpuid@[0-9]+$') res = 0 for pd in pseudoDevices: if expr.match(pd) != None: res += 1 if res > 0: return res except OSError: pass # Fallback to assuming only a single CPU. return 1 def _linux_physical_processor_count(filename=None): # For Linux we can use information from '/proc/cpuinfo. # A line in the file that starts with 'processor' marks the # beginning of a section. # # Multi-core processors will have a 'processor' section for each # core. There is usually a 'physical id' field and a 'cpu cores' # field as well. The 'physical id' field in each 'processor' # section will have the same value for all cores in a physical # processor. The 'cpu cores' field for each 'processor' section will # provide the total number of cores for that physical processor. # The 'cpu cores' field is duplicated, so only remember the last filename = filename or '/proc/cpuinfo' processors = 0 physical_processors = {} try: with open(filename, 'r') as fp: processor_id = None cores = None for line in fp: try: key, value = line.split(':') key = key.lower().strip() value = value.strip() except ValueError: continue if key == 'processor': processors += 1 # If this is not the first processor section # and prior sections specified a physical ID # and number of cores, we want to remember # the number of cores corresponding to that # physical core. Note that we may see details # for the same phyiscal ID more than one and # thus we only end up remember the number of # cores from the last one we see. if cores and processor_id: physical_processors[processor_id] = cores processor_id = None cores = None elif key == 'physical id': processor_id = value elif key == 'cpu cores': cores = int(value) # When we have reached the end of the file, we now need to save # away the number of cores for the physical ID we saw in the # last processor section. if cores and processor_id: physical_processors[processor_id] = cores except Exception: pass num_physical_processors = len(physical_processors) or (processors if processors == 1 else None) num_physical_cores = sum(physical_processors.values()) or (processors if processors == 1 else None) return (num_physical_processors, num_physical_cores) def _darwin_physical_processor_count(): # For MacOS X we can use sysctl. physical_processor_cmd = ['/usr/sbin/sysctl', '-n', 'hw.packages'] try: num_physical_processors = int(_execute_program(physical_processor_cmd, stderr=subprocess.PIPE)) except (subprocess.CalledProcessError, ValueError): num_physical_processors = None physical_core_cmd = ['/usr/sbin/sysctl', '-n', 'hw.physicalcpu'] try: num_physical_cores = int(_execute_program(physical_core_cmd, stderr=subprocess.PIPE)) except (subprocess.CalledProcessError, ValueError): num_physical_cores = None return (num_physical_processors, num_physical_cores) def physical_processor_count(): """Returns the number of physical processors and the number of physical cores in the system as a tuple. One or both values may be None, if a value cannot be determined. """ if sys.platform.startswith('linux'): return _linux_physical_processor_count() elif sys.platform == 'darwin': return _darwin_physical_processor_count() return (None, None) def _linux_total_physical_memory(filename=None): # For Linux we can use information from /proc/meminfo. Although the # units is given in the file, it is always in kilobytes so we do not # need to accomodate any other unit types beside 'kB'. filename = filename or '/proc/meminfo' try: parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB') with open(filename, 'r') as fp: for line in fp.readlines(): match = parser.match(line) if not match: continue key, value = match.groups(['key', 'value']) if key == 'MemTotal': memory_bytes = float(value) * 1024 return memory_bytes / (1024*1024) except Exception: pass def _darwin_total_physical_memory(): # For MacOS X we can use sysctl. The value queried from sysctl is # always bytes. command = ['/usr/sbin/sysctl', '-n', 'hw.memsize'] try: return float(_execute_program(command, stderr=subprocess.PIPE)) / (1024*1024) except subprocess.CalledProcessError: pass except ValueError: pass def total_physical_memory(): """Returns the total physical memory available in the system. Returns None if the value cannot be calculated. """ if sys.platform.startswith('linux'): return _linux_total_physical_memory() elif sys.platform == 'darwin': return _darwin_total_physical_memory() def _linux_physical_memory_used(filename=None): # For Linux we can use information from the proc filesystem. We use # '/proc/statm' as it easier to parse than '/proc/status' file. The # value queried from the file is always in bytes. # # /proc/[number]/statm # Provides information about memory usage, measured # in pages. The columns are: # # size total program size # (same as VmSize in /proc/[number]/status) # resident resident set size # (same as VmRSS in /proc/[number]/status) # share shared pages (from shared mappings) # text text (code) # lib library (unused in Linux 2.6) # data data + stack # dt dirty pages (unused in Linux 2.6) filename = filename or '/proc/%d/statm' % os.getpid() try: with open(filename, 'r') as fp: rss_pages = float(fp.read().split()[1]) memory_bytes = rss_pages * resource.getpagesize() return memory_bytes / (1024*1024) except Exception: return 0 def physical_memory_used(): """Returns the amount of physical memory used in MBs. Returns 0 if the value cannot be calculated. """ # A value of 0 is returned by default rather than None as this value # can be used in metrics. As such has traditionally always been # returned as an integer to avoid checks at the point is used. if sys.platform.startswith('linux'): return _linux_physical_memory_used() # For all other platforms try using getrusage() if we have the # resource module available. The units returned can differ based on # platform. Assume 1024 byte blocks as default. Some platforms such # as Solaris will report zero for 'ru_maxrss', so we skip those. try: rusage = resource.getrusage(resource.RUSAGE_SELF) except NameError: pass else: if sys.platform == 'darwin': # On MacOS X, despite the manual page saying the # value is in kilobytes, it is actually in bytes. memory_bytes = float(rusage.ru_maxrss) return memory_bytes / (1024*1024) elif rusage.ru_maxrss > 0: memory_kbytes = float(rusage.ru_maxrss) return memory_kbytes / 1024 return 0
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/newrelic-2.46.0.37/newrelic/common/system_info.py
Python
agpl-3.0
10,108
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.vo; public class OrderSetListSearchCriteriaVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public OrderSetListSearchCriteriaVo() { } public OrderSetListSearchCriteriaVo(ims.ocrr.vo.beans.OrderSetListSearchCriteriaVoBean bean) { this.name = bean.getName(); this.status = bean.getStatus() == null ? null : ims.core.vo.lookups.PreActiveActiveInactiveStatus.buildLookup(bean.getStatus()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.beans.OrderSetListSearchCriteriaVoBean bean) { this.name = bean.getName(); this.status = bean.getStatus() == null ? null : ims.core.vo.lookups.PreActiveActiveInactiveStatus.buildLookup(bean.getStatus()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.ocrr.vo.beans.OrderSetListSearchCriteriaVoBean bean = null; if(map != null) bean = (ims.ocrr.vo.beans.OrderSetListSearchCriteriaVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.ocrr.vo.beans.OrderSetListSearchCriteriaVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public boolean getNameIsNotNull() { return this.name != null; } public String getName() { return this.name; } public static int getNameMaxLength() { return 255; } public void setName(String value) { this.isValidated = false; this.name = value; } public boolean getStatusIsNotNull() { return this.status != null; } public ims.core.vo.lookups.PreActiveActiveInactiveStatus getStatus() { return this.status; } public void setStatus(ims.core.vo.lookups.PreActiveActiveInactiveStatus value) { this.isValidated = false; this.status = value; } public final String getIItemText() { return toString(); } public final Integer getBoId() { return null; } public final String getBoClassName() { return null; } public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof OrderSetListSearchCriteriaVo)) return false; OrderSetListSearchCriteriaVo compareObj = (OrderSetListSearchCriteriaVo)obj; if(this.getName() == null && compareObj.getName() != null) return false; if(this.getName() != null && compareObj.getName() == null) return false; if(this.getName() != null && compareObj.getName() != null) return this.getName().equals(compareObj.getName()); return super.equals(obj); } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; OrderSetListSearchCriteriaVo clone = new OrderSetListSearchCriteriaVo(); clone.name = this.name; if(this.status == null) clone.status = null; else clone.status = (ims.core.vo.lookups.PreActiveActiveInactiveStatus)this.status.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(OrderSetListSearchCriteriaVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A OrderSetListSearchCriteriaVo object cannot be compared an Object of type " + obj.getClass().getName()); } OrderSetListSearchCriteriaVo compareObj = (OrderSetListSearchCriteriaVo)obj; int retVal = 0; if (retVal == 0) { if(this.getName() == null && compareObj.getName() != null) return -1; if(this.getName() != null && compareObj.getName() == null) return 1; if(this.getName() != null && compareObj.getName() != null) { if(caseInsensitive) retVal = this.getName().toLowerCase().compareTo(compareObj.getName().toLowerCase()); else retVal = this.getName().compareTo(compareObj.getName()); } } if (retVal == 0) { if(this.getStatus() == null && compareObj.getStatus() != null) return -1; if(this.getStatus() != null && compareObj.getStatus() == null) return 1; if(this.getStatus() != null && compareObj.getStatus() != null) retVal = this.getStatus().compareTo(compareObj.getStatus()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.name != null) count++; if(this.status != null) count++; return count; } public int countValueObjectFields() { return 2; } protected String name; protected ims.core.vo.lookups.PreActiveActiveInactiveStatus status; private boolean isValidated = false; private boolean isBusy = false; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/OrderSetListSearchCriteriaVo.java
Java
agpl-3.0
8,075
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>A Pelican Blog - foobar</title> <link rel="stylesheet" href="/theme/css/main.css" /> <link href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="A Pelican Blog Atom Feed" /> </head> <body id="index" class="home"> <header id="banner" class="body"> <h1><a href="/">A Pelican Blog </a></h1> <nav><ul> <li><a href="/tag/oh.html">Oh Oh Oh</a></li> <li><a href="/override/">Override url/save_as</a></li> <li><a href="/pages/this-is-a-test-page.html">This is a test page</a></li> <li><a href="/category/bar.html">bar</a></li> <li><a href="/category/cat1.html">cat1</a></li> <li><a href="/category/misc.html">misc</a></li> <li><a href="/category/yeah.html">yeah</a></li> </ul></nav> </header><!-- /#banner --> <aside id="featured" class="body"> <article> <h1 class="entry-title"><a href="/this-is-a-super-article.html">This is a super article !</a></h1> <footer class="post-info"> <abbr class="published" title="2010-12-02T10:14:00+00:00"> Published: Thu 02 December 2010 </abbr> <br /> <abbr class="modified" title="2013-11-17T23:29:00+00:00"> Updated: Sun 17 November 2013 </abbr> <address class="vcard author"> By <a class="url fn" href="/author/alexis-metaireau.html">Alexis Métaireau</a> </address> <p>In <a href="/category/yeah.html">yeah</a>.</p> <p>tags: <a href="/tag/foo.html">foo</a> <a href="/tag/bar.html">bar</a> <a href="/tag/foobar.html">foobar</a> </p> </footer><!-- /.post-info --><p>Some content here !</p> <div class="section" id="this-is-a-simple-title"> <h2>This is a simple title</h2> <p>And here comes the cool <a class="reference external" href="http://books.couchdb.org/relax/design-documents/views">stuff</a>.</p> <img alt="alternate text" src="/pictures/Sushi.jpg" style="width: 600px; height: 450px;" /> <img alt="alternate text" src="/pictures/Sushi_Macro.jpg" style="width: 600px; height: 450px;" /> <pre class="literal-block"> &gt;&gt;&gt; from ipdb import set_trace &gt;&gt;&gt; set_trace() </pre> <p>→ And now try with some utf8 hell: ééé</p> </div> </article> </aside><!-- /#featured --> <section id="extras" class="body"> <div class="social"> <h2>social</h2> <ul> <li><a href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate">atom feed</a></li> </ul> </div><!-- /.social --> </section><!-- /#extras --> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> Proudly powered by <a href="http://getpelican.com/">Pelican</a>, which takes great advantage of <a href="http://python.org">Python</a>. </address><!-- /#about --> <p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!</p> </footer><!-- /#contentinfo --> </body> </html>
talha131/pelican
pelican/tests/output/basic/tag/foobar.html
HTML
agpl-3.0
3,457
/* * Copyright (C) 2000 - 2015 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.components.webpages.control; import org.silverpeas.core.contribution.content.form.DataRecord; import org.silverpeas.core.contribution.content.form.Form; import org.silverpeas.core.contribution.content.form.FormException; import org.silverpeas.core.contribution.content.form.PagesContext; import org.silverpeas.core.contribution.content.form.RecordSet; import org.silverpeas.core.contribution.template.publication.PublicationTemplate; import org.silverpeas.core.contribution.template.publication.PublicationTemplateException; import org.silverpeas.core.contribution.template.publication.PublicationTemplateManager; import org.silverpeas.core.subscription.SubscriptionService; import org.silverpeas.core.subscription.SubscriptionServiceProvider; import org.silverpeas.core.subscription.service.ComponentSubscription; import org.silverpeas.core.web.mvc.controller.AbstractComponentSessionController; import org.silverpeas.core.web.mvc.controller.ComponentContext; import org.silverpeas.core.web.mvc.controller.MainSessionController; import org.silverpeas.core.admin.component.model.ComponentInstLight; import org.silverpeas.core.node.model.NodePK; import org.apache.commons.fileupload.FileItem; import org.silverpeas.components.webpages.model.WebPagesException; import org.silverpeas.components.webpages.notification.WebPagesUserNotifier; import org.silverpeas.core.index.indexing.model.FullIndexEntry; import org.silverpeas.core.index.indexing.model.IndexEngineProxy; import org.silverpeas.core.silvertrace.SilverTrace; import org.silverpeas.core.util.StringUtil; import org.silverpeas.core.exception.SilverpeasException; import org.silverpeas.core.i18n.I18NHelper; import org.silverpeas.core.contribution.content.wysiwyg.service.WysiwygController; import java.util.Date; import java.util.List; public class WebPagesSessionController extends AbstractComponentSessionController { String usedTemplate = null; /** * Standard Session Controller Constructor * @param mainSessionCtrl The user's profile * @param componentContext The component's profile * @see */ public WebPagesSessionController(MainSessionController mainSessionCtrl, ComponentContext componentContext) { super(mainSessionCtrl, componentContext, "org.silverpeas.webpages.multilang.webPagesBundle", "org.silverpeas.webpages.settings.webPagesIcons"); registerXMLForm(); } /** * Méthode récupérant le role le plus élevé du user * @return le role */ public String getProfile() { String[] profiles = getUserRoles(); String flag = "user"; for (String profile : profiles) { // if publisher, return it, we won't find a better profile if (profile.equals("publisher")) { return profile; } } return flag; } /** * @return vrai s'il existe un fichier wysiwyg pour l'instance de composant */ public boolean haveGotWysiwygNotEmpty() { return WysiwygController.haveGotWysiwyg(getComponentId(), getComponentId(), I18NHelper.defaultLanguage); } public synchronized void removeSubscription() { getSubscribeService().unsubscribe(new ComponentSubscription(getUserId(), getComponentId())); } public synchronized void addSubscription() { if (isSubscriber()) { return; } getSubscribeService().subscribe(new ComponentSubscription(getUserId(), getComponentId())); } public boolean isSubscriber() { return getSubscribeService().existsSubscription( new ComponentSubscription(getUserId(), getComponentId())); } private NodePK getNodePK() { return new NodePK(NodePK.ROOT_NODE_ID, getSpaceId(), getComponentId()); } private SubscriptionService getSubscribeService() { return SubscriptionServiceProvider.getSubscribeService(); } /** * Return boolean if subscription is used for this instance * @return boolean */ public boolean isSubscriptionUsed() { return "yes".equalsIgnoreCase(getComponentParameterValue("useSubscription")); } /* * XML template management */ private String getUsedXMLTemplate() { return getComponentParameterValue("xmlTemplate"); } private String getUsedXMLTemplateShortname() { String xmlFormName = getUsedXMLTemplate(); return xmlFormName.substring(xmlFormName.indexOf('/') + 1, xmlFormName.indexOf('.')); } public boolean isXMLTemplateUsed() { return StringUtil.isDefined(getUsedXMLTemplate()); } private PublicationTemplate getXMLTemplate() throws WebPagesException { if (isTemplateChanged()) { registerXMLForm(); } try { PublicationTemplate pubTemplate = PublicationTemplateManager.getInstance(). getPublicationTemplate(getComponentId() + ":" + getUsedXMLTemplateShortname()); return pubTemplate; } catch (PublicationTemplateException e) { throw new WebPagesException("WebPagesSessionController.getXMLTemplate()", SilverpeasException.ERROR, "webPages.EX_CANT_GET_TEMPLATE", e); } } public DataRecord getDataRecord() throws WebPagesException { try { PublicationTemplate pubTemplate = getXMLTemplate(); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord("0"); if (data == null) { data = recordSet.getEmptyRecord(); data.setId("0"); } return data; } catch (Exception e) { throw new WebPagesException("WebPagesSessionController.getDataRecord()", SilverpeasException.ERROR, "webPages.EX_CANT_GET_DATA", e); } } public boolean isXMLContentDefined() throws WebPagesException { DataRecord data; try { PublicationTemplate pubTemplate = getXMLTemplate(); RecordSet recordSet = pubTemplate.getRecordSet(); data = recordSet.getRecord("0"); return data != null; } catch (Exception e) { throw new WebPagesException("WebPagesSessionController.isXMLContentDefined()", SilverpeasException.ERROR, "webPages.EX_CANT_GET_DATA", e); } } public Form getViewForm() throws WebPagesException { try { PublicationTemplate pubTemplate = getXMLTemplate(); return pubTemplate.getViewForm(); } catch (PublicationTemplateException e) { throw new WebPagesException("WebPagesSessionController.getViewForm()", SilverpeasException.ERROR, "webPages.EX_CANT_GET_VIEWFORM", e); } } public Form getUpdateForm() throws WebPagesException { try { PublicationTemplate pubTemplate = getXMLTemplate(); return pubTemplate.getUpdateForm(); } catch (PublicationTemplateException e) { throw new WebPagesException("WebPagesSessionController.getUpdateForm()", SilverpeasException.ERROR, "webPages.EX_CANT_GET_UPDATEFORM", e); } } public void saveDataRecord(List<FileItem> items) throws WebPagesException { // save data in database RecordSet set; try { PublicationTemplate pub = getXMLTemplate(); set = pub.getRecordSet(); Form form = pub.getUpdateForm(); DataRecord data = set.getRecord("0"); if (data == null) { data = set.getEmptyRecord(); data.setId("0"); } PagesContext context = new PagesContext("useless", "0", getLanguage(), false, getComponentId(), getUserId()); context.setEncoding("UTF-8"); context.setObjectId("0"); context.setContentLanguage(I18NHelper.defaultLanguage); form.update(items, data, context); set.save(data); } catch (Exception e) { throw new WebPagesException("WebPagesSessionController.saveDataRecord()", SilverpeasException.ERROR, "webPages.EX_CANT_SAVE_DATA", e); } // send subscriptions WebPagesUserNotifier.notify(getNodePK(), getUserId()); // index updated data indexForm(set); } private void indexForm(RecordSet recordSet) throws WebPagesException { try { if (recordSet == null) { PublicationTemplate pub = getXMLTemplate(); recordSet = pub.getRecordSet(); } } catch (Exception e) { throw new WebPagesException("WebPagesSessionController.indexForm()", SilverpeasException.ERROR, "webPages.EX_CANT_GET_FORM", e); } // index data try { FullIndexEntry indexEntry = new FullIndexEntry(getComponentId(), "Component", getComponentId()); indexEntry.setCreationDate(new Date()); indexEntry.setCreationUser(getUserId()); indexEntry.setTitle(getComponentLabel()); ComponentInstLight component = getOrganisationController().getComponentInstLight(getComponentId()); if (component != null) { indexEntry.setPreView(component.getDescription()); } recordSet.indexRecord("0", getUsedXMLTemplateShortname(), indexEntry); IndexEngineProxy.addIndexEntry(indexEntry); } catch (FormException e) { throw new WebPagesException("WebPagesSessionController.indexForm()", SilverpeasException.ERROR, "webPages.EX_CANT_INDEX_DATA", e); } } private boolean isTemplateChanged() { return isXMLTemplateUsed() && !getUsedXMLTemplate().equals(usedTemplate); } private void registerXMLForm() { if (isXMLTemplateUsed()) { // register xmlForm to component try { PublicationTemplateManager.getInstance() .addDynamicPublicationTemplate(getComponentId() + ":" + getUsedXMLTemplateShortname(), getUsedXMLTemplate()); usedTemplate = getUsedXMLTemplate(); } catch (PublicationTemplateException e) { SilverTrace.error("webPages", "WebPagesSessionController.registerXMLForm()", "", "template = " + getUsedXMLTemplate(), e); } } } }
ebonnet/Silverpeas-Components
webPages/webPages-war/src/main/java/org/silverpeas/components/webpages/control/WebPagesSessionController.java
Java
agpl-3.0
10,887
""" Each store has slightly different semantics wrt draft v published. XML doesn't officially recognize draft but does hold it in a subdir. Old mongo has a virtual but not physical draft for every unit in published state. Split mongo has a physical for every unit in every state. Given that, here's a table of semantics and behaviors where - means no record and letters indicate values. For xml, (-, x) means the item is published and can be edited. For split, it means the item's been deleted from draft and will be deleted from published the next time it gets published. old mongo can't represent that virtual state (2nd row in table) In the table body, the tuples represent virtual modulestore result. The row headers represent the pre-import modulestore state. Modulestore virtual | XML physical (draft, published) (draft, published) | (-, -) | (x, -) | (x, x) | (x, y) | (-, x) ----------------------+-------------------------------------------- (-, -) | (-, -) | (x, -) | (x, x) | (x, y) | (-, x) (-, a) | (-, a) | (x, a) | (x, x) | (x, y) | (-, x) : deleted from draft before import (a, -) | (a, -) | (x, -) | (x, x) | (x, y) | (a, x) (a, a) | (a, a) | (x, a) | (x, x) | (x, y) | (a, x) (a, b) | (a, b) | (x, b) | (x, x) | (x, y) | (a, x) """ import logging import os import mimetypes from path import path import json import re from .xml import XMLModuleStore, ImportSystem, ParentTracker from xblock.runtime import KvsFieldData, DictKeyValueStore from xmodule.x_module import XModuleDescriptor from opaque_keys.edx.keys import UsageKey from xblock.fields import Scope, Reference, ReferenceList, ReferenceValueDict from xmodule.contentstore.content import StaticContent from .inheritance import own_metadata from xmodule.errortracker import make_error_tracker from .store_utilities import rewrite_nonportable_content_links import xblock from xmodule.tabs import CourseTabList from xmodule.modulestore.django import ASSET_IGNORE_REGEX from xmodule.modulestore.exceptions import DuplicateCourseError from xmodule.modulestore.mongo.base import MongoRevisionKey from xmodule.modulestore import ModuleStoreEnum log = logging.getLogger(__name__) def import_static_content( course_data_path, static_content_store, target_course_id, subpath='static', verbose=False): remap_dict = {} # now import all static assets static_dir = course_data_path / subpath try: with open(course_data_path / 'policies/assets.json') as f: policy = json.load(f) except (IOError, ValueError) as err: # xml backed courses won't have this file, only exported courses; # so, its absence is not really an exception. policy = {} verbose = True mimetypes.add_type('application/octet-stream', '.sjson') mimetypes.add_type('application/octet-stream', '.srt') mimetypes_list = mimetypes.types_map.values() for dirname, _, filenames in os.walk(static_dir): for filename in filenames: content_path = os.path.join(dirname, filename) if re.match(ASSET_IGNORE_REGEX, filename): if verbose: log.debug('skipping static content %s...', content_path) continue if verbose: log.debug('importing static content %s...', content_path) try: with open(content_path, 'rb') as f: data = f.read() except IOError: if filename.startswith('._'): # OS X "companion files". See # http://www.diigo.com/annotated/0c936fda5da4aa1159c189cea227e174 continue # Not a 'hidden file', then re-raise exception raise # strip away leading path from the name fullname_with_subpath = content_path.replace(static_dir, '') if fullname_with_subpath.startswith('/'): fullname_with_subpath = fullname_with_subpath[1:] asset_key = StaticContent.compute_location(target_course_id, fullname_with_subpath) policy_ele = policy.get(asset_key.path, {}) displayname = policy_ele.get('displayname', filename) locked = policy_ele.get('locked', False) mime_type = policy_ele.get('contentType') # Check extracted contentType in list of all valid mimetypes if not mime_type or mime_type not in mimetypes_list: mime_type = mimetypes.guess_type(filename)[0] # Assign guessed mimetype content = StaticContent( asset_key, displayname, mime_type, data, import_path=fullname_with_subpath, locked=locked ) # first let's save a thumbnail so we can get back a thumbnail location thumbnail_content, thumbnail_location = static_content_store.generate_thumbnail(content) if thumbnail_content is not None: content.thumbnail_location = thumbnail_location # then commit the content try: static_content_store.save(content) except Exception as err: log.exception(u'Error importing {0}, error={1}'.format( fullname_with_subpath, err )) # store the remapping information which will be needed # to subsitute in the module data remap_dict[fullname_with_subpath] = asset_key return remap_dict def import_from_xml( store, user_id, data_dir, course_dirs=None, default_class='xmodule.raw_module.RawDescriptor', load_error_modules=True, static_content_store=None, target_course_id=None, verbose=False, do_import_static=True, create_new_course_if_not_present=False): """ Import xml-based courses from data_dir into modulestore. Returns: list of new course objects Args: store: a modulestore implementing ModuleStoreWriteBase in which to store the imported courses. data_dir: the root directory from which to find the xml courses. course_dirs: If specified, the list of data_dir subdirectories to load. Otherwise, load all course dirs target_course_id: is the CourseKey that all modules should be remapped to after import off disk. NOTE: this only makes sense if importing only one course. If there are more than one course loaded from data_dir/course_dirs & you supply this id, this method will raise an AssertException. static_content_store: the static asset store do_import_static: if True, then import the course's static files into static_content_store This can be employed for courses which have substantial unchanging static content, which is too inefficient to import every time the course is loaded. Static content for some courses may also be served directly by nginx, instead of going through django. create_new_course_if_not_present: If True, then a new course is created if it doesn't already exist. Otherwise, it throws an InvalidLocationError if the course does not exist. default_class, load_error_modules: are arguments for constructing the XMLModuleStore (see its doc) """ xml_module_store = XMLModuleStore( data_dir, default_class=default_class, course_dirs=course_dirs, load_error_modules=load_error_modules, xblock_mixins=store.xblock_mixins, xblock_select=store.xblock_select, ) # If we're going to remap the course_id, then we can only do that with # a single course if target_course_id: assert(len(xml_module_store.modules) == 1) new_courses = [] for course_key in xml_module_store.modules.keys(): if target_course_id is not None: dest_course_id = target_course_id else: dest_course_id = store.make_course_key(course_key.org, course_key.course, course_key.run) runtime = None # Creates a new course if it doesn't already exist if create_new_course_if_not_present and not store.has_course(dest_course_id, ignore_case=True): try: new_course = store.create_course(dest_course_id.org, dest_course_id.course, dest_course_id.run, user_id) runtime = new_course.runtime except DuplicateCourseError: # course w/ same org and course exists log.debug( "Skipping import of course with id, %s," "since it collides with an existing one", dest_course_id ) continue with store.bulk_write_operations(dest_course_id): source_course = xml_module_store.get_course(course_key) # STEP 1: find and import course module course, course_data_path = _import_course_module( store, runtime, user_id, data_dir, course_key, dest_course_id, source_course, do_import_static, verbose ) new_courses.append(course) # STEP 2: import static content _import_static_content_wrapper( static_content_store, do_import_static, course_data_path, dest_course_id, verbose ) # STEP 3: import PUBLISHED items # now loop through all the modules depth first and then orphans with store.branch_setting(ModuleStoreEnum.Branch.published_only, dest_course_id): all_locs = set(xml_module_store.modules[course_key].keys()) all_locs.remove(source_course.location) def depth_first(subtree): """ Import top down just so import code can make assumptions about parents always being available """ if subtree.has_children: for child in subtree.get_children(): try: all_locs.remove(child.location) except KeyError: # tolerate same child occurring under 2 parents such as in # ContentStoreTest.test_image_import pass if verbose: log.debug('importing module location {loc}'.format(loc=child.location)) _import_module_and_update_references( child, store, user_id, course_key, dest_course_id, do_import_static=do_import_static, runtime=course.runtime ) depth_first(child) depth_first(source_course) for leftover in all_locs: if verbose: log.debug('importing module location {loc}'.format(loc=leftover)) _import_module_and_update_references( xml_module_store.get_item(leftover), store, user_id, course_key, dest_course_id, do_import_static=do_import_static, runtime=course.runtime ) # STEP 4: import any DRAFT items with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, dest_course_id): _import_course_draft( xml_module_store, store, user_id, course_data_path, course_key, dest_course_id, course.runtime ) return new_courses def _import_course_module( store, runtime, user_id, data_dir, course_key, dest_course_id, source_course, do_import_static, verbose, ): if verbose: log.debug("Scanning {0} for course module...".format(course_key)) # Quick scan to get course module as we need some info from there. # Also we need to make sure that the course module is committed # first into the store course_data_path = path(data_dir) / source_course.data_dir log.debug(u'======> IMPORTING course {course_key}'.format( course_key=course_key, )) if not do_import_static: # for old-style xblock where this was actually linked to kvs source_course.static_asset_path = source_course.data_dir source_course.save() log.debug('course static_asset_path={path}'.format( path=source_course.static_asset_path )) log.debug('course data_dir={0}'.format(source_course.data_dir)) with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, dest_course_id): course = _import_module_and_update_references( source_course, store, user_id, course_key, dest_course_id, do_import_static=do_import_static, runtime=runtime, ) for entry in course.pdf_textbooks: for chapter in entry.get('chapters', []): if StaticContent.is_c4x_path(chapter.get('url', '')): asset_key = StaticContent.get_location_from_path(chapter['url']) chapter['url'] = StaticContent.get_static_path_from_location(asset_key) # Original wiki_slugs had value location.course. To make them unique this was changed to 'org.course.name'. # If we are importing into a course with a different course_id and wiki_slug is equal to either of these default # values then remap it so that the wiki does not point to the old wiki. if course_key != course.id: original_unique_wiki_slug = u'{0}.{1}.{2}'.format( course_key.org, course_key.course, course_key.run ) if course.wiki_slug == original_unique_wiki_slug or course.wiki_slug == course_key.course: course.wiki_slug = u'{0}.{1}.{2}'.format( course.id.org, course.id.course, course.id.run, ) # cdodge: more hacks (what else). Seems like we have a # problem when importing a course (like 6.002) which # does not have any tabs defined in the policy file. # The import goes fine and then displays fine in LMS, # but if someone tries to add a new tab in the CMS, then # the LMS barfs because it expects that -- if there are # *any* tabs -- then there at least needs to be # some predefined ones if course.tabs is None or len(course.tabs) == 0: CourseTabList.initialize_default(course) store.update_item(course, user_id) return course, course_data_path def _import_static_content_wrapper(static_content_store, do_import_static, course_data_path, dest_course_id, verbose): # then import all the static content if static_content_store is not None and do_import_static: # first pass to find everything in /static/ import_static_content( course_data_path, static_content_store, dest_course_id, subpath='static', verbose=verbose ) elif verbose and not do_import_static: log.debug( "Skipping import of static content, " "since do_import_static={0}".format(do_import_static) ) # no matter what do_import_static is, import "static_import" directory # This is needed because the "about" pages (eg "overview") are # loaded via load_extra_content, and do not inherit the lms # metadata from the course module, and thus do not get # "static_content_store" properly defined. Static content # referenced in those extra pages thus need to come through the # c4x:// contentstore, unfortunately. Tell users to copy that # content into the "static_import" subdir. simport = 'static_import' if os.path.exists(course_data_path / simport): import_static_content( course_data_path, static_content_store, dest_course_id, subpath=simport, verbose=verbose ) def _import_module_and_update_references( module, store, user_id, source_course_id, dest_course_id, do_import_static=True, runtime=None): logging.debug(u'processing import of module {}...'.format(module.location.to_deprecated_string())) if do_import_static and 'data' in module.fields and isinstance(module.fields['data'], xblock.fields.String): # we want to convert all 'non-portable' links in the module_data # (if it is a string) to portable strings (e.g. /static/) module.data = rewrite_nonportable_content_links( source_course_id, dest_course_id, module.data ) # Move the module to a new course def _convert_reference_fields_to_new_namespace(reference): """ Convert a reference to the new namespace, but only if the original namespace matched the original course. Otherwise, returns the input value. """ assert isinstance(reference, UsageKey) if source_course_id == reference.course_key: return reference.map_into_course(dest_course_id) else: return reference fields = {} for field_name, field in module.fields.iteritems(): if field.is_set_on(module): if isinstance(field, Reference): fields[field_name] = _convert_reference_fields_to_new_namespace(field.read_from(module)) elif isinstance(field, ReferenceList): references = field.read_from(module) fields[field_name] = [_convert_reference_fields_to_new_namespace(reference) for reference in references] elif isinstance(field, ReferenceValueDict): reference_dict = field.read_from(module) fields[field_name] = { key: _convert_reference_fields_to_new_namespace(reference) for key, reference in reference_dict.iteritems() } elif field_name == 'xml_attributes': value = field.read_from(module) # remove any export/import only xml_attributes # which are used to wire together draft imports if 'parent_sequential_url' in value: del value['parent_sequential_url'] if 'index_in_children_list' in value: del value['index_in_children_list'] fields[field_name] = value else: fields[field_name] = field.read_from(module) return store.import_xblock(user_id, dest_course_id, module.location.category, module.location.block_id, fields, runtime) def _import_course_draft( xml_module_store, store, user_id, course_data_path, source_course_id, target_course_id, mongo_runtime ): ''' This will import all the content inside of the 'drafts' folder, if it exists NOTE: This is not a full course import, basically in our current application only verticals (and downwards) can be in draft. Therefore, we need to use slightly different call points into the import process_xml as we can't simply call XMLModuleStore() constructor (like we do for importing public content) ''' draft_dir = course_data_path + "/drafts" if not os.path.exists(draft_dir): return # create a new 'System' object which will manage the importing errorlog = make_error_tracker() # The course_dir as passed to ImportSystem is expected to just be relative, not # the complete path including data_dir. ImportSystem will concatenate the two together. data_dir = xml_module_store.data_dir # Whether or not data_dir ends with a "/" differs in production vs. test. if not data_dir.endswith("/"): data_dir += "/" draft_course_dir = draft_dir.replace(data_dir, '', 1) system = ImportSystem( xmlstore=xml_module_store, course_id=source_course_id, course_dir=draft_course_dir, error_tracker=errorlog.tracker, parent_tracker=ParentTracker(), load_error_modules=False, mixins=xml_module_store.xblock_mixins, field_data=KvsFieldData(kvs=DictKeyValueStore()), ) # now walk the /vertical directory where each file in there # will be a draft copy of the Vertical # First it is necessary to order the draft items by their desired index in the child list # (order os.walk returns them in is not guaranteed). drafts = dict() for dirname, _dirnames, filenames in os.walk(draft_dir + "/vertical"): for filename in filenames: module_path = os.path.join(dirname, filename) with open(module_path, 'r') as f: try: # note, on local dev it seems like OSX will put # some extra files in the directory with "quarantine" # information. These files are binary files and will # throw exceptions when we try to parse the file # as an XML string. Let's make sure we're # dealing with a string before ingesting data = f.read() try: xml = data.decode('utf-8') except UnicodeDecodeError, err: # seems like on OSX localdev, the OS is making # quarantine files in the unzip directory # when importing courses so if we blindly try to # enumerate through the directory, we'll try # to process a bunch of binary quarantine files # (which are prefixed with a '._' character which # will dump a bunch of exceptions to the output, # although they are harmless. # # Reading online docs there doesn't seem to be # a good means to detect a 'hidden' file that works # well across all OS environments. So for now, I'm using # OSX's utilization of a leading '.' in the filename # to indicate a system hidden file. # # Better yet would be a way to figure out if this is # a binary file, but I haven't found a good way # to do this yet. if filename.startswith('._'): continue # Not a 'hidden file', then re-raise exception raise err # process_xml call below recursively processes all descendants. If # we call this on all verticals in a course with verticals nested below # the unit level, we try to import the same content twice, causing naming conflicts. # Therefore only process verticals at the unit level, assuming that any other # verticals must be descendants. if 'index_in_children_list' in xml: descriptor = system.process_xml(xml) # HACK: since we are doing partial imports of drafts # the vertical doesn't have the 'url-name' set in the # attributes (they are normally in the parent object, # aka sequential), so we have to replace the location.name # with the XML filename that is part of the pack filename, __ = os.path.splitext(filename) descriptor.location = descriptor.location.replace(name=filename) index = int(descriptor.xml_attributes['index_in_children_list']) if index in drafts: drafts[index].append(descriptor) else: drafts[index] = [descriptor] except Exception: logging.exception('Error while parsing course xml.') # For each index_in_children_list key, there is a list of vertical descriptors. for key in sorted(drafts.iterkeys()): for descriptor in drafts[key]: course_key = descriptor.location.course_key try: def _import_module(module): # IMPORTANT: Be sure to update the module location in the NEW namespace module_location = module.location.map_into_course(target_course_id) # Update the module's location to DRAFT revision # We need to call this method (instead of updating the location directly) # to ensure that pure XBlock field data is updated correctly. _update_module_location(module, module_location.replace(revision=MongoRevisionKey.draft)) # make sure our parent has us in its list of children # this is to make sure private only verticals show up # in the list of children since they would have been # filtered out from the non-draft store export. # Note though that verticals nested below the unit level will not have # a parent_sequential_url and do not need special handling. if module.location.category == 'vertical' and 'parent_sequential_url' in module.xml_attributes: sequential_url = module.xml_attributes['parent_sequential_url'] index = int(module.xml_attributes['index_in_children_list']) seq_location = course_key.make_usage_key_from_deprecated_string(sequential_url) # IMPORTANT: Be sure to update the sequential in the NEW namespace seq_location = seq_location.map_into_course(target_course_id) sequential = store.get_item(seq_location, depth=0) non_draft_location = module.location.map_into_course(target_course_id) if not any(child.block_id == module.location.block_id for child in sequential.children): sequential.children.insert(index, non_draft_location) store.update_item(sequential, user_id) _import_module_and_update_references( module, store, user_id, source_course_id, target_course_id, runtime=mongo_runtime, ) for child in module.get_children(): _import_module(child) _import_module(descriptor) except Exception: logging.exception('There while importing draft descriptor %s', descriptor) def allowed_metadata_by_category(category): # should this be in the descriptors?!? return { 'vertical': [], 'chapter': ['start'], 'sequential': ['due', 'format', 'start', 'graded'] }.get(category, ['*']) def check_module_metadata_editability(module): ''' Assert that there is no metadata within a particular module that we can't support editing. However we always allow 'display_name' and 'xml_attributes' ''' allowed = allowed_metadata_by_category(module.location.category) if '*' in allowed: # everything is allowed return 0 allowed = allowed + ['xml_attributes', 'display_name'] err_cnt = 0 illegal_keys = set(own_metadata(module).keys()) - set(allowed) if len(illegal_keys) > 0: err_cnt = err_cnt + 1 print( ": found non-editable metadata on {url}. " "These metadata keys are not supported = {keys}".format( url=module.location.to_deprecated_string(), keys=illegal_keys ) ) return err_cnt def validate_no_non_editable_metadata(module_store, course_id, category): err_cnt = 0 for module_loc in module_store.modules[course_id]: module = module_store.modules[course_id][module_loc] if module.location.category == category: err_cnt = err_cnt + check_module_metadata_editability(module) return err_cnt def validate_category_hierarchy( module_store, course_id, parent_category, expected_child_category): err_cnt = 0 parents = [] # get all modules of parent_category for module in module_store.modules[course_id].itervalues(): if module.location.category == parent_category: parents.append(module) for parent in parents: for child_loc in parent.children: if child_loc.category != expected_child_category: err_cnt += 1 print( "ERROR: child {child} of parent {parent} was expected to be " "category of {expected} but was {actual}".format( child=child_loc, parent=parent.location, expected=expected_child_category, actual=child_loc.category ) ) return err_cnt def validate_data_source_path_existence(path, is_err=True, extra_msg=None): _cnt = 0 if not os.path.exists(path): print( "{type}: Expected folder at {path}. {extra}".format( type='ERROR' if is_err else 'WARNING', path=path, extra=extra_msg or "", ) ) _cnt = 1 return _cnt def validate_data_source_paths(data_dir, course_dir): # check that there is a '/static/' directory course_path = data_dir / course_dir err_cnt = 0 warn_cnt = 0 err_cnt += validate_data_source_path_existence(course_path / 'static') warn_cnt += validate_data_source_path_existence( course_path / 'static/subs', is_err=False, extra_msg='Video captions (if they are used) will not work unless they are static/subs.' ) return err_cnt, warn_cnt def validate_course_policy(module_store, course_id): """ Validate that the course explicitly sets values for any fields whose defaults may have changed between the export and the import. Does not add to error count as these are just warnings. """ # is there a reliable way to get the module location just given the course_id? warn_cnt = 0 for module in module_store.modules[course_id].itervalues(): if module.location.category == 'course': if not module._field_data.has(module, 'rerandomize'): warn_cnt += 1 print( 'WARN: course policy does not specify value for ' '"rerandomize" whose default is now "never". ' 'The behavior of your course may change.' ) if not module._field_data.has(module, 'showanswer'): warn_cnt += 1 print( 'WARN: course policy does not specify value for ' '"showanswer" whose default is now "finished". ' 'The behavior of your course may change.' ) return warn_cnt def perform_xlint( data_dir, course_dirs, default_class='xmodule.raw_module.RawDescriptor', load_error_modules=True): err_cnt = 0 warn_cnt = 0 module_store = XMLModuleStore( data_dir, default_class=default_class, course_dirs=course_dirs, load_error_modules=load_error_modules ) # check all data source path information for course_dir in course_dirs: _err_cnt, _warn_cnt = validate_data_source_paths(path(data_dir), course_dir) err_cnt += _err_cnt warn_cnt += _warn_cnt # first count all errors and warnings as part of the XMLModuleStore import for err_log in module_store._course_errors.itervalues(): for err_log_entry in err_log.errors: msg = err_log_entry[0] if msg.startswith('ERROR:'): err_cnt += 1 else: warn_cnt += 1 # then count outright all courses that failed to load at all for err_log in module_store.errored_courses.itervalues(): for err_log_entry in err_log.errors: msg = err_log_entry[0] print(msg) if msg.startswith('ERROR:'): err_cnt += 1 else: warn_cnt += 1 for course_id in module_store.modules.keys(): # constrain that courses only have 'chapter' children err_cnt += validate_category_hierarchy( module_store, course_id, "course", "chapter" ) # constrain that chapters only have 'sequentials' err_cnt += validate_category_hierarchy( module_store, course_id, "chapter", "sequential" ) # constrain that sequentials only have 'verticals' err_cnt += validate_category_hierarchy( module_store, course_id, "sequential", "vertical" ) # validate the course policy overrides any defaults # which have changed over time warn_cnt += validate_course_policy(module_store, course_id) # don't allow metadata on verticals, since we can't edit them in studio err_cnt += validate_no_non_editable_metadata( module_store, course_id, "vertical" ) # don't allow metadata on chapters, since we can't edit them in studio err_cnt += validate_no_non_editable_metadata( module_store, course_id, "chapter" ) # don't allow metadata on sequences that we can't edit err_cnt += validate_no_non_editable_metadata( module_store, course_id, "sequential" ) # check for a presence of a course marketing video if not module_store.has_item(course_id.make_usage_key('about', 'video')): print( "WARN: Missing course marketing video. It is recommended " "that every course have a marketing video." ) warn_cnt += 1 print("\n") print("------------------------------------------") print("VALIDATION SUMMARY: {err} Errors {warn} Warnings".format( err=err_cnt, warn=warn_cnt) ) if err_cnt > 0: print( "This course is not suitable for importing. Please fix courseware " "according to specifications before importing." ) elif warn_cnt > 0: print( "This course can be imported, but some errors may occur " "during the run of the course. It is recommend that you fix " "your courseware before importing" ) else: print("This course can be imported successfully.") return err_cnt def _update_module_location(module, new_location): """ Update a module's location. If the module is a pure XBlock (not an XModule), then its field data keys will need to be updated to include the new location. Args: module (XModuleMixin): The module to update. new_location (Location): The new location of the module. Returns: None """ # Retrieve the content and settings fields that have been explicitly set # to ensure that they are properly re-keyed in the XBlock field data. if isinstance(module, XModuleDescriptor): rekey_fields = [] else: rekey_fields = ( module.get_explicitly_set_fields_by_scope(Scope.content).keys() + module.get_explicitly_set_fields_by_scope(Scope.settings).keys() ) module.location = new_location # Pure XBlocks store the field data in a key-value store # in which one component of the key is the XBlock's location (equivalent to "scope_ids"). # Since we've changed the XBlock's location, we need to re-save # all the XBlock's fields so they will be stored using the new location in the key. # However, since XBlocks only save "dirty" fields, we need to first # explicitly set each field to its current value before triggering the save. if len(rekey_fields) > 0: for rekey_field_name in rekey_fields: setattr(module, rekey_field_name, getattr(module, rekey_field_name)) module.save()
xiandiancloud/edxplaltfom-xusong
common/lib/xmodule/xmodule/modulestore/xml_importer.py
Python
agpl-3.0
37,244
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>AW21 Test.6.4.1 NMI 02</title> </head> <body> <div> <p class="test-detail"> <span lang="fr">Test 6.4.1 : Chaque lien identique de type texte a-t-il les mêmes fonction et destination ?</span> </p> <p class="test-detail"> <a href="fake-link.htm">cliquez ici</a> </p> <p class="test-detail"> <a href="fake-link2.htm"> cliquez ici </a> </p> <p class="test-explanation">NMI : The page contains two identical links with context and with a different target</p> </div> </body> </html>
medsob/Tanaguru
rules/accessiweb2.1-testcases/src/main/resources/testcases/AW21/Aw21Rule06041/AW21.Test.06.04.01-3NMI-02.html
HTML
agpl-3.0
961
<?php class CsvFile { protected $current_line = 0; protected $csvdata = null; protected $file = null; protected $separator = null; protected $ignore = null; public function getFileName() { return $this->file; } public function __construct($file = null, $options = array()) { $this->options = $options; if (!isset($this->options["ignore_first_if_comment"])) { $this->options["ignore_first_if_comment"] = true; } $this->ignore = $this->options["ignore_first_if_comment"]; $this->separator = ';'; if (!$file) return ; if (!file_exists($file) && !preg_match('/^http/', $file)) throw new sfException("Cannont access $file"); $charset = $this->getCharset($file); if ($charset != 'utf-8'){ exec('iconv -f '.$charset.' -t utf-8 '.$file.' > '.$file.'.tmp'); if (filesize($file.".tmp")) { exec('mv '.$file.".tmp ".$file); } } $this->file = $file; $handle = fopen($this->file, 'r'); if (!$handle) { throw new sfException('unable to open file: '.$this->file); } $buffer = fread($handle, 500); fclose($handle); $buffer = preg_replace('/$[^\n]*\n/', '', $buffer); if (!$buffer) { throw new sfException('invalid csv file; '.$this->file); } $virgule = explode(',', $buffer); $ptvirgule = explode(';', $buffer); $tabulation = explode('\t', $buffer); if (count($virgule) > count($ptvirgule) && count($virgule) > count($tabulation)) $this->separator = ','; else if (count($tabulation) > count($ptvirgule)) $this->separator = '\t'; } public function getCsv() { if ($this->csvdata) { return $this->csvdata; } $handler = fopen($this->file, 'r'); if (!$handler) { throw new sfException('Cannot open csv file anymore'); } $this->csvdata = array(); while (($data = fgetcsv($handler, 0, $this->separator)) !== FALSE) { if (!preg_match('/^(...)?#/', $data[0]) && !preg_match('/^$/', $data[0])) { $this->csvdata[] = $data; } } fclose($handler); return $this->csvdata; } private function getCharset($file) { $ret = exec('file -i '.$file); $charset = substr($ret, strpos($ret,'charset=')); return str_replace('charset=','',$charset); } }
24eme/giilda
project/plugins/acVinImportPlugin/lib/csv/CsvFile.class.php
PHP
agpl-3.0
2,301
/** * A RESTful web service on top of DSpace. * Copyright (C) 2010-2014 National Library of Finland * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fi.helsinki.lib.simplerest; import com.google.gson.Gson; import fi.helsinki.lib.simplerest.options.GetOptions; import fi.helsinki.lib.simplerest.stubs.StubGroup; import java.sql.SQLException; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.apache.log4j.Logger; import org.apache.log4j.Priority; public class GroupResource extends BaseResource { private static Logger log = Logger.getLogger(GroupResource.class); private int groupId; private Group group; private Context context; public GroupResource(Group g, int groupId){ this.group = g; this.groupId = groupId; } public GroupResource(){ this.groupId = 0; this.group = null; try{ this.context = new Context(); }catch(SQLException e){ log.log(Priority.FATAL, e); } } @Override protected void doInit() throws ResourceException { try { String s = (String)getRequest().getAttributes().get("groupId"); this.groupId = Integer.parseInt(s); } catch (NumberFormatException e) { ResourceException resourceException = new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Group ID must be a number."); throw resourceException; } } static public String relativeUrl(int groupId) { return "group/" + Integer.toString(groupId); } @Get("html|xhtml|xml") public Representation toXml() { DomRepresentation representation = null; Document d = null; Group groups[] = null; EPerson epersons[] = null; try { representation = new DomRepresentation(MediaType.TEXT_HTML); d = representation.getDocument(); group = Group.find(context,groupId); groups = group.getMemberGroups(); epersons = group.getMembers(); } catch (Exception e) { log.log(Priority.INFO, e); } if(group == null){ return errorInternal(context, "group not found"); } Element html = d.createElement("html"); d.appendChild(html); Element head = d.createElement("head"); html.appendChild(head); Element title = d.createElement("title"); title.appendChild(d.createTextNode(group.getName())); head.appendChild(title); Element body = d.createElement("body"); html.appendChild(body); Element h1 = d.createElement("h1"); body.appendChild(h1); h1.appendChild(d.createTextNode(group.getName())); Element ul1 = d.createElement("ul"); ul1.setAttribute("id","membergroupss"); body.appendChild(ul1); for (Group subgroup : groups) { Element li = d.createElement("li"); Element a = d.createElement("a"); ul1.appendChild(li); li.appendChild(a); String url = ""; try{ url = baseUrl() + GroupResource.relativeUrl(subgroup.getID()); }catch(NullPointerException e){ log.log(Priority.INFO, e.toString()); } a.setAttribute("href",url); Text text = d.createTextNode(subgroup.getName()); a.appendChild(text); } Element ul2 = d.createElement("ul"); ul2.setAttribute("id","members"); body.appendChild(ul2); for (EPerson eperson : epersons) { Element li = d.createElement("li"); Element a = d.createElement("a"); ul2.appendChild(li); li.appendChild(a); String url = ""; try{ url = baseUrl() + UserResource.relativeUrl(eperson.getID()); }catch(NullPointerException e){ log.log(Priority.INFO, e.toString()); } a.setAttribute("href",url); Text text = d.createTextNode(eperson.getName()); a.appendChild(text); } context.abort(); // Same as c.complete() because we didn't modify the db. return representation; } @Get("json") public String toJson(){ GetOptions.allowAccess(getResponse()); try{ this.group = Group.find(context, groupId); }catch(Exception ex){ log.log(Priority.INFO, ex); }finally{ context.abort(); } StubGroup stub = new StubGroup(this.group); Gson gson = new Gson(); try{ context.abort(); }catch(NullPointerException e){ log.log(Priority.INFO, e); } return gson.toJson(stub); } }
anis-moubarik/SimpleREST
src/main/java/fi/helsinki/lib/simplerest/GroupResource.java
Java
agpl-3.0
5,734
<?php /* * This file is part of FacturaSctipts * Copyright (C) 2014 Carlos Garcia Gomez neorazorx@gmail.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'base/fs_model.php'; /** * El agente es el que se asocia a un albarán, factura o caja. * Cada usuario puede estar asociado a un agente, y un agente puede * estar asociado a varios usuarios. */ class agente extends fs_model { public $coddepartamento; public $email; public $fax; public $telefono; public $codpostal; public $codpais; public $provincia; public $ciudad; public $direccion; public $porcomision; public $irpf; public $dnicif; public $nombre; public $apellidos; public $codagente; /// pkey public function __construct($a=FALSE) { parent::__construct('agentes'); if($a) { $this->coddepartamento = $a['coddepartamento']; $this->email = $a['email']; $this->fax = $a['fax']; $this->telefono = $a['telefono']; $this->codpostal = $a['codpostal']; $this->codpais = $a['codpais']; $this->provincia = $a['provincia']; $this->ciudad = $a['ciudad']; $this->direccion = $a['direccion']; $this->porcomision = floatval($a['porcomision']); $this->irpf = floatval($a['irpf']); $this->dnicif = $a['dnicif']; $this->nombre = $a['nombre']; $this->apellidos = $a['apellidos']; $this->codagente = $a['codagente']; } else { $this->coddepartamento = NULL; $this->email = NULL; $this->fax = NULL; $this->telefono = NULL; $this->codpostal = NULL; $this->codpais = NULL; $this->provincia = NULL; $this->ciudad = NULL; $this->direccion = NULL; $this->porcomision = 0; $this->irpf = 0; $this->dnicif = ''; $this->nombre = ''; $this->apellidos = ''; $this->codagente = NULL; } } protected function install() { $this->clean_cache(); return "INSERT INTO ".$this->table_name." (codagente,nombre,apellidos,dnicif) VALUES ('1','Paco','Pepe','00000014Z');"; } public function get_fullname() { return $this->nombre." ".$this->apellidos; } public function get_new_codigo() { $sql = "SELECT MAX(".$this->db->sql_to_int('codagente').") as cod FROM ".$this->table_name.";"; $cod = $this->db->select($sql); if($cod) return 1 + intval($cod[0]['cod']); else return 1; } public function url() { if( is_null($this->codagente) ) return "index.php?page=admin_agentes"; else return "index.php?page=admin_agente&cod=".$this->codagente; } public function get($cod) { $a = $this->db->select("SELECT * FROM ".$this->table_name." WHERE codagente = ".$this->var2str($cod).";"); if($a) { return new agente($a[0]); } else return FALSE; } public function exists() { if( is_null($this->codagente) ) return FALSE; else return $this->db->select("SELECT * FROM ".$this->table_name." WHERE codagente = ".$this->var2str($this->codagente).";"); } public function test() { $status = FALSE; $this->codagente = trim($this->codagente); $this->nombre = $this->no_html($this->nombre); $this->apellidos = $this->no_html($this->apellidos); $this->dnicif = $this->no_html($this->dnicif); $this->telefono = $this->no_html($this->telefono); $this->email = $this->no_html($this->email); if( !preg_match("/^[A-Z0-9]{1,10}$/i", $this->codagente) ) $this->new_error_msg("Código de agente no válido."); else if( strlen($this->nombre) < 1 OR strlen($this->nombre) > 50 ) $this->new_error_msg("Nombre de agente no válido."); else if( strlen($this->apellidos) < 1 OR strlen($this->apellidos) > 50 ) $this->new_error_msg("Apellidos del agente no válidos."); else $status = TRUE; return $status; } public function save() { if( $this->test() ) { $this->clean_cache(); if( $this->exists() ) { $sql = "UPDATE ".$this->table_name." SET nombre = ".$this->var2str($this->nombre).", apellidos = ".$this->var2str($this->apellidos).", dnicif = ".$this->var2str($this->dnicif).", telefono = ".$this->var2str($this->telefono).", email = ".$this->var2str($this->email).", porcomision = ".$this->var2str($this->porcomision)." WHERE codagente = ".$this->var2str($this->codagente).";"; } else { $sql = "INSERT INTO ".$this->table_name." (codagente,nombre,apellidos,dnicif,telefono,email,porcomision) VALUES (".$this->var2str($this->codagente).",".$this->var2str($this->nombre).", ".$this->var2str($this->apellidos).",".$this->var2str($this->dnicif).", ".$this->var2str($this->telefono).",".$this->var2str($this->email).",".$this->var2str($this->porcomision).");"; } return $this->db->exec($sql); } else return FALSE; } public function delete() { $this->clean_cache(); return $this->db->exec("DELETE FROM ".$this->table_name." WHERE codagente = ".$this->var2str($this->codagente).";"); } private function clean_cache() { $this->cache->delete('m_agente_all'); } public function all() { $listagentes = $this->cache->get_array('m_agente_all'); if( !$listagentes ) { $agentes = $this->db->select("SELECT * FROM ".$this->table_name." ORDER BY nombre ASC;"); if($agentes) { foreach($agentes as $a) $listagentes[] = new agente($a); } $this->cache->set('m_agente_all', $listagentes); } return $listagentes; } }
opblanco/facturascripts
model/agente.php
PHP
agpl-3.0
6,696
""" *2014.09.10 16:10:05 DEPRECATED!!!! please use building.models.search_building and building.models.make_building instead of the make_unit and make_building functions found here... out of date. """ import sys, os, json, codecs, re sys.path.append(os.path.dirname(os.getcwd())) from geopy import geocoders, distance # MapQuest no longer available in present api. Work around # detailed here: http://stackoverflow.com/questions/30132636/geocoding-error-with-geopandas-and-geopy geocoders.MapQuest = geocoders.OpenMapQuest #http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell #from rentrocket import settings #from django.core.management import setup_environ #setup_environ(settings) #pre django 1.4 approach: #from rentrocket import settings as rrsettings #from django.core.management import setup_environ #setup_environ(settings) #from django.conf import settings #settings.configure(rrsettings) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rentrocket.settings") from building.models import Building, Parcel, BuildingPerson, Unit from person.models import Person def parse_person(text): """ take a string representing all details of a person and try to parse out the different details for that person... usually it's a comma separated string, but sometimes names have commas in them instead, look for the start of the address, either a number or a PO variation """ name = '' address = '' phone = '' remainder = '' print "Parsing: %s" % text phone = re.compile("(\d{3})\W*(\d{3})\W*(\d{4})\W*(\w*)") m = phone.search(text) if m: #print dir(m) #print len(m.groups()) phone1 = m.group(1) parts = text.split(phone1) #update text so it only contains part without phone number: text = parts[0] full_phone = phone1+parts[1] print "Phone found: %s" % full_phone filler='.*?' # Non-greedy match on filler po_box='( P\\.O\\. | P O | PO )' rg = re.compile(po_box,re.IGNORECASE|re.DOTALL) m = rg.search(text) if m: csv1=m.group(1) print "PO BOX MATCH: ("+csv1+")"+"\n" print text parts = text.split(csv1) #name = m.group(0) name = parts[0] #IndexError: no such group #address = m.group(1) + m.group(2) address = m.group(1) + parts[1] else: re2='(\\d+)' # Integer Number 1 rg = re.compile(re2,re.IGNORECASE|re.DOTALL) m = rg.search(text) if m: int1 = m.group(1) print "NUMBER MATCH: (" + int1 + ")" parts = text.split(int1) #name = m.group(0) name = parts[0] #IndexError: no such group #address = m.group(1) + m.group(2) address = m.group(1) + parts[1] address = address.strip() name = name.strip() print "name: %s" % name print "address: %s" % address print "" if name[-1] == ',': name = name[:-1] if address[-1] == ',': address = address[:-1] return (name, address, phone, remainder) def make_building(location, bldg_id, city, feed_source, parcel_id=None, bldg_type=None, no_units=None, sqft=None): """ add the building to the database #*2015.03.07 14:04:37 #see search_building(bldgform.cleaned_data.get("address"), unit=unit, make=True) """ full_city = '%s, IN, USA' % city.name match = False #find an address to use for geo_source in location.sources: if not match: source_list = location.get_source(geo_source) if len(source_list) and source_list[0]['place'] and source_list[0]['place'] != full_city: print "using: %s to check: %s" % (geo_source, source_list[0]['place']) match = True #TODO: process this a bit more... #probably don't want city and zip here: #keeping city and zip minimizes chance for overlap #especially since this is used as a key #can always take it out on display, if necessary #*2014.09.10 14:51:28 #this has changed... should only use street now... #see building/models.py -> make_building #cur_address = source_list[0]['place'] #cur_address = source_list[0]['place'] if parcel_id == None: cid = "%s-%s" % (city.tag, bldg_id) else: cid = parcel_id print "Checking parcel id: %s" % (cid) parcels = Parcel.objects.filter(custom_id=cid) if parcels.exists(): parcel = parcels[0] print "Already had parcel: %s" % parcel.custom_id else: parcel = Parcel() parcel.custom_id = cid parcel.save() print "Created new parcel: %s" % parcel.custom_id buildings = Building.objects.filter(city=city).filter(address=cur_address) bldg = None #check if a previous building object in the db exists if buildings.exists(): bldg = buildings[0] print "Already had: %s" % bldg.address else: #if not, #CREATE A NEW BUILDING OBJECT HERE #cur_building = Building() bldg = Building() #bldg.address = source_list[0]['place'] bldg.address = source_list[0]['street'] bldg.latitude = float(source_list[0]['lat']) bldg.longitude = float(source_list[0]['lng']) bldg.parcel = parcel bldg.geocoder = geo_source bldg.source = feed_source bldg.city = city bldg.state = city.state if bldg_type: bldg.type = bldg_type if no_units: bldg.number_of_units = no_units if sqft: bldg.sqft = sqft bldg.save() print "Created new building: %s" % bldg.address return bldg else: print "Skipping: %s with value: %s" % (geo_source, source_list[0]['place']) def make_unit(apt_num, building): #check for existing: units = Unit.objects.filter(building=building).filter(number=apt_num) unit = None #check if a previous building object in the db exists if units.exists(): unit = units[0] print "Already had Unit: %s" % unit.address else: #if not, #CREATE A NEW UNIT OBJECT HERE unit = Unit() unit.building = building unit.number = apt_num # don't want to set this unless it's different: #unit.address = building.address + ", " + apt_num ## bedrooms ## bathrooms ## sqft ## max_occupants unit.save() print "Created new unit: %s" % unit.number return unit def make_person(name, building, relation, address=None, city=None, website=None, phone=None): #now associate applicant with building: #first find/make person people = Person.objects.filter(city=city).filter(name=name) person = None #check if a previous building object in the db exists if people.exists(): person = people[0] print "Already had Person: %s" % person.name else: #if not, #CREATE A NEW PERSON OBJECT HERE person = Person() person.name = name if city: person.city = city if address: person.address = address if website: person.website = website if phone: person.phone = phone person.save() #then find/make association: bpeople = BuildingPerson.objects.filter(building=building).filter(person=person) bperson = None #check if a previous building_person object in the db exists if bpeople.exists(): bperson = bpeople[0] print "Already had BuildingPerson: %s with: %s" % (bperson.person.name, bperson.building.address) else: #if not, #CREATE A NEW BUILDING PERSON OBJECT HERE bperson = BuildingPerson() bperson.person = person bperson.building = building bperson.relation = relation bperson.save() return (person, bperson) def save_results(locations, destination="test.tsv"): #destination = "test.tsv" match_tallies = {} closest_tallies = {} furthest_tallies = {} print "Saving: %s results to %s" % (len(locations), destination) with codecs.open(destination, 'w', encoding='utf-8') as out: #print locations.values()[0].make_header() out.write(locations.values()[0].make_header()) for key, location in locations.items(): for source in location.sources: #if hasattr(location, source) and getattr(location, source)[0]['place']: source_list = location.get_source(source) if len(source_list) and source_list[0]['place']: if match_tallies.has_key(source): match_tallies[source] += 1 else: match_tallies[source] = 1 location.compare_points() #print location.make_row() # this was used to filter units with 1, 1 out separately #if location.bldg_units == '1, 1': # out.write(location.make_row()) print match_tallies exit() class Location(object): """ hold geolocation data associated with a specific address making an object to help with processing results consistently """ def __init__(self, dictionary={}, sources=None): """ http://stackoverflow.com/questions/1305532/convert-python-dict-to-object """ self.__dict__.update(dictionary) if sources: self.sources = sources else: self.sources = ["google", "bing", "usgeo", "geonames", "openmq", "mq"] #*2014.01.08 09:01:16 #this was only needed for csv exporting #but these valued should be passed in to make_building #this is not provided by any geolocation service, #so it doesn't make sense to track here: #self.units_bdrms = '' #self.bldg_units = '' def get_source(self, source): """ wrap hasattr/getattr combination if we have something, return it, otherwise return empty list """ if hasattr(self, source): return getattr(self, source) else: return [] def to_dict(self): """ http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields """ result = self.__dict__.copy() #can't remove('sources') on a dict result.pop('sources', None) return result def compare_points(self): #find only points with something in them options = {} for source in self.sources: #this does the same thing as the next 2 lines, #but is not as easy to read #if hasattr(self, source) and getattr(self, source)[0]['place']: source_list = self.get_source(source) if len(source_list) and source_list[0]['place']: #options[source] = getattr(self, source)[0] options[source] = source_list[0] d = distance.distance available = options.keys() self.distances = {} self.totals = {} index = 1 for item in available: total = 0 others = available[:] if item in others: others.remove(item) for other in others: pt1 = ( options[item]['lat'], options[item]['lng'] ) pt2 = ( options[other]['lat'], options[other]['lng'] ) key = "%s-%s" % (item, other) #https://github.com/geopy/geopy/blob/master/geopy/distance.py #miles are also an option #cur_d = d(pt1, pt2).miles cur_d = d(pt1, pt2).feet if not self.distances.has_key(key): self.distances[key] = cur_d total += cur_d #this will be the same for all items if adding everything self.totals[item] = total def min_max_distances(self): if not self.distances: self.compare_points() sortable = [] for key, value in self.distances.items(): sortable.append( (value, key) ) sortable.sort() if len(sortable) >= 2: return ( sortable[0], sortable[-1] ) else: return ( ('', ''), ('', '') ) def min_max_totals(self): if not self.distances: self.compare_points() sortable = [] for key, value in self.totals.items(): sortable.append( (value, key) ) sortable.sort() if len(sortable) >= 2: return ( sortable[0], sortable[-1] ) else: return ( ('', ''), ('', '') ) def make_header(self): """ return a row representation of the header (for CSV output) """ #header = [ 'search', 'address', 'bldg_units', 'units_bdrms', '' ] header = [ 'search', 'address', '' ] header.extend( self.sources ) header.extend( [ '', 'closest', 'closest_amt', 'furthest', 'furthest_amt', '' ] ) header.extend( [ '', 'tclosest', 'tclosest_amt', 'tfurthest', 'tfurthest_amt', '' ] ) index = 1 for item1 in self.sources: for item2 in self.sources[index:]: title = "%s-%s" % (item1, item2) header.append(title) return "\t".join(header) + '\n' def make_row(self): """ return a row representation of our data (for CSV output) """ ## for source in self.sources: ## if self.get ## if source == 'google': ## #set this as the default ## if location.google['place']: ## location.address = location.google['place'] ## else: ## #TODO ## #maybe check other places? ## location.address = '' #row = [ self.address ] row = [] found_address = False for source in self.sources: source_list = self.get_source(source) if len(source_list) and source_list[0]['place']: #if hasattr(self, source) and getattr(self, source)[0]['place']: # cur = getattr(self, source)[0] cur = source_list[0] ll = "%s, %s" % (cur['lat'], cur['lng']) #pick out the first address that has a value if not found_address: #insert these in reverse order: self.address = cur['place'] row.insert(0, '') #row.insert(0, self.units_bdrms) #row.insert(0, self.bldg_units) row.insert(0, self.address) #this should always be set... if not, investigate why: if not hasattr(self, 'address_alt'): print self.to_dict() exit() row.insert(0, self.address_alt) found_address = True else: ll = '' row.append( ll ) #couldn't find an address anywhere: if not found_address: row.insert(0, '') #row.insert(0, self.units_bdrms) #row.insert(0, self.bldg_units) row.insert(0, '') row.insert(0, self.address_alt) print "ERROR LOCATING: %s" % self.address_alt (mi, ma) = self.min_max_distances() # 'closest', 'closest_amt', 'furthest', 'furthest_amt', row.extend( [ '', mi[1], str(mi[0]), ma[1], str(ma[0]), '' ] ) (mi, ma) = self.min_max_totals() # 'closest', 'closest_amt', 'furthest', 'furthest_amt', row.extend( [ '', mi[1], str(mi[0]), ma[1], str(ma[0]), '' ] ) index = 1 for item1 in self.sources: for item2 in self.sources[index:]: title = "%s-%s" % (item1, item2) if self.distances.has_key(title): row.append(str(self.distances[title])) else: row.append('') return "\t".join(row) + '\n' class Geo(object): """ object to assist with geocoding tasks... wraps geopy and initializes coders in one spot """ def __init__(self): #initialize geocoders once: self.google = geocoders.GoogleV3() #doesn't look like yahoo supports free api any longer: #http://developer.yahoo.com/forum/General-Discussion-at-YDN/Yahoo-GeoCode-404-Not-Found/1362061375511-7faa66ba-191d-4593-ba63-0bb8f5d43c06 #yahoo = geocoders.Yahoo('PCqXY9bV34G8P7jzm_9JeuOfIviv37mvfyTvA62Ro_pBrwDtoIaiNLT_bqRVtETpb79.avb0LFV4U1fvgyz0bQlX_GoBA0s-') self.usgeo = geocoders.GeocoderDotUS() #self.geonames = geocoders.GeoNames() self.bing = geocoders.Bing('AnFGlcOgRppf5ZSLF8wxXXN2_E29P-W9CMssWafE1RC9K9eXhcAL7nqzTmjwzMQD') self.openmq = geocoders.OpenMapQuest() #self.mq = geocoders.MapQuest('Fmjtd%7Cluub2hu7nl%2C20%3Do5-9uzg14') #skipping mediawiki, seems less complete? #mediawiki = geocoders.MediaWiki("http://wiki.case.edu/%s") def lookup(self, address, source="google", location=None, force=False): """ look up the specified address using the designated source if location dictionary is specified (for local caching) store results there return results either way """ updated = False if not location is None: self.location = location else: self.location = Location() #if we already have any value for source (even None) #won't look again unless force is set True if (not hasattr(location, source)) or force: do_query = False if hasattr(location, source): previous_result = getattr(location, source) if previous_result[0]['place'] is None: do_query = True else: do_query = True if do_query: print "Looking for: %s in %s" % (address, source) coder = getattr(self, source) if hasattr(location, source): result = getattr(location, source) else: result = [] #Be very careful when enabling try/except here: #can hide limit errors with a geocoder. #good to do at the last phase #try: options = coder.geocode(address, exactly_one=False) if options: if isinstance(options[0], unicode): (place, (lat, lng)) = options result.append({'place': place, 'lat': lat, 'lng': lng}) setattr(location, source, result) print location.to_dict() updated = True else: print options for place, (lat, lng) in options: #clear out any old "None" entries: for item in result[:]: if item['place'] is None: result.remove(item) result.append({'place': place, 'lat': lat, 'lng': lng}) setattr(location, source, result) print location.to_dict() updated = True #print "Result was: %s" % place #print "lat: %s, long: %s" % (lat, lng) #setattr(location, source, {'place': place, 'lat': lat, 'lng': lng}) ## except: ## print "Error with lookup!" ## result.append({'place': None, 'lat': None, 'lng': None}) ## setattr(location, source, result) else: print "Already have %s results for: %s" % (source, address) return updated def save_json(destination, json_objects): json_file = codecs.open(destination, 'w', encoding='utf-8', errors='ignore') json_file.write(json.dumps(json_objects)) json_file.close() def load_json(source_file, create=False): if not os.path.exists(source_file): json_objects = {} if create: print "CREATING NEW JSON FILE: %s" % source_file json_file = codecs.open(source_file, 'w', encoding='utf-8', errors='ignore') #make sure there is something there for subsequent loads json_file.write(json.dumps(json_objects)) json_file.close() else: raise ValueError, "JSON file does not exist: %s" % source_file else: json_file = codecs.open(source_file, 'r', encoding='utf-8', errors='ignore') try: json_objects = json.loads(json_file.read()) except: raise ValueError, "No JSON object could be decoded from: %s" % source_file json_file.close() return json_objects
City-of-Bloomington/green-rental
scripts/helpers.py
Python
agpl-3.0
22,169
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("time_log", "activity_type", "activity_type"); cur_frm.add_fetch("time_log", "billing_amount", "billing_amount"); cur_frm.add_fetch("time_log", "hours", "hours"); cur_frm.set_query("time_log", "time_logs", function(doc) { return { query: "erpnext.projects.utils.get_time_log_list", filters: { "billable": 1, "status": "Submitted" } } }); $.extend(cur_frm.cscript, { refresh: function(doc) { cur_frm.set_intro({ "Draft": __("Select Time Logs and Submit to create a new Sales Invoice."), "Submitted": __("Click on 'Make Sales Invoice' button to create a new Sales Invoice."), "Billed": __("This Time Log Batch has been billed."), "Cancelled": __("This Time Log Batch has been cancelled.") }[doc.status]); if(doc.status=="Submitted") { cur_frm.add_custom_button(__("Make Sales Invoice"), function() { cur_frm.cscript.make_invoice() }, "icon-file-alt"); } }, make_invoice: function() { frappe.model.open_mapped_doc({ method: "erpnext.projects.doctype.time_log_batch.time_log_batch.make_sales_invoice", frm: cur_frm }); } }); frappe.ui.form.on("Time Log Batch Detail", "time_log", function(frm, cdt, cdn) { var tl = frm.doc.time_logs || []; total_hr = 0; total_amt = 0; for(var i=0; i<tl.length; i++) { total_hr += tl[i].hours; total_amt += tl[i].billing_amount; } cur_frm.set_value("total_hours", total_hr); cur_frm.set_value("total_billing_amount", total_amt); });
mbauskar/alec_frappe5_erpnext
erpnext/projects/doctype/time_log_batch/time_log_batch.js
JavaScript
agpl-3.0
1,580
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ namespace Shopware\Bundle\ESIndexingBundle; use Elasticsearch\Client; use Shopware\Bundle\ESIndexingBundle\Console\ProgressHelperInterface; use Shopware\Bundle\ESIndexingBundle\Struct\IndexConfiguration; use Shopware\Bundle\ESIndexingBundle\Struct\ShopIndex; use Shopware\Bundle\StoreFrontBundle\Struct\Shop; class ShopIndexer implements ShopIndexerInterface { /** * @var Client */ private $client; /** * @var BacklogReaderInterface */ private $backlogReader; /** * @var MappingInterface[] */ private $mappings; /** * @var DataIndexerInterface[] */ private $indexer; /** * @var SettingsInterface[] */ private $settings; /** * @var IndexFactoryInterface */ private $indexFactory; /** * @var BacklogProcessorInterface */ private $backlogProcessor; /** * @var array */ private $configuration; /** * @param Client $client * @param BacklogReaderInterface $backlogReader * @param BacklogProcessorInterface $backlogProcessor * @param IndexFactoryInterface $indexFactory * @param DataIndexerInterface[] $indexer * @param MappingInterface[] $mappings * @param SettingsInterface[] $settings * @param array $configuration */ public function __construct( Client $client, BacklogReaderInterface $backlogReader, BacklogProcessorInterface $backlogProcessor, IndexFactoryInterface $indexFactory, array $indexer, array $mappings, array $settings, array $configuration ) { $this->client = $client; $this->backlogReader = $backlogReader; $this->backlogProcessor = $backlogProcessor; $this->indexFactory = $indexFactory; $this->indexer = $indexer; $this->mappings = $mappings; $this->settings = $settings; $this->configuration = $configuration; } /** * {@inheritdoc} * * @throws \RuntimeException */ public function index(Shop $shop, ProgressHelperInterface $helper) { $lastBacklogId = $this->backlogReader->getLastBacklogId(); $configuration = $this->indexFactory->createIndexConfiguration($shop); $shopIndex = new ShopIndex($configuration->getName(), $shop); $this->createIndex($configuration, $shopIndex); $this->updateMapping($shopIndex); $this->populate($shopIndex, $helper); $this->applyBacklog($shopIndex, $lastBacklogId); $this->createAlias($configuration); } /** * Removes unused indices */ public function cleanupIndices() { $prefix = $this->indexFactory->getPrefix(); $aliases = $this->client->indices()->getAliases(); foreach ($aliases as $index => $indexAliases) { if (strpos($index, $prefix) !== 0) { continue; } if (empty($indexAliases['aliases'])) { $this->client->indices()->delete(['index' => $index]); } } } /** * @param IndexConfiguration $configuration * @param ShopIndex $index * * @throws \RuntimeException */ private function createIndex(IndexConfiguration $configuration, ShopIndex $index) { $exist = $this->client->indices()->exists(['index' => $configuration->getName()]); if ($exist) { throw new \RuntimeException(sprintf('ElasticSearch index %s already exist.', $configuration->getName())); } $mergedSettings = [ 'settings' => [ 'number_of_shards' => $configuration->getNumberOfShards(), 'number_of_replicas' => $configuration->getNumberOfReplicas(), ], ]; // Merge default settings with those set by plugins foreach ($this->settings as $setting) { $settings = $setting->get($index->getShop()); if (!$settings) { continue; } $mergedSettings = array_replace_recursive($mergedSettings, $settings); } $this->client->indices()->create([ 'index' => $configuration->getName(), 'body' => $mergedSettings, ]); } /** * @param ShopIndex $index */ private function updateMapping(ShopIndex $index) { foreach ($this->mappings as $mapping) { $this->client->indices()->putMapping([ 'index' => $index->getName(), 'type' => $mapping->getType(), 'body' => $mapping->get($index->getShop()), ]); } } /** * @param ShopIndex $index * @param ProgressHelperInterface $progress */ private function populate(ShopIndex $index, ProgressHelperInterface $progress) { foreach ($this->indexer as $indexer) { $indexer->populate($index, $progress); } $this->client->indices()->refresh(['index' => $index->getName()]); } /** * @param ShopIndex $shopIndex * @param int $lastId */ private function applyBacklog(ShopIndex $shopIndex, $lastId) { $backlogs = $this->backlogReader->read($lastId, 100); if (empty($backlogs)) { return; } while ($backlogs = $this->backlogReader->read($lastId, 100)) { $this->backlogProcessor->process($shopIndex, $backlogs); $last = array_pop($backlogs); $lastId = $last->getId(); } } /** * @param IndexConfiguration $configuration */ private function createAlias(IndexConfiguration $configuration) { $exist = $this->client->indices()->existsAlias(['name' => $configuration->getAlias()]); if ($exist) { $this->switchAlias($configuration); return; } $this->client->indices()->putAlias([ 'index' => $configuration->getName(), 'name' => $configuration->getAlias(), ]); } /** * @param IndexConfiguration $configuration */ private function switchAlias(IndexConfiguration $configuration) { $actions = [ ['add' => ['index' => $configuration->getName(), 'alias' => $configuration->getAlias()]], ]; $current = $this->client->indices()->getAlias(['name' => $configuration->getAlias()]); $current = array_keys($current); foreach ($current as $value) { $actions[] = ['remove' => ['index' => $value, 'alias' => $configuration->getAlias()]]; } $this->client->indices()->updateAliases(['body' => ['actions' => $actions]]); } }
egoistIT/shopware
engine/Shopware/Bundle/ESIndexingBundle/ShopIndexer.php
PHP
agpl-3.0
7,739
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken 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. # # Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>. # This Class is a plugin for the Shinken Broker. It is in charge # to brok information of the service perfdata into the file # var/service-perfdata # So it just manage the service_check_return # Maybe one day host data will be useful too # It will need just a new file, and a new manager :) import codecs from shinken.basemodule import BaseModule properties = { 'daemons': ['broker'], 'type': 'service_perfdata', 'phases': ['running'], } # called by the plugin manager to get a broker def get_instance(plugin): print "Get a Service Perfdata broker for plugin %s" % plugin.get_name() # Catch errors path = plugin.path if hasattr(plugin, 'mode'): mode = plugin.mode else: mode = 'a' if hasattr(plugin, 'template'): template = plugin.template else: template = "$LASTSERVICECHECK$\t$HOSTNAME$\t$SERVICEDESC$\t$SERVICEOUTPUT$\t$SERVICESTATE$\t$SERVICEPERFDATA$\n" # int(data['last_chk']),data['host_name'], data['service_description'], data['output'], current_state, data['perf_data'] instance = Service_perfdata_broker(plugin, path, mode, template) return instance # Class for the Merlindb Broker # Get broks and puts them in merlin database class Service_perfdata_broker(BaseModule): def __init__(self, modconf, path, mode, template): BaseModule.__init__(self, modconf) self.path = path self.mode = mode self.template = template # Make some raw change self.template = self.template.replace(r'\t', '\t') self.template = self.template.replace(r'\n', '\n') # In Nagios it's said to force a return in line if not self.template.endswith('\n'): self.template += '\n' self.buffer = [] # Called by Broker so we can do init stuff # TODO: add conf param to get pass with init # Conf from arbiter! def init(self): print "[%s] I open the service-perfdata file '%s'" % (self.name, self.path) # Try to open the file to be sure we can self.file = codecs.open(self.path, self.mode, "utf-8") self.file.close() # We've got a 0, 1, 2 or 3 (or something else? ->3 # And want a real OK, WARNING, CRITICAL, etc... def resolve_service_state(self, state): states = {0: 'OK', 1: 'WARNING', 2: 'CRITICAL', 3: 'UNKNOWN'} if state in states: return states[state] else: return 'UNKNOWN' # A service check have just arrived, we UPDATE data info with this def manage_service_check_result_brok(self, b): data = b.data # The original model # "$TIMET\t$HOSTNAME\t$SERVICEDESC\t$OUTPUT\t$SERVICESTATE\t$PERFDATA\n" current_state = self.resolve_service_state(data['state_id']) macros = { '$LASTSERVICECHECK$': int(data['last_chk']), '$HOSTNAME$': data['host_name'], '$SERVICEDESC$': data['service_description'], '$SERVICEOUTPUT$': data['output'], '$SERVICESTATE$': current_state, '$SERVICEPERFDATA$': data['perf_data'], '$LASTSERVICESTATE$': data['last_state'], } s = self.template for m in macros: #print "Replacing in %s %s by %s" % (s, m, str(macros[m])) s = s.replace(m, unicode(macros[m])) #s = "%s\t%s\t%s\t%s\t%s\t%s\n" % (int(data['last_chk']),data['host_name'], \ # data['service_description'], data['output'], \ # current_state, data['perf_data'] ) self.buffer.append(s) # Each second the broker say it's a new second. Let use this to # dump to the file def hook_tick(self, brok): # Go to write it :) buf = self.buffer self.buffer = [] try: self.file = codecs.open(self.path, self.mode, "utf-8") for s in buf: self.file.write(s) self.file.flush() self.file.close() except IOError, exp: # Maybe another tool is just getting it, pass pass
shinken-monitoring/mod-perfdata-service
module/module.py
Python
agpl-3.0
5,056
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: Grayscale.qml Example File (declarative/shadereffects/qml/shadereffects/Grayscale.qml)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">Grayscale.qml Example File</h1> <span class="small-subtitle">declarative/shadereffects/qml/shadereffects/Grayscale.qml</span> <!-- $$$declarative/shadereffects/qml/shadereffects/Grayscale.qml-description --> <div class="descr"> <a name="details"></a> <pre class="qml"> <span class="comment">/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/</span> import QtQuick 1.0 import Qt.labs.shaders 1.0 <span class="type"><a href="qml-item.html">Item</a></span> { <span class="name">id</span>: <span class="name">main</span> <span class="name">anchors</span>.fill: <span class="name">parent</span> <span class="type">GrayscaleEffect</span> { <span class="name">id</span>: <span class="name">layer</span> <span class="name">anchors</span>.fill: <span class="name">parent</span> <span class="name">source</span>: <span class="name">ShaderEffectSource</span> { <span class="name">sourceItem</span>: <span class="name">Image</span> { <span class="name">source</span>: <span class="string">&quot;images/desaturate.jpg&quot;</span> } <span class="name">live</span>: <span class="number">false</span> <span class="name">hideSource</span>: <span class="number">true</span> } SequentialAnimation on <span class="name">ratio</span> { <span class="name">id</span>: <span class="name">ratioAnimation</span> <span class="name">running</span>: <span class="number">true</span> <span class="name">loops</span>: <span class="name">Animation</span>.<span class="name">Infinite</span> <span class="type"><a href="qml-numberanimation.html">NumberAnimation</a></span> { <span class="name">easing</span>.type: <span class="name">Easing</span>.<span class="name">Linear</span> <span class="name">to</span>: <span class="number">0.0</span> <span class="name">duration</span>: <span class="number">1500</span> } <span class="type"><a href="qml-pauseanimation.html">PauseAnimation</a></span> { <span class="name">duration</span>: <span class="number">1000</span> } <span class="type"><a href="qml-numberanimation.html">NumberAnimation</a></span> { <span class="name">easing</span>.type: <span class="name">Easing</span>.<span class="name">Linear</span> <span class="name">to</span>: <span class="number">1.0</span> <span class="name">duration</span>: <span class="number">1500</span> } <span class="type"><a href="qml-pauseanimation.html">PauseAnimation</a></span> { <span class="name">duration</span>: <span class="number">1000</span> } } } }</pre> </div> <!-- @@@declarative/shadereffects/qml/shadereffects/Grayscale.qml --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2014 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
eric100lin/Qt-4.8.6
doc/html/declarative-shadereffects-qml-shadereffects-grayscale-qml.html
HTML
lgpl-2.1
13,806
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qxsdcomplextype_p.h" QT_BEGIN_NAMESPACE using namespace QPatternist; void XsdComplexType::OpenContent::setMode(Mode mode) { m_mode = mode; } XsdComplexType::OpenContent::Mode XsdComplexType::OpenContent::mode() const { return m_mode; } void XsdComplexType::OpenContent::setWildcard(const XsdWildcard::Ptr &wildcard) { m_wildcard = wildcard; } XsdWildcard::Ptr XsdComplexType::OpenContent::wildcard() const { return m_wildcard; } void XsdComplexType::ContentType::setVariety(Variety variety) { m_variety = variety; } XsdComplexType::ContentType::Variety XsdComplexType::ContentType::variety() const { return m_variety; } void XsdComplexType::ContentType::setParticle(const XsdParticle::Ptr &particle) { m_particle = particle; } XsdParticle::Ptr XsdComplexType::ContentType::particle() const { return m_particle; } void XsdComplexType::ContentType::setOpenContent(const OpenContent::Ptr &content) { m_openContent = content; } XsdComplexType::OpenContent::Ptr XsdComplexType::ContentType::openContent() const { return m_openContent; } void XsdComplexType::ContentType::setSimpleType(const AnySimpleType::Ptr &type) { m_simpleType = type; } AnySimpleType::Ptr XsdComplexType::ContentType::simpleType() const { return m_simpleType; } XsdComplexType::XsdComplexType() : m_isAbstract(false) , m_contentType(new ContentType()) { m_contentType->setVariety(ContentType::Empty); } void XsdComplexType::setIsAbstract(bool abstract) { m_isAbstract = abstract; } bool XsdComplexType::isAbstract() const { return m_isAbstract; } QString XsdComplexType::displayName(const NamePool::Ptr &np) const { return np->displayName(name(np)); } void XsdComplexType::setWxsSuperType(const SchemaType::Ptr &type) { m_superType = type.data(); } SchemaType::Ptr XsdComplexType::wxsSuperType() const { return SchemaType::Ptr(m_superType); } void XsdComplexType::setContext(const NamedSchemaComponent::Ptr &component) { m_context = component.data(); } NamedSchemaComponent::Ptr XsdComplexType::context() const { return NamedSchemaComponent::Ptr(m_context); } void XsdComplexType::setContentType(const ContentType::Ptr &type) { m_contentType = type; } XsdComplexType::ContentType::Ptr XsdComplexType::contentType() const { return m_contentType; } void XsdComplexType::setAttributeUses(const XsdAttributeUse::List &attributeUses) { m_attributeUses = attributeUses; } void XsdComplexType::addAttributeUse(const XsdAttributeUse::Ptr &attributeUse) { m_attributeUses.append(attributeUse); } XsdAttributeUse::List XsdComplexType::attributeUses() const { return m_attributeUses; } void XsdComplexType::setAttributeWildcard(const XsdWildcard::Ptr &wildcard) { m_attributeWildcard = wildcard; } XsdWildcard::Ptr XsdComplexType::attributeWildcard() const { return m_attributeWildcard; } XsdComplexType::TypeCategory XsdComplexType::category() const { return ComplexType; } void XsdComplexType::setDerivationMethod(DerivationMethod method) { m_derivationMethod = method; } XsdComplexType::DerivationMethod XsdComplexType::derivationMethod() const { return m_derivationMethod; } void XsdComplexType::setProhibitedSubstitutions(const BlockingConstraints &substitutions) { m_prohibitedSubstitutions = substitutions; } XsdComplexType::BlockingConstraints XsdComplexType::prohibitedSubstitutions() const { return m_prohibitedSubstitutions; } void XsdComplexType::setAssertions(const XsdAssertion::List &assertions) { m_assertions = assertions; } void XsdComplexType::addAssertion(const XsdAssertion::Ptr &assertion) { m_assertions.append(assertion); } XsdAssertion::List XsdComplexType::assertions() const { return m_assertions; } bool XsdComplexType::isDefinedBySchema() const { return true; } QT_END_NAMESPACE
sicily/qt4.8.4
src/xmlpatterns/schema/qxsdcomplextype.cpp
C++
lgpl-2.1
5,842
package net.jradius.tls; /** * A queue for bytes. This file could be more optimized. */ public class ByteQueue { /** * @return The smallest number which can be written as 2^x which is bigger than i. */ public static final int nextTwoPow(int i) { /* * This code is based of a lot of code I found on the Internet which mostly * referenced a book called "Hacking delight". */ i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i + 1; } /** * The initial size for our buffer. */ private static final int INITBUFSIZE = 1024; /** * The buffer where we store our data. */ private byte[] databuf = new byte[ByteQueue.INITBUFSIZE]; /** * How many bytes at the beginning of the buffer are skipped. */ private int skipped = 0; /** * How many bytes in the buffer are valid data. */ private int available = 0; /** * Read data from the buffer. * * @param buf The buffer where the read data will be copied to. * @param offset How many bytes to skip at the beginning of buf. * @param len How many bytes to read at all. * @param skip How many bytes from our data to skip. */ public void read(byte[] buf, int offset, int len, int skip) { if ((available - skip) < len) { throw new TlsRuntimeException("Not enough data to read"); } if ((buf.length - offset) < len) { throw new TlsRuntimeException("Buffer size of " + buf.length + " is too small for a read of " + len + " bytes"); } System.arraycopy(databuf, skipped + skip, buf, offset, len); return; } /** * Add some data to our buffer. * * @param data A byte-array to read data from. * @param offset How many bytes to skip at the beginning of the array. * @param len How many bytes to read from the array. */ public void addData(byte[] data, int offset, int len) { if ((skipped + available + len) > databuf.length) { byte[] tmp = new byte[ByteQueue.nextTwoPow(data.length)]; System.arraycopy(databuf, skipped, tmp, 0, available); skipped = 0; databuf = tmp; } System.arraycopy(data, offset, databuf, skipped + available, len); available += len; } /** * Remove some bytes from our data from the beginning. * * @param i How many bytes to remove. */ public void removeData(int i) { if (i > available) { throw new TlsRuntimeException("Cannot remove " + i + " bytes, only got " + available); } /* * Skip the data. */ available -= i; skipped += i; /* * If more than half of our data is skipped, we will move the data in the buffer. */ if (skipped > (databuf.length / 2)) { System.arraycopy(databuf, skipped, databuf, 0, available); skipped = 0; } } /** * @return The number of bytes which are available in this buffer. */ public int size() { return available; } }
Chandrashar/jradius
extended/src/main/java/net/jradius/tls/ByteQueue.java
Java
lgpl-2.1
3,330
#include "myglwidget.h" //粒子系统: //你是否希望创建爆炸,喷泉,流星之类的效果。这一课将告诉你如何创建一个简单的粒子系统,并用它来创建一种喷射的效果。 //欢迎来到第十九课.你已经学习了很多知识,并且现在想自己来实践.我将在这讲解一个新命令... 三角形带(我的理解就是画很多三角形来组合成我们要的形状), //它非常容易使用,当画很多三角形的时候能加快你程序的运行速度.在本课中,我将会教你该如何做一个半复杂的微粒程序.一旦您了解微粒程序的原理后, //在创建例如:火,烟,喷泉等效果将是很轻松的事情.我必须警告你!直到今天我从未写一个真正的粒子程序.我想写一个"出名"的复杂的粒子程序.我尝试过, //但在我了解我不能控制所有点变疯狂之后我放弃了!!!你也许不相信我要告诉你的,但这个课程从头到尾都是我自己的想法.开始我没有一点想法,并且没有 //任何技术数据放在我的面前.我开始考虑粒子,突然我的脑袋装满想法(脑袋开启了??):给予每个粒子生命,任意变化颜色,速度,重力影响等等.来适应环境的 //变化,把每个粒子看成单一的从这个点运动到另一个点的颗粒.很快我完成了这个项目.我看看时钟然后有个想法突然出现.四个小时过去了!我偶尔记得已经 //停止喝咖啡,眨眼,但是4个小时...?尽管这个程序我觉得很棒,并象我想象的那么严密的运行,但它不可能是最好的粒子引擎,这个我不关心,只要他运行好 //就可以.并且我能把它运行在我的项目中.如果你是那种想了解透彻的人,那么你要花费很多时间在网络上查找资料并弄明白它.在程序中有很多小的代码会 //看起来很模糊:)本课教程所用的部分代码来自于Lesson1.但有很多新的代码,因此我将重写一些发生代码变化的部分(使它更容易了解). //在颜色数组上我们减少一些代码来存储12中不同的颜色.对每一个颜色从0到11我们存储亮红,亮绿,和亮蓝. //下面的颜色表里包含12个渐变颜色从红色到紫罗兰色 static GLfloat colors[12][3]= // 彩虹颜色 { {1.0f,0.5f,0.5f},{1.0f,0.75f,0.5f},{1.0f,1.0f,0.5f},{0.75f,1.0f,0.5f}, {0.5f,1.0f,0.5f},{0.5f,1.0f,0.75f},{0.5f,1.0f,1.0f},{0.5f,0.75f,1.0f}, {0.5f,0.5f,1.0f},{0.75f,0.5f,1.0f},{1.0f,0.5f,1.0f},{1.0f,0.5f,0.75f} }; MyGLWidget::MyGLWidget(QWidget *parent) : QGLWidget(parent), m_show_full_screen(false), m_rainbow(true), m_slowdown(2.0f), m_zoom(-40.0f), m_xspeed(0.0f), m_yspeed(0.0f), m_delay(0), m_col(0) { showNormal(); startTimer(10); } MyGLWidget::~MyGLWidget() { glDeleteTextures(1, &m_texture[0]); } //在resizeGL()之前,我们增加了下面这一段代码。 //这段代码用来加载位图文件。如果文件不存在,返回 NULL 告知程序无法加载位图。在 //我开始解释这段代码之前,关于用作纹理的图像我想有几点十分重要,并且您必须明白。 //此图像的宽和高必须是2的n次方;宽度和高度最小必须是64象素;并且出于兼容性的原因,图像的宽度和高度不应超过256象素。 //如果您的原始素材的宽度和高度不是64,128,256象素的话,使用图像处理软件重新改变图像的大小。 //可以肯定有办法能绕过这些限制,但现在我们只需要用标准的纹理尺寸。 void MyGLWidget::resizeGL(int w, int h) { if(h == 0)// 防止被零除 { h = 1;// 将高设为1 } glViewport(0, 0, w, h); //重置当前的视口 //下面几行为透视图设置屏幕。意味着越远的东西看起来越小。这么做创建了一个现实外观的场景。 //此处透视按照基于窗口宽度和高度的45度视角来计算。0.1f,100.0f是我们在场景中所能绘制深度的起点和终点。 //glMatrixMode(GL_PROJECTION)指明接下来的两行代码将影响projection matrix(投影矩阵)。 //投影矩阵负责为我们的场景增加透视。 glLoadIdentity()近似于重置。它将所选的矩阵状态恢复成其原始状态。 //调用glLoadIdentity()之后我们为场景设置透视图。 //glMatrixMode(GL_MODELVIEW)指明任何新的变换将会影响 modelview matrix(模型观察矩阵)。 //模型观察矩阵中存放了我们的物体讯息。最后我们重置模型观察矩阵。如果您还不能理解这些术语的含义,请别着急。 //在以后的教程里,我会向大家解释。只要知道如果您想获得一个精彩的透视场景的话,必须这么做。 glMatrixMode(GL_PROJECTION);// 选择投影矩阵 glLoadIdentity();// 重置投影矩阵 //设置视口的大小 gluPerspective(45.0f,(GLfloat)w/(GLfloat)h,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); //选择模型观察矩阵 glLoadIdentity(); // 重置模型观察矩阵 } //我们使用光滑的阴影,清除背景为黑色,关闭深度测试,绑定并映射纹理.启用映射位图后我们选择粒子纹理。唯一的改变就是禁用深度测试和初始化粒子 void MyGLWidget::initializeGL() { loadGLTexture(); glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f,0.0f,0.0f,0.0f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glDisable(GL_DEPTH_TEST); // Disable Depth Testing glEnable(GL_BLEND); // Enable Blending glBlendFunc(GL_SRC_ALPHA,GL_ONE); // Type Of Blending To Perform glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); // Really Nice Perspective Calculations glHint(GL_POINT_SMOOTH_HINT,GL_NICEST); // Really Nice Point Smoothing glEnable(GL_TEXTURE_2D); // Enable Texture Mapping glBindTexture(GL_TEXTURE_2D,m_texture[0]); //下面代码初始化每个粒子.我们从活跃的粒子开始.如果粒子不活跃,它在荧屏上将不出现,无论它有多少life. //当我们使粒子活跃之後,我们给它life.我怀疑给粒子生命和颜色渐变的是否是最好的方法,但当它运行一次后,效果很好! //life满值是1.0f.这也给粒子完整的光亮. for (int i = 0, iend = MAX_PARTICLES; i < iend;i++) //初始化所有的粒子 { particle[i].active=true; // 使所有的粒子为激活状态 particle[i].life=1.0f; // 所有的粒子生命值为最大 //我们通过给定的值来设定粒子退色快慢.每次粒子被拉的时候life随着fade而减小. //结束的数值将是0~99中的任意一个,然后平分1000份来得到一个很小的浮点数.最后我们把结果加上0.003f来使fade速度值不为0 particle[i].fade=float(qrand()%100)/1000.0f+0.003f; // 随机生成衰减速率 //既然粒子是活跃的,而且我们又给它生命,下面将给它颜色数值.一开始,我们就想每个粒子有不同的颜色. //我怎么做才能使每个粒子与前面颜色箱里的颜色一一对应那?数学很简单,我们用i变量乘以箱子中颜色的数目与粒子 //最大值(MAX_PARTICLES)的余数.这样防止最后的颜色数值大于最大的颜色数值(12).举例:900*(12/900)=12.1000*(12/1000)=12,等等 particle[i].r=colors[i*(12/MAX_PARTICLES)][0]; // 粒子的红色颜色 particle[i].g=colors[i*(12/MAX_PARTICLES)][1]; // 粒子的绿色颜色 particle[i].b=colors[i*(12/MAX_PARTICLES)][2]; // 粒子的蓝色颜色 //现在设定每个粒子移动的方向和速度.我们通过将结果乘于10.0f来创造开始时的爆炸效果.我们将会以任意一个正或负值结束. //这个数值将以任意速度,任意方向移动粒子. particle[i].xi=float((qrand()%50)-26.0f)*10.0f; // 随机生成X轴方向速度 particle[i].yi=float((qrand()%50)-25.0f)*10.0f; // 随机生成Y轴方向速度 particle[i].zi=float((qrand()%50)-25.0f)*10.0f; // 随机生成Z轴方向速度 //最后,我们设定加速度的数值.不像一般的加速度仅仅把事物拉下,我们的加速度能拉出,拉下,拉左,拉右,拉前和拉后粒子. //开始我们需要强大的向下加速度.为了达到这样的效果我们将xg设为0.0f.在x方向没有拉力.我们设yg为-0.8f来产生一个向下的拉力. //如果值为正则拉向上.我们不希望粒子拉近或远离我们,所以将zg设为0.0f particle[i].xg=0.0f; // 设置X轴方向加速度为0 particle[i].yg=-0.8f; // 设置Y轴方向加速度为-0.8 particle[i].zg=0.0f; // 设置Z轴方向加速度为0 } } //现在为有趣的部分.下面的部分是我们从哪里拉粒子,检查加速度等等.你要明白它是怎么实现的,因此仔细的看:)我们重置Modelview巨阵. //在画粒子位置的时候用glVertex3f()命令来代替tranlations,这样在我们画粒子的时候不会改变modelview巨阵 void MyGLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 以黑色背景清楚 glLoadIdentity(); // 重置模型变换矩阵 //我们开始创建一个循环.这个环将会更新每一个粒子. for (int i = 0, iend = MAX_PARTICLES;i<iend;i++) // 循环所有的粒子 { //首先我们做的事物是检查粒子是否活跃.如果不活跃,则不被更新.在这个程序中,它们始终活跃.但是在你自己的程序中,你可能想要使某粒子不活跃 { if(particle[i].active) // 如果粒子为激活的 { //下面三个变量是我们确定x,y和z位置的暂时变量.注意:在z的位置上我们加上zoom以便我们的场景在以前的基础上再移入zoom个位置. //particle[i].x告诉我们要画的x的位置.particle[i].y告诉我们要画的y的位置.particle[i]. //z告诉我们要画的z的位置 float x = particle[i].x; // 返回X轴的位置 float y = particle[i].y; // 返回Y轴的位置 float z = particle[i].z+m_zoom; // 返回Z轴的位置 //既然知道粒子位置,就能给粒子上色.particle[i].r保存粒子的亮红,particle[i]. //g保存粒子的亮绿,particle[i].b保存粒子的亮蓝.注意我用alpha为粒子生命.当粒子要燃尽时, //它会越来越透明直到它最后消失.这就是为什么粒子的生命不应该超过1.0f.如果你想粒子燃烧时间长,可降低fade减小的速度 // 设置粒子颜色 glColor4f(particle[i].r,particle[i].g,particle[i].b,particle[i].life); //我们有粒子的位置,并设置颜色了.所以现在我们来画我们的粒子.我们用一个三角形带来代替一个四边形这样使程序运行快一点. //很多3D card画三角形带比画四边形要快的多.有些3D card将四边形分成两个三角形,而有些不. //所以我们按照我们自己的想法来,所以我们来画一个生动的三角形带 glBegin(GL_TRIANGLE_STRIP); // 绘制三角形带 //从红宝书引述:三角形带就是画一连续的三角形(三个边的多角形)使用vertices V0,V1,V2,然后V2,V1,V3(注意顺序), //然后V2,V3,V4等等.画三角形的顺序一样才能保证三角形带为相同的表面.要求方向是很重要的, //例如:剔除,最少用三点来画当第一个三角形使用vertices0,1和2被画. //如果你看图片你将会理解用顶点0,1和2构造第一个三角形(顶端右边,顶端左边,底部的右边). //第二个三角形用点vertices2,1和3构造.再一次,如果你注意图片,点vertices2, //1和3构造第二个三角形(底部右边,顶端左边,底部左边).注意:两个三角形画点顺序相同. //我看到很多的网站要求第二个三角形反方向画.这是不对的.Opengl从新整理顶点来保证所有的三角形为同一方向! //注意:你在屏幕上看见的三角形个数是你叙述的顶点的个数减2.在程序中在我们有4个顶点,所以我们看见二个三角形 glTexCoord2d(1,1); glVertex3f(x+0.5f,y+0.5f,z); glTexCoord2d(0,1); glVertex3f(x-0.5f,y+0.5f,z); glTexCoord2d(1,0); glVertex3f(x+0.5f,y-0.5f,z); glTexCoord2d(0,0); glVertex3f(x-0.5f,y-0.5f,z); //最后我们告诉Opengl我们画完三角形带 glEnd(); } } } } void MyGLWidget::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_F2: { m_show_full_screen = !m_show_full_screen; if(m_show_full_screen) { showFullScreen(); } else { showNormal(); } updateGL(); break; } case Qt::Key_Escape: { qApp->exit(); break; } case Qt::Key_Up: { //下行描述加速度的数值是多少.通过上箭头键,我们增加yg(y 地心引力)值.这引起向上的力. //如果这个程序在循环外面,那么我们必须生成另一个循环做相同的工作,因此我们最好放在这里 for (int i = 0, iend = MAX_PARTICLES; i < iend;i++) // 循环所有的粒子 { if(particle[i].active) { if(particle[i].yg < 1.5f) { particle[i].yg+=0.01f; } } } break; } case Qt::Key_Down: { //这行是产生相反的效果.通过下箭头号键,减小yg值,引起向下的力 //下行描述加速度的数值是多少.通过上箭头键,我们增加yg(y 地心引力)值.这引起向上的力. //如果这个程序在循环外面,那么我们必须生成另一个循环做相同的工作,因此我们最好放在这里 for (int i = 0, iend = MAX_PARTICLES; i < iend;i++) // 循环所有的粒子 { if(particle[i].active) { if(particle[i].yg > -1.5f) { particle[i].yg-=0.01f; } } } break; } case Qt::Key_Right: { //现在更改向右的拉力.如果按下右箭头键时增加向右的拉力. for (int i = 0, iend = MAX_PARTICLES; i < iend;i++) // 循环所有的粒子 { if(particle[i].active) { if(particle[i].xg < 1.5f) { particle[i].xg+=0.01f; } } } break; } case Qt::Key_Left: { //最后如果左箭头键被按下则增加向左的拉力.这些按键给了我们很酷的结果. //举例来说:你可以用粒子造一条向上设的水流.通过增加向下的引力可以形成泉水 for (int i = 0, iend = MAX_PARTICLES; i < iend;i++) // 循环所有的粒子 { if(particle[i].active) { if(particle[i].xg > -1.5f) { particle[i].xg-=0.01f; } } } break; } case Qt::Key_Tab: { //我仅仅为乐趣增加了一些代码.我的兄弟产生很棒的效果:)通过按住tab键所有粒子都回到屏幕中心. //所有的粒子在从新开始运动,再产生一个大的爆发.在粒子变弱之后,你最初的效果会再一次出现 for (int i = 0, iend = MAX_PARTICLES; i < iend;i++) // 循环所有的粒子 { particle[i].x=0.0f; particle[i].y=0.0f; particle[i].z=0.0f; particle[i].xi=float((qrand()%50)-26.0f)*10.0f; // 随机生成速度 particle[i].yi=float((qrand()%50)-25.0f)*10.0f; particle[i].zi=float((qrand()%50)-25.0f)*10.0f; } break; } case Qt::Key_BracketRight: { //下面的代码检查"]"是否被按下.如果它和slowdown一起实现则slowdown减少0.01f.粒子就可以较快速地移动. if(m_slowdown > 1.0f) { m_slowdown-=0.1f; } break; } case Qt::Key_BracketLeft: { //下面的代码检查"["是否被按下.如果它和slowdown一起实现则slowdown增加0.01f. //粒子就可以较慢速地移动.我实质的极限是4.0f,我不想它太慢的运动,你可以随你的要求改变最大最小值 if(m_slowdown < 4.0f) { m_slowdown+=0.1f; } break; } case Qt::Key_PageUp: { //下面的代码检测Page Up是否被按下.如果是,则zoom增加.从而导致粒子靠近我们 m_zoom+=1.0f; break; } case Qt::Key_PageDown: { //下行代码检测Page Down是否别按下,如果是,则zoom减小.从而导致粒子离开我们 m_zoom-=1.0f; break; } case Qt::Key_Return: { //下面的代码检验enter键是否被按下.如果是,并且没有被一直按着,我们将让计算机把rp变为true, //然后我们固定彩虹模式.如果彩虹模式为true,将其变成false.如果为false,将其变成true. m_rainbow = !m_rainbow; break; } case Qt::Key_Space: { //下面行是为了当space按下则彩虹关掉而设置的.如果我们不关掉彩虹模式,颜色会继续变化直到enter再被按下. //也就是说人们按下space来代替enter是想叫粒子颜色自己变化 m_rainbow = false; m_delay = 0; //如果颜色值大于11,我们把它重新设为零.如果我们不重新设定为零,程序将去找第13颜色. //而我们只有12种颜色!寻找不存在的颜色将会导致程序瘫痪 m_col++; if(m_col > 11) { m_col = 0; } break; } case Qt::Key_W: { //现在对粒子增加一些控制.还记得我们从开始定义的2变量么?一个xspeed,一个yspeed.在粒子燃尽之后, //我们给它新的移动速度且把新的速度加入到xspeed和yspeed中.这样当粒子被创建时将影响粒子的速度. //举例来说:粒子在x轴上的速度为5在y轴上的速度为0.当我们减少xspeed到-10,我们将以-10(xspeed)+5(最初的移动速度)的速度移动. //这样我们将以5的速度向左移动.明白了么??无论如何,下面的代码检测W是否被按下. //如果它,yspeed将增加这将引起粒子向上运动.最大速度不超过200.速度在快就不好看了 if(m_yspeed < 200) { m_yspeed+=10.0f; } break; } case Qt::Key_S: { //这行检查S键是否被按下,如果它是,yspeed将减少.这将引起粒子向下运动.再一次,最大速度为200 if(m_yspeed > -200) { m_yspeed-=10.0f; } break; } case Qt::Key_D: { //现在我们检查A键是否被按下.如果它是..xspeed将被增加.粒子将移到右边.最大速度为200 if(m_xspeed < 200) { m_xspeed+=10.0f; } break; } case Qt::Key_A: { if(m_xspeed > -200) { m_xspeed-=10.0f; } break; } } QGLWidget::keyPressEvent(event); } void MyGLWidget::timerEvent(QTimerEvent *event) { for (int i = 0, iend = MAX_PARTICLES;i<iend;i++) // 循环所有的粒子 { //首先我们做的事物是检查粒子是否活跃.如果不活跃,则不被更新.在这个程序中,它们始终活跃.但是在你自己的程序中,你可能想要使某粒子不活跃 { if(particle[i].active) // 如果粒子为激活的 { //现在我们能移动粒子.下面公式可能看起来很奇怪,其实很简单.首先我们取得当前粒子的x位置. //然后把x运动速度加上粒子被减速1000倍后的值.所以如果粒子在x轴(0)上屏幕中心的位置, //运动值(xi)为x轴方向+10(移动我们为右),而slowdown等于1,我们移向右边以10/(1*1000)或 0.01f速度. //如果增加slowdown值到2我们只移动0.005f.希望能帮助你了解slowdown如何工作. //那也是为什么用10.0f乘开始值来叫象素移动快速,创造一个爆发效果.y和z轴用相同的公式来计算附近移动粒子 particle[i].x+=particle[i].xi/(m_slowdown*1000); // 更新X坐标的位置 particle[i].y+=particle[i].yi/(m_slowdown*1000); // 更新Y坐标的位置 particle[i].z+=particle[i].zi/(m_slowdown*1000); // 更新Z坐标的位置 //在计算出下一步粒子移到那里,开始考虑重力和阻力.在下面的第一行,将阻力(xg)和移动速度(xi)相加. //我们的移动速度是10和阻力是1.每时每刻粒子都在抵抗阻力.第二次画粒子时,阻力开始作用,移动速度将会从10掉到9. //第三次画粒子时,阻力再一次作用,移动速度降低到8.如果粒子燃烧为超过10次重画,它将会最后结束,并向相反方向移动. //因为移动速度会变成负值.阻力同样使用于y和z移动速度 particle[i].xi+=particle[i].xg; // 更新X轴方向速度大小 particle[i].yi+=particle[i].yg; // 更新Y轴方向速度大小 particle[i].zi+=particle[i].zg; // 更新Z轴方向速度大小 //下行将粒子的生命减少.如果我们不这么做,粒子无法烧尽.我们用粒子当前的life减去当前的fade值. //每粒子都有不同的fade值,因此他们全部将会以不同的速度烧尽 particle[i].life-=particle[i].fade; // 减少粒子的生命值 //现在我们检查当生命为零的话粒子是否活着 if(particle[i].life<0.0f) // 如果粒子生命值小于0 { //如果粒子是小时(烧尽),我们将会使它复原.我们给它全值生命和新的衰弱速度. particle[i].life=1.0f; // 产生一个新的粒子 particle[i].fade=float(qrand()%100)/1000.0f+0.003f; // 随机生成衰减速率 //我们也重新设定粒子在屏幕中心放置.我们重新设定粒子的x,y和z位置为零 particle[i].x=0.0f; // 新粒子出现在屏幕的中央 particle[i].y=0.0f; particle[i].z=0.0f; //在粒子从新设置之后,将给它新的移动速度/方向.注意:我增加最大和最小值,粒子移动速度为从50到60的任意值, //但是这次我们没将移动速度乘10.我们这次不想要一个爆发的效果,而要比较慢地移动粒子.也注意我把xspeed和x轴移动速度相加, //y轴移动速度和yspeed相加.这个控制粒子的移动方向. particle[i].xi=m_xspeed+float((qrand()%60)-32.0f); // 随机生成粒子速度 particle[i].yi=m_yspeed+float((qrand()%60)-30.0f); particle[i].zi=float((qrand()%60)-30.0f); //最后我们分配粒子一种新的颜色.变量col保存一个数字从1到11(12种颜色),我们用这个变量去找红,绿,蓝亮度在颜色箱里面. //下面第一行表示红色的强度,数值保存在colors[col][0].所以如果col是0,红色的亮度就是1.0f. //绿色的和蓝色的值用相同的方法读取.如果你不了解为什么红色亮度为1.0f那col就为0.我将一点点的解释. //看着程序的最前面.找到那行:static GLfloat colors[12][3]. //注意:12行3列.三个数字的第一行是红色强度.第二行是绿色强度而且第三行是蓝色强度.[0],[1]和[2]下面描述的1st,2nd和3rd //就是我刚提及的.如果col等于0,我们要看第一个组.11 是最後一个组(第12种颜色). particle[i].r=colors[m_col][0]; // 设置粒子颜色 particle[i].g=colors[m_col][1]; particle[i].b=colors[m_col][2]; } } } } if(m_rainbow && m_delay > 25) { //如果颜色值大于11,我们把它重新设为零.如果我们不重新设定为零,程序将去找第13颜色. //而我们只有12种颜色!寻找不存在的颜色将会导致程序瘫痪 m_col++; if(m_col > 11) { m_col = 0; } } m_delay++; updateGL(); QGLWidget::timerEvent(event); } void MyGLWidget::loadGLTexture() { //现在载入图像,并将其转换为纹理。 QImage image(":/image/Particle.bmp"); image = image.convertToFormat(QImage::Format_RGB888); image = image.mirrored(); glGenTextures(1, &m_texture[0]);// 创建纹理 // 使用来自位图数据生成 的典型纹理 glBindTexture(GL_TEXTURE_2D, m_texture[0]); //下来我们创建真正的纹理。下面一行告诉OpenGL此纹理是一个2D纹理 ( GL_TEXTURE_2D )。 //参数“0”代表图像的详细程度,通常就由它为零去了。参数三是数据的成分数。 //因为图像是由红色数据,绿色数据,蓝色数据三种组分组成。 TextureImage[0]->sizeX 是纹理的宽度。 //如果您知道宽度,您可以在这里填入,但计算机可以很容易的为您指出此值。 //TextureImage[0]->sizey 是纹理的高度。参数零是边框的值,一般就是“0”。 //GL_RGB 告诉OpenGL图像数据由红、绿、蓝三色数据组成。 //GL_UNSIGNED_BYTE 意味着组成图像的数据是无符号字节类型的。 //最后... TextureImage[0]->data 告诉OpenGL纹理数据的来源。此例中指向存放在 TextureImage[0] 记录中的数据。 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width(), image.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, image.bits()); //下面的两行告诉OpenGL在显示图像时, //当它比放大得原始的纹理大 ( GL_TEXTURE_MAG_FILTER )或缩小得比原始得纹理小( GL_TEXTURE_MIN_FILTER )时 //OpenGL采用的滤波方式。通常这两种情况下我都采用 GL_LINEAR 。 //这使得纹理从很远处到离屏幕很近时都平滑显示。使用 GL_LINEAR 需要CPU和显卡做更多的运算。 //如果您的机器很慢,您也许应该采用 GL_NEAREST 。过滤的纹理在放大的时候,看起来斑驳的很『译者注:马赛克啦』。 //您也可以结合这两种滤波方式。在近处时使用 GL_LINEAR ,远处时 GL_NEAREST 。 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // 线形滤波 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // 线形滤波 } //在课程中,我试着把所有细节都讲清楚,并且简单的了解粒子系统.这个粒子系统能在游戏产生例如火,水,雪,爆炸,流行等效果. //程序能简单的修改参数来实现新的效果(例:烟花效果)
chenzilin/qt-opengl
Lesson19_TriangleStripAndParticleEngine/myglwidget.cpp
C++
lgpl-2.1
28,352
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Message.h * Holds the data for a message. * Copyright (C) 2011 Simon Newton */ #ifndef INCLUDE_OLA_MESSAGING_MESSAGE_H_ #define INCLUDE_OLA_MESSAGING_MESSAGE_H_ #include <ola/messaging/Descriptor.h> #include <ola/messaging/MessageVisitor.h> #include <ola/network/IPV4Address.h> #include <ola/rdm/UID.h> #include <string> #include <vector> using std::string; using std::vector; namespace ola { namespace messaging { class MessageVisitor; class Message { public: explicit Message(const vector<const class MessageFieldInterface*> &fields) : m_fields(fields) { } ~Message(); void Accept(MessageVisitor *visitor) const; unsigned int FieldCount() const { return m_fields.size(); } private: vector<const class MessageFieldInterface*> m_fields; }; /** * The Interface for a MessageField. */ class MessageFieldInterface { public: virtual ~MessageFieldInterface() {} // Call back into a MessageVisitor virtual void Accept(MessageVisitor *visitor) const = 0; }; /** * A MessageField that represents a bool */ class BoolMessageField: public MessageFieldInterface { public: BoolMessageField(const BoolFieldDescriptor *descriptor, bool value) : m_descriptor(descriptor), m_value(value) { } const BoolFieldDescriptor *GetDescriptor() const { return m_descriptor; } bool Value() const { return m_value; } void Accept(MessageVisitor *visitor) const { visitor->Visit(this); } private: const BoolFieldDescriptor *m_descriptor; bool m_value; }; /** * A MessageField that represents a IPv4 Address */ class IPV4MessageField: public MessageFieldInterface { public: IPV4MessageField(const IPV4FieldDescriptor *descriptor, const ola::network::IPV4Address &value) : m_descriptor(descriptor), m_value(value) { } IPV4MessageField(const IPV4FieldDescriptor *descriptor, uint32_t value) : m_descriptor(descriptor), m_value(ola::network::IPV4Address(value)) { } const IPV4FieldDescriptor *GetDescriptor() const { return m_descriptor; } ola::network::IPV4Address Value() const { return m_value; } void Accept(MessageVisitor *visitor) const { visitor->Visit(this); } private: const IPV4FieldDescriptor *m_descriptor; ola::network::IPV4Address m_value; }; /** * A MessageField that represents a UID. */ class UIDMessageField: public MessageFieldInterface { public: UIDMessageField(const UIDFieldDescriptor *descriptor, const ola::rdm::UID &uid) : m_descriptor(descriptor), m_uid(uid) { } const UIDFieldDescriptor *GetDescriptor() const { return m_descriptor; } const ola::rdm::UID& Value() const { return m_uid; } void Accept(MessageVisitor *visitor) const { visitor->Visit(this); } private: const UIDFieldDescriptor *m_descriptor; ola::rdm::UID m_uid; }; /** * A MessageField that represents a string */ class StringMessageField: public MessageFieldInterface { public: StringMessageField(const StringFieldDescriptor *descriptor, const string &value) : m_descriptor(descriptor), m_value(value) { } const StringFieldDescriptor *GetDescriptor() const { return m_descriptor; } const string& Value() const { return m_value; } void Accept(MessageVisitor *visitor) const { visitor->Visit(this); } private: const StringFieldDescriptor *m_descriptor; const string m_value; }; /** * A MessageField that represents an simple type */ template <typename type> class BasicMessageField: public MessageFieldInterface { public: BasicMessageField(const IntegerFieldDescriptor<type> *descriptor, type value) : m_descriptor(descriptor), m_value(value) { } const IntegerFieldDescriptor<type> *GetDescriptor() const { return m_descriptor; } type Value() const { return m_value; } void Accept(MessageVisitor *visitor) const { visitor->Visit(this); } private: const IntegerFieldDescriptor<type> *m_descriptor; type m_value; }; typedef BasicMessageField<uint8_t> UInt8MessageField; typedef BasicMessageField<uint16_t> UInt16MessageField; typedef BasicMessageField<uint32_t> UInt32MessageField; typedef BasicMessageField<int8_t> Int8MessageField; typedef BasicMessageField<int16_t> Int16MessageField; typedef BasicMessageField<int32_t> Int32MessageField; /** * A MessageField that consists of a group of fields */ class GroupMessageField: public MessageFieldInterface { public: GroupMessageField(const FieldDescriptorGroup *descriptor, const vector<const class MessageFieldInterface*> &fields) : m_descriptor(descriptor), m_fields(fields) { } ~GroupMessageField(); const FieldDescriptorGroup *GetDescriptor() const { return m_descriptor; } unsigned int FieldCount() const { return m_fields.size(); } const class MessageFieldInterface *GetField(unsigned int index) const { if (index < m_fields.size()) return m_fields[index]; return NULL; } void Accept(MessageVisitor *visitor) const; private: const FieldDescriptorGroup *m_descriptor; vector<const class MessageFieldInterface*> m_fields; }; } // namespace messaging } // namespace ola #endif // INCLUDE_OLA_MESSAGING_MESSAGE_H_
mlba-team/open-lighting
include/ola/messaging/Message.h
C
lgpl-2.1
6,281
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtXml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qxml.h" #include "qtextcodec.h" #include "qbuffer.h" #include "qregexp.h" #include "qmap.h" #include "qhash.h" #include "qstack.h" #include <qdebug.h> #ifdef Q_CC_BOR // borland 6 finds bogus warnings when building this file in uic3 # pragma warn -8080 #endif //#define QT_QXML_DEBUG // Error strings for the XML reader #define XMLERR_OK QT_TRANSLATE_NOOP("QXml", "no error occurred") #define XMLERR_ERRORBYCONSUMER QT_TRANSLATE_NOOP("QXml", "error triggered by consumer") #define XMLERR_UNEXPECTEDEOF QT_TRANSLATE_NOOP("QXml", "unexpected end of file") #define XMLERR_MORETHANONEDOCTYPE QT_TRANSLATE_NOOP("QXml", "more than one document type definition") #define XMLERR_ERRORPARSINGELEMENT QT_TRANSLATE_NOOP("QXml", "error occurred while parsing element") #define XMLERR_TAGMISMATCH QT_TRANSLATE_NOOP("QXml", "tag mismatch") #define XMLERR_ERRORPARSINGCONTENT QT_TRANSLATE_NOOP("QXml", "error occurred while parsing content") #define XMLERR_UNEXPECTEDCHARACTER QT_TRANSLATE_NOOP("QXml", "unexpected character") #define XMLERR_INVALIDNAMEFORPI QT_TRANSLATE_NOOP("QXml", "invalid name for processing instruction") #define XMLERR_VERSIONEXPECTED QT_TRANSLATE_NOOP("QXml", "version expected while reading the XML declaration") #define XMLERR_WRONGVALUEFORSDECL QT_TRANSLATE_NOOP("QXml", "wrong value for standalone declaration") #define XMLERR_EDECLORSDDECLEXPECTED QT_TRANSLATE_NOOP("QXml", "encoding declaration or standalone declaration expected while reading the XML declaration") #define XMLERR_SDDECLEXPECTED QT_TRANSLATE_NOOP("QXml", "standalone declaration expected while reading the XML declaration") #define XMLERR_ERRORPARSINGDOCTYPE QT_TRANSLATE_NOOP("QXml", "error occurred while parsing document type definition") #define XMLERR_LETTEREXPECTED QT_TRANSLATE_NOOP("QXml", "letter is expected") #define XMLERR_ERRORPARSINGCOMMENT QT_TRANSLATE_NOOP("QXml", "error occurred while parsing comment") #define XMLERR_ERRORPARSINGREFERENCE QT_TRANSLATE_NOOP("QXml", "error occurred while parsing reference") #define XMLERR_INTERNALGENERALENTITYINDTD QT_TRANSLATE_NOOP("QXml", "internal general entity reference not allowed in DTD") #define XMLERR_EXTERNALGENERALENTITYINAV QT_TRANSLATE_NOOP("QXml", "external parsed general entity reference not allowed in attribute value") #define XMLERR_EXTERNALGENERALENTITYINDTD QT_TRANSLATE_NOOP("QXml", "external parsed general entity reference not allowed in DTD") #define XMLERR_UNPARSEDENTITYREFERENCE QT_TRANSLATE_NOOP("QXml", "unparsed entity reference in wrong context") #define XMLERR_RECURSIVEENTITIES QT_TRANSLATE_NOOP("QXml", "recursive entities") #define XMLERR_ERRORINTEXTDECL QT_TRANSLATE_NOOP("QXml", "error in the text declaration of an external entity") QT_BEGIN_NAMESPACE // the constants for the lookup table static const signed char cltWS = 0; // white space static const signed char cltPer = 1; // % static const signed char cltAmp = 2; // & static const signed char cltGt = 3; // > static const signed char cltLt = 4; // < static const signed char cltSlash = 5; // / static const signed char cltQm = 6; // ? static const signed char cltEm = 7; // ! static const signed char cltDash = 8; // - static const signed char cltCB = 9; // ] static const signed char cltOB = 10; // [ static const signed char cltEq = 11; // = static const signed char cltDq = 12; // " static const signed char cltSq = 13; // ' static const signed char cltUnknown = 14; // Hack for letting QDom know where the skipped entity occurred // ### the use of this variable means the code isn't reentrant. bool qt_xml_skipped_entity_in_content; // character lookup table static const signed char charLookupTable[256]={ cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x00 - 0x07 cltUnknown, // 0x08 cltWS, // 0x09 \t cltWS, // 0x0A \n cltUnknown, // 0x0B cltUnknown, // 0x0C cltWS, // 0x0D \r cltUnknown, // 0x0E cltUnknown, // 0x0F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x17 - 0x16 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x18 - 0x1F cltWS, // 0x20 Space cltEm, // 0x21 ! cltDq, // 0x22 " cltUnknown, // 0x23 cltUnknown, // 0x24 cltPer, // 0x25 % cltAmp, // 0x26 & cltSq, // 0x27 ' cltUnknown, // 0x28 cltUnknown, // 0x29 cltUnknown, // 0x2A cltUnknown, // 0x2B cltUnknown, // 0x2C cltDash, // 0x2D - cltUnknown, // 0x2E cltSlash, // 0x2F / cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x30 - 0x37 cltUnknown, // 0x38 cltUnknown, // 0x39 cltUnknown, // 0x3A cltUnknown, // 0x3B cltLt, // 0x3C < cltEq, // 0x3D = cltGt, // 0x3E > cltQm, // 0x3F ? cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x40 - 0x47 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x48 - 0x4F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x50 - 0x57 cltUnknown, // 0x58 cltUnknown, // 0x59 cltUnknown, // 0x5A cltOB, // 0x5B [ cltUnknown, // 0x5C cltCB, // 0x5D] cltUnknown, // 0x5E cltUnknown, // 0x5F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x60 - 0x67 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x68 - 0x6F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x70 - 0x77 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x78 - 0x7F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x80 - 0x87 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x88 - 0x8F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x90 - 0x97 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0x98 - 0x9F cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xA0 - 0xA7 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xA8 - 0xAF cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xB0 - 0xB7 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xB8 - 0xBF cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xC0 - 0xC7 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xC8 - 0xCF cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xD0 - 0xD7 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xD8 - 0xDF cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xE0 - 0xE7 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xE8 - 0xEF cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, // 0xF0 - 0xF7 cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown, cltUnknown // 0xF8 - 0xFF }; // // local helper functions // /* This function strips the TextDecl [77] ("<?xml ...?>") from the string \a str. The stripped version is stored in \a str. If this function finds an invalid TextDecl, it returns \c false, otherwise true. This function is used for external entities since those can include an TextDecl that must be stripped before inserting the entity. */ static bool stripTextDecl(QString& str) { QString textDeclStart(QLatin1String("<?xml")); if (str.startsWith(textDeclStart)) { QRegExp textDecl(QString::fromLatin1( "^<\\?xml\\s+" "(version\\s*=\\s*((['\"])[-a-zA-Z0-9_.:]+\\3))?" "\\s*" "(encoding\\s*=\\s*((['\"])[A-Za-z][-a-zA-Z0-9_.]*\\6))?" "\\s*\\?>" )); QString strTmp = str.replace(textDecl, QLatin1String("")); if (strTmp.length() != str.length()) return false; // external entity has wrong TextDecl str = strTmp; } return true; } class QXmlAttributesPrivate { }; /* \class QXmlInputSourcePrivate \internal There's a slight misdesign in this class that can be worth to keep in mind: the `str' member is a buffer which QXmlInputSource::next() returns from, and which is populated from the input device or input stream. However, when the input is a QString(the user called QXmlInputSource::setData()), `str' has two roles: it's the buffer, but also the source. This /seems/ to be no problem because in the case of having no device or stream, the QString is read in one go. */ class QXmlInputSourcePrivate { public: QIODevice *inputDevice; QTextStream *inputStream; QString str; const QChar *unicode; int pos; int length; bool nextReturnedEndOfData; #ifndef QT_NO_TEXTCODEC QTextDecoder *encMapper; #endif QByteArray encodingDeclBytes; QString encodingDeclChars; bool lookingForEncodingDecl; }; class QXmlParseExceptionPrivate { public: QXmlParseExceptionPrivate() : column(-1), line(-1) { } QXmlParseExceptionPrivate(const QXmlParseExceptionPrivate &other) : msg(other.msg), column(other.column), line(other.line), pub(other.pub), sys(other.sys) { } QString msg; int column; int line; QString pub; QString sys; }; class QXmlLocatorPrivate { }; class QXmlDefaultHandlerPrivate { }; class QXmlSimpleReaderPrivate { public: ~QXmlSimpleReaderPrivate(); private: // functions QXmlSimpleReaderPrivate(QXmlSimpleReader *reader); void initIncrementalParsing(); // used to determine if elements are correctly nested QStack<QString> tags; // used by parseReference() and parsePEReference() enum EntityRecognitionContext { InContent, InAttributeValue, InEntityValue, InDTD }; // used for entity declarations struct ExternParameterEntity { ExternParameterEntity() {} ExternParameterEntity(const QString &p, const QString &s) : publicId(p), systemId(s) {} QString publicId; QString systemId; Q_DUMMY_COMPARISON_OPERATOR(ExternParameterEntity) }; struct ExternEntity { ExternEntity() {} ExternEntity(const QString &p, const QString &s, const QString &n) : publicId(p), systemId(s), notation(n) {} QString publicId; QString systemId; QString notation; Q_DUMMY_COMPARISON_OPERATOR(ExternEntity) }; QMap<QString,ExternParameterEntity> externParameterEntities; QMap<QString,QString> parameterEntities; QMap<QString,ExternEntity> externEntities; QMap<QString,QString> entities; // used for parsing of entity references struct XmlRef { XmlRef() : index(0) {} XmlRef(const QString &_name, const QString &_value) : name(_name), value(_value), index(0) {} bool isEmpty() const { return index == value.length(); } QChar next() { return value.at(index++); } QString name; QString value; int index; }; QStack<XmlRef> xmlRefStack; // used for standalone declaration enum Standalone { Yes, No, Unknown }; QString doctype; // only used for the doctype QString xmlVersion; // only used to store the version information QString encoding; // only used to store the encoding Standalone standalone; // used to store the value of the standalone declaration QString publicId; // used by parseExternalID() to store the public ID QString systemId; // used by parseExternalID() to store the system ID // Since publicId/systemId is used as temporary variables by parseExternalID(), it // might overwrite the PUBLIC/SYSTEM for the document we're parsing. In effect, we would // possibly send off an QXmlParseException that has the PUBLIC/SYSTEM of a entity declaration // instead of those of the current document. // Hence we have these two variables for storing the document's data. QString thisPublicId; QString thisSystemId; QString attDeclEName; // use by parseAttlistDecl() QString attDeclAName; // use by parseAttlistDecl() // flags for some features support bool useNamespaces; bool useNamespacePrefixes; bool reportWhitespaceCharData; bool reportEntities; // used to build the attribute list QXmlAttributes attList; // used in QXmlSimpleReader::parseContent() to decide whether character // data was read bool contentCharDataRead; // helper classes QScopedPointer<QXmlLocator> locator; QXmlNamespaceSupport namespaceSupport; // error string QString error; // arguments for parse functions (this is needed to allow incremental // parsing) bool parsePI_xmldecl; bool parseName_useRef; bool parseReference_charDataRead; EntityRecognitionContext parseReference_context; bool parseExternalID_allowPublicID; EntityRecognitionContext parsePEReference_context; QString parseString_s; // for incremental parsing struct ParseState { typedef bool (QXmlSimpleReaderPrivate::*ParseFunction)(); ParseFunction function; int state; }; QStack<ParseState> *parseStack; // used in parseProlog() bool xmldecl_possible; bool doctype_read; // used in parseDoctype() bool startDTDwasReported; // used in parseString() signed char Done; // variables QXmlContentHandler *contentHnd; QXmlErrorHandler *errorHnd; QXmlDTDHandler *dtdHnd; QXmlEntityResolver *entityRes; QXmlLexicalHandler *lexicalHnd; QXmlDeclHandler *declHnd; QXmlInputSource *inputSource; QChar c; // the character at reading position int lineNr; // number of line int columnNr; // position in line QChar nameArray[256]; // only used for names QString nameValue; // only used for names int nameArrayPos; int nameValueLen; QChar refArray[256]; // only used for references QString refValue; // only used for references int refArrayPos; int refValueLen; QChar stringArray[256]; // used for any other strings that are parsed QString stringValue; // used for any other strings that are parsed int stringArrayPos; int stringValueLen; QString emptyStr; QHash<QString, int> literalEntitySizes; // The entity at (QMap<QString,) referenced the entities at (QMap<QString,) (int>) times. QHash<QString, QHash<QString, int> > referencesToOtherEntities; QHash<QString, int> expandedSizes; // The limit to the amount of times the DTD parsing functions can be called // for the DTD currently being parsed. static const int dtdRecursionLimit = 2; // The maximum amount of characters an entity value may contain, after expansion. static const int entityCharacterLimit = 1024; const QString &string(); void stringClear(); void stringAddC(QChar); inline void stringAddC() { stringAddC(c); } const QString &name(); void nameClear(); void nameAddC(QChar); inline void nameAddC() { nameAddC(c); } const QString &ref(); void refClear(); void refAddC(QChar); inline void refAddC() { refAddC(c); } // private functions bool eat_ws(); bool next_eat_ws(); void QT_FASTCALL next(); bool atEnd(); void init(const QXmlInputSource* i); void initData(); bool entityExist(const QString&) const; bool parseBeginOrContinue(int state, bool incremental); bool parseProlog(); bool parseElement(); bool processElementEmptyTag(); bool processElementETagBegin2(); bool processElementAttribute(); bool parseMisc(); bool parseContent(); bool parsePI(); bool parseDoctype(); bool parseComment(); bool parseName(); bool parseNmtoken(); bool parseAttribute(); bool parseReference(); bool processReference(); bool parseExternalID(); bool parsePEReference(); bool parseMarkupdecl(); bool parseAttlistDecl(); bool parseAttType(); bool parseAttValue(); bool parseElementDecl(); bool parseNotationDecl(); bool parseChoiceSeq(); bool parseEntityDecl(); bool parseEntityValue(); bool parseString(); bool insertXmlRef(const QString&, const QString&, bool); bool reportEndEntities(); void reportParseError(const QString& error); typedef bool (QXmlSimpleReaderPrivate::*ParseFunction) (); void unexpectedEof(ParseFunction where, int state); void parseFailed(ParseFunction where, int state); void pushParseState(ParseFunction function, int state); bool isExpandedEntityValueTooLarge(QString *errorMessage); Q_DECLARE_PUBLIC(QXmlSimpleReader) QXmlSimpleReader *q_ptr; friend class QXmlSimpleReaderLocator; }; /*! \class QXmlParseException \reentrant \brief The QXmlParseException class is used to report errors with the QXmlErrorHandler interface. \inmodule QtXml \ingroup xml-tools The XML subsystem constructs an instance of this class when it detects an error. You can retrieve the place where the error occurred using systemId(), publicId(), lineNumber() and columnNumber(), along with the error message(). The possible error messages are: \list \li "no error occurred" \li "error triggered by consumer" \li "unexpected end of file" \li "more than one document type definition" \li "error occurred while parsing element" \li "tag mismatch" \li "error occurred while parsing content" \li "unexpected character" \li "invalid name for processing instruction" \li "version expected while reading the XML declaration" \li "wrong value for standalone declaration" \li "encoding declaration or standalone declaration expected while reading the XML declaration" \li "standalone declaration expected while reading the XML declaration" \li "error occurred while parsing document type definition" \li "letter is expected" \li "error occurred while parsing comment" \li "error occurred while parsing reference" \li "internal general entity reference not allowed in DTD" \li "external parsed general entity reference not allowed in attribute value" \li "external parsed general entity reference not allowed in DTD" \li "unparsed entity reference n wrong context" \li "recursive entities" \li "error in the text declaration of an external entity" \endlist Note that, if you want to display these error messages to your application's users, they will be displayed in English unless they are explicitly translated. \sa QXmlErrorHandler, QXmlReader */ /*! Constructs a parse exception with the error string \a name for column \a c and line \a l for the public identifier \a p and the system identifier \a s. */ QXmlParseException::QXmlParseException(const QString& name, int c, int l, const QString& p, const QString& s) : d(new QXmlParseExceptionPrivate) { d->msg = name; d->column = c; d->line = l; d->pub = p; d->sys = s; } /*! Creates a copy of \a other. */ QXmlParseException::QXmlParseException(const QXmlParseException& other) : d(new QXmlParseExceptionPrivate(*other.d)) { } /*! Destroys the QXmlParseException. */ QXmlParseException::~QXmlParseException() { } /*! Returns the error message. */ QString QXmlParseException::message() const { return d->msg; } /*! Returns the column number where the error occurred. */ int QXmlParseException::columnNumber() const { return d->column; } /*! Returns the line number where the error occurred. */ int QXmlParseException::lineNumber() const { return d->line; } /*! Returns the public identifier where the error occurred. */ QString QXmlParseException::publicId() const { return d->pub; } /*! Returns the system identifier where the error occurred. */ QString QXmlParseException::systemId() const { return d->sys; } /*! \class QXmlLocator \reentrant \brief The QXmlLocator class provides the XML handler classes with information about the parsing position within a file. \inmodule QtXml \ingroup xml-tools The reader reports a QXmlLocator to the content handler before it starts to parse the document. This is done with the QXmlContentHandler::setDocumentLocator() function. The handler classes can now use this locator to get the position (lineNumber() and columnNumber()) that the reader has reached. */ /*! Constructor. */ QXmlLocator::QXmlLocator() { } /*! Destructor. */ QXmlLocator::~QXmlLocator() { } /*! \fn int QXmlLocator::columnNumber() const Returns the column number (starting at 1) or -1 if there is no column number available. */ /*! \fn int QXmlLocator::lineNumber() const Returns the line number (starting at 1) or -1 if there is no line number available. */ class QXmlSimpleReaderLocator : public QXmlLocator { public: QXmlSimpleReaderLocator(QXmlSimpleReader* parent) { reader = parent; } ~QXmlSimpleReaderLocator() { } int columnNumber() const { return (reader->d_ptr->columnNr == -1 ? -1 : reader->d_ptr->columnNr + 1); } int lineNumber() const { return (reader->d_ptr->lineNr == -1 ? -1 : reader->d_ptr->lineNr + 1); } // QString getPublicId() // QString getSystemId() private: QXmlSimpleReader *reader; }; /********************************************* * * QXmlNamespaceSupport * *********************************************/ typedef QMap<QString, QString> NamespaceMap; class QXmlNamespaceSupportPrivate { public: QXmlNamespaceSupportPrivate() { ns.insert(QLatin1String("xml"), QLatin1String("http://www.w3.org/XML/1998/namespace")); // the XML namespace } ~QXmlNamespaceSupportPrivate() { } QStack<NamespaceMap> nsStack; NamespaceMap ns; }; /*! \class QXmlNamespaceSupport \since 4.4 \reentrant \brief The QXmlNamespaceSupport class is a helper class for XML readers which want to include namespace support. \inmodule QtXml \ingroup xml-tools You can set the prefix for the current namespace with setPrefix(), and get the list of current prefixes (or those for a given URI) with prefixes(). The namespace URI is available from uri(). Use pushContext() to start a new namespace context, and popContext() to return to the previous namespace context. Use splitName() or processName() to split a name into its prefix and local name. \sa {Namespace Support via Features} */ /*! Constructs a QXmlNamespaceSupport. */ QXmlNamespaceSupport::QXmlNamespaceSupport() { d = new QXmlNamespaceSupportPrivate; } /*! Destroys a QXmlNamespaceSupport. */ QXmlNamespaceSupport::~QXmlNamespaceSupport() { delete d; } /*! This function declares a prefix \a pre in the current namespace context to be the namespace URI \a uri. The prefix remains in force until this context is popped, unless it is shadowed in a descendant context. Note that there is an asymmetry in this library. prefix() does not return the default "" prefix, even if you have declared one; to check for a default prefix, you must look it up explicitly using uri(). This asymmetry exists to make it easier to look up prefixes for attribute names, where the default prefix is not allowed. */ void QXmlNamespaceSupport::setPrefix(const QString& pre, const QString& uri) { if(pre.isNull()) { d->ns.insert(QLatin1String(""), uri); } else { d->ns.insert(pre, uri); } } /*! Returns one of the prefixes mapped to the namespace URI \a uri. If more than one prefix is currently mapped to the same URI, this function makes an arbitrary selection; if you want all of the prefixes, use prefixes() instead. Note: to check for a default prefix, use the uri() function with an argument of "". */ QString QXmlNamespaceSupport::prefix(const QString& uri) const { NamespaceMap::const_iterator itc, it = d->ns.constBegin(); while ((itc=it) != d->ns.constEnd()) { ++it; if (*itc == uri && !itc.key().isEmpty()) return itc.key(); } return QLatin1String(""); } /*! Looks up the prefix \a prefix in the current context and returns the currently-mapped namespace URI. Use the empty string ("") for the default namespace. */ QString QXmlNamespaceSupport::uri(const QString& prefix) const { return d->ns[prefix]; } /*! Splits the name \a qname at the ':' and returns the prefix in \a prefix and the local name in \a localname. \sa processName() */ void QXmlNamespaceSupport::splitName(const QString& qname, QString& prefix, QString& localname) const { int pos = qname.indexOf(QLatin1Char(':')); if (pos == -1) pos = qname.size(); prefix = qname.left(pos); localname = qname.mid(pos+1); } /*! Processes a raw XML 1.0 name in the current context by removing the prefix and looking it up among the prefixes currently declared. \a qname is the raw XML 1.0 name to be processed. \a isAttribute is true if the name is an attribute name. This function stores the namespace URI in \a nsuri (which will be set to an empty string if the raw name has an undeclared prefix), and stores the local name (without prefix) in \a localname (which will be set to an empty string if no namespace is in use). Note that attribute names are processed differently than element names: an unprefixed element name gets the default namespace (if any), while an unprefixed attribute name does not. */ void QXmlNamespaceSupport::processName(const QString& qname, bool isAttribute, QString& nsuri, QString& localname) const { int len = qname.size(); const QChar *data = qname.constData(); for (int pos = 0; pos < len; ++pos) { if (data[pos] == QLatin1Char(':')) { nsuri = uri(qname.left(pos)); localname = qname.mid(pos + 1); return; } } // there was no ':' nsuri.clear(); // attributes don't take default namespace if (!isAttribute && !d->ns.isEmpty()) { /* We want to access d->ns.value(""), but as an optimization we use the fact that "" compares less than any other string, so it's either first in the map or not there. */ NamespaceMap::const_iterator first = d->ns.constBegin(); if (first.key().isEmpty()) nsuri = first.value(); // get default namespace } localname = qname; } /*! Returns a list of all the prefixes currently declared. If there is a default prefix, this function does not return it in the list; check for the default prefix using uri() with an argument of "". */ QStringList QXmlNamespaceSupport::prefixes() const { QStringList list; NamespaceMap::const_iterator itc, it = d->ns.constBegin(); while ((itc=it) != d->ns.constEnd()) { ++it; if (!itc.key().isEmpty()) list.append(itc.key()); } return list; } /*! \overload Returns a list of all prefixes currently declared for the namespace URI \a uri. The "xml:" prefix is included. If you only want one prefix that is mapped to the namespace URI, and you don't care which one you get, use the prefix() function instead. Note: The empty (default) prefix is never included in this list; to check for the presence of a default namespace, call uri() with "" as the argument. */ QStringList QXmlNamespaceSupport::prefixes(const QString& uri) const { QStringList list; NamespaceMap::const_iterator itc, it = d->ns.constBegin(); while ((itc=it) != d->ns.constEnd()) { ++it; if (*itc == uri && !itc.key().isEmpty()) list.append(itc.key()); } return list; } /*! Starts a new namespace context. Normally, you should push a new context at the beginning of each XML element: the new context automatically inherits the declarations of its parent context, and it also keeps track of which declarations were made within this context. \sa popContext() */ void QXmlNamespaceSupport::pushContext() { d->nsStack.push(d->ns); } /*! Reverts to the previous namespace context. Normally, you should pop the context at the end of each XML element. After popping the context, all namespace prefix mappings that were previously in force are restored. \sa pushContext() */ void QXmlNamespaceSupport::popContext() { d->ns.clear(); if(!d->nsStack.isEmpty()) d->ns = d->nsStack.pop(); } /*! Resets this namespace support object ready for reuse. */ void QXmlNamespaceSupport::reset() { QXmlNamespaceSupportPrivate *newD = new QXmlNamespaceSupportPrivate; delete d; d = newD; } /********************************************* * * QXmlAttributes * *********************************************/ /*! \class QXmlAttributes \reentrant \brief The QXmlAttributes class provides XML attributes. \inmodule QtXml \ingroup xml-tools If attributes are reported by QXmlContentHandler::startElement() this class is used to pass the attribute values. Use index() to locate the position of an attribute in the list, count() to retrieve the number of attributes, and clear() to remove the attributes. New attributes can be added with append(). Use type() to get an attribute's type and value() to get its value. The attribute's name is available from localName() or qName(), and its namespace URI from uri(). */ /*! \fn QXmlAttributes::QXmlAttributes() Constructs an empty attribute list. */ QXmlAttributes::QXmlAttributes() { // ### In Qt 5.0, this function was inlined and d was not initialized // The member cannot be used until Qt 6.0 Q_UNUSED(d); } /*! \fn QXmlAttributes::~QXmlAttributes() Destroys the attributes object. */ QXmlAttributes::~QXmlAttributes() { } /*! Looks up the index of an attribute by the qualified name \a qName. Returns the index of the attribute or -1 if it wasn't found. \sa {Namespace Support via Features} */ int QXmlAttributes::index(const QString& qName) const { for (int i = 0; i < attList.size(); ++i) { if (attList.at(i).qname == qName) return i; } return -1; } /*! \overload */ int QXmlAttributes::index(QLatin1String qName) const { for (int i = 0; i < attList.size(); ++i) { if (attList.at(i).qname == qName) return i; } return -1; } /*! \overload Looks up the index of an attribute by a namespace name. \a uri specifies the namespace URI, or an empty string if the name has no namespace URI. \a localPart specifies the attribute's local name. Returns the index of the attribute, or -1 if it wasn't found. \sa {Namespace Support via Features} */ int QXmlAttributes::index(const QString& uri, const QString& localPart) const { for (int i = 0; i < attList.size(); ++i) { const Attribute &att = attList.at(i); if (att.uri == uri && att.localname == localPart) return i; } return -1; } /*! Returns the number of attributes in the list. \sa count() */ int QXmlAttributes::length() const { return attList.count(); } /*! \fn int QXmlAttributes::count() const Returns the number of attributes in the list. This function is equivalent to length(). */ /*! Looks up an attribute's local name for the attribute at position \a index. If no namespace processing is done, the local name is an empty string. \sa {Namespace Support via Features} */ QString QXmlAttributes::localName(int index) const { return attList.at(index).localname; } /*! Looks up an attribute's XML 1.0 qualified name for the attribute at position \a index. \sa {Namespace Support via Features} */ QString QXmlAttributes::qName(int index) const { return attList.at(index).qname; } /*! Looks up an attribute's namespace URI for the attribute at position \a index. If no namespace processing is done or if the attribute has no namespace, the namespace URI is an empty string. \sa {Namespace Support via Features} */ QString QXmlAttributes::uri(int index) const { return attList.at(index).uri; } /*! Looks up an attribute's type for the attribute at position \a index. Currently only "CDATA" is returned. */ QString QXmlAttributes::type(int) const { return QLatin1String("CDATA"); } /*! \overload Looks up an attribute's type for the qualified name \a qName. Currently only "CDATA" is returned. */ QString QXmlAttributes::type(const QString&) const { return QLatin1String("CDATA"); } /*! \overload Looks up an attribute's type by namespace name. \a uri specifies the namespace URI and \a localName specifies the local name. If the name has no namespace URI, use an empty string for \a uri. Currently only "CDATA" is returned. */ QString QXmlAttributes::type(const QString&, const QString&) const { return QLatin1String("CDATA"); } /*! Returns an attribute's value for the attribute at position \a index. The index must be a valid position (i.e., 0 <= \a index < count()). */ QString QXmlAttributes::value(int index) const { return attList.at(index).value; } /*! \overload Returns an attribute's value for the qualified name \a qName, or an empty string if no attribute exists for the name given. \sa {Namespace Support via Features} */ QString QXmlAttributes::value(const QString& qName) const { int i = index(qName); if (i == -1) return QString(); return attList.at(i).value; } /*! \overload Returns an attribute's value for the qualified name \a qName, or an empty string if no attribute exists for the name given. \sa {Namespace Support via Features} */ QString QXmlAttributes::value(QLatin1String qName) const { int i = index(qName); if (i == -1) return QString(); return attList.at(i).value; } /*! \overload Returns an attribute's value by namespace name. \a uri specifies the namespace URI, or an empty string if the name has no namespace URI. \a localName specifies the attribute's local name. */ QString QXmlAttributes::value(const QString& uri, const QString& localName) const { int i = index(uri, localName); if (i == -1) return QString(); return attList.at(i).value; } /*! Clears the list of attributes. \sa append() */ void QXmlAttributes::clear() { attList.clear(); } /*! Appends a new attribute entry to the list of attributes. The qualified name of the attribute is \a qName, the namespace URI is \a uri and the local name is \a localPart. The value of the attribute is \a value. \sa qName(), uri(), localName(), value() */ void QXmlAttributes::append(const QString &qName, const QString &uri, const QString &localPart, const QString &value) { Attribute att; att.qname = qName; att.uri = uri; att.localname = localPart; att.value = value; attList.append(att); } /********************************************* * * QXmlInputSource * *********************************************/ /*! \class QXmlInputSource \reentrant \brief The QXmlInputSource class provides the input data for the QXmlReader subclasses. \inmodule QtXml \ingroup xml-tools All subclasses of QXmlReader read the input XML document from this class. This class recognizes the encoding of the data by reading the encoding declaration in the XML file if it finds one, and reading the data using the corresponding encoding. If it does not find an encoding declaration, then it assumes that the data is either in UTF-8 or UTF-16, depending on whether it can find a byte-order mark. There are two ways to populate the input source with data: you can construct it with a QIODevice* so that the input source reads the data from that device. Or you can set the data explicitly with one of the setData() functions. Usually you either construct a QXmlInputSource that works on a QIODevice* or you construct an empty QXmlInputSource and set the data with setData(). There are only rare occasions where you would want to mix both methods. The QXmlReader subclasses use the next() function to read the input character by character. If you want to start from the beginning again, use reset(). The functions data() and fetchData() are useful if you want to do something with the data other than parsing, e.g. displaying the raw XML file. The benefit of using the QXmlInputClass in such cases is that it tries to use the correct encoding. \sa QXmlReader, QXmlSimpleReader */ // the following two are guaranteed not to be a character const ushort QXmlInputSource::EndOfData = 0xfffe; const ushort QXmlInputSource::EndOfDocument = 0xffff; /* Common part of the constructors. */ void QXmlInputSource::init() { d = new QXmlInputSourcePrivate; QT_TRY { d->inputDevice = 0; d->inputStream = 0; setData(QString()); #ifndef QT_NO_TEXTCODEC d->encMapper = 0; #endif d->nextReturnedEndOfData = true; // first call to next() will call fetchData() d->encodingDeclBytes.clear(); d->encodingDeclChars.clear(); d->lookingForEncodingDecl = true; } QT_CATCH(...) { delete(d); QT_RETHROW; } } /*! Constructs an input source which contains no data. \sa setData() */ QXmlInputSource::QXmlInputSource() { init(); } /*! Constructs an input source and gets the data from device \a dev. If \a dev is not open, it is opened in read-only mode. If \a dev is 0 or it is not possible to read from the device, the input source will contain no data. \sa setData(), fetchData(), QIODevice */ QXmlInputSource::QXmlInputSource(QIODevice *dev) { init(); d->inputDevice = dev; if (dev->isOpen()) d->inputDevice->setTextModeEnabled(false); } /*! Destructor. */ QXmlInputSource::~QXmlInputSource() { // ### close the input device. #ifndef QT_NO_TEXTCODEC delete d->encMapper; #endif delete d; } /*! Returns the next character of the input source. If this function reaches the end of available data, it returns QXmlInputSource::EndOfData. If you call next() after that, it tries to fetch more data by calling fetchData(). If the fetchData() call results in new data, this function returns the first character of that data; otherwise it returns QXmlInputSource::EndOfDocument. Readers, such as QXmlSimpleReader, will assume that the end of the XML document has been reached if the this function returns QXmlInputSource::EndOfDocument, and will check that the supplied input is well-formed. Therefore, when reimplementing this function, it is important to ensure that this behavior is duplicated. \sa reset(), fetchData(), QXmlSimpleReader::parse(), QXmlSimpleReader::parseContinue() */ QChar QXmlInputSource::next() { if (d->pos >= d->length) { if (d->nextReturnedEndOfData) { d->nextReturnedEndOfData = false; fetchData(); if (d->pos >= d->length) { return EndOfDocument; } return next(); } d->nextReturnedEndOfData = true; return EndOfData; } // QXmlInputSource has no way to signal encoding errors. The best we can do // is return EndOfDocument. We do *not* return EndOfData, because the reader // will then just call this function again to get the next char. QChar c = d->unicode[d->pos++]; if (c.unicode() == EndOfData) c = EndOfDocument; return c; } /*! This function sets the position used by next() to the beginning of the data returned by data(). This is useful if you want to use the input source for more than one parse. \note In the case that the underlying data source is a QIODevice, the current position in the device is not automatically set to the start of input. Call QIODevice::seek(0) on the device to do this. \sa next() */ void QXmlInputSource::reset() { d->nextReturnedEndOfData = false; d->pos = 0; } /*! Returns the data the input source contains or an empty string if the input source does not contain any data. \sa setData(), QXmlInputSource(), fetchData() */ QString QXmlInputSource::data() const { if (d->nextReturnedEndOfData) { QXmlInputSource *that = const_cast<QXmlInputSource*>(this); that->d->nextReturnedEndOfData = false; that->fetchData(); } return d->str; } /*! Sets the data of the input source to \a dat. If the input source already contains data, this function deletes that data first. \sa data() */ void QXmlInputSource::setData(const QString& dat) { d->str = dat; d->unicode = dat.unicode(); d->pos = 0; d->length = d->str.length(); d->nextReturnedEndOfData = false; } /*! \overload The data \a dat is passed through the correct text-codec, before it is set. */ void QXmlInputSource::setData(const QByteArray& dat) { setData(fromRawData(dat)); } /*! This function reads more data from the device that was set during construction. If the input source already contained data, this function deletes that data first. This object contains no data after a call to this function if the object was constructed without a device to read data from or if this function was not able to get more data from the device. There are two occasions where a fetch is done implicitly by another function call: during construction (so that the object starts out with some initial data where available), and during a call to next() (if the data had run out). You don't normally need to use this function if you use next(). \sa data(), next(), QXmlInputSource() */ void QXmlInputSource::fetchData() { enum { BufferSize = 1024 }; QByteArray rawData; if (d->inputDevice || d->inputStream) { QIODevice *device = d->inputDevice ? d->inputDevice : d->inputStream->device(); if (!device) { if (d->inputStream && d->inputStream->string()) { QString *s = d->inputStream->string(); rawData = QByteArray((const char *) s->constData(), s->size() * sizeof(QChar)); } } else if (device->isOpen() || device->open(QIODevice::ReadOnly)) { rawData.resize(BufferSize); qint64 size = device->read(rawData.data(), BufferSize); if (size != -1) { // We don't want to give fromRawData() less than four bytes if we can avoid it. while (size < 4) { if (!device->waitForReadyRead(-1)) break; int ret = device->read(rawData.data() + size, BufferSize - size); if (ret <= 0) break; size += ret; } } rawData.resize(qMax(qint64(0), size)); } /* We do this inside the "if (d->inputDevice ..." scope * because if we're not using a stream or device, that is, * the user set a QString manually, we don't want to set * d->str. */ setData(fromRawData(rawData)); } } #ifndef QT_NO_TEXTCODEC static QString extractEncodingDecl(const QString &text, bool *needMoreText) { *needMoreText = false; int l = text.length(); QString snip = QString::fromLatin1("<?xml").left(l); if (l > 0 && !text.startsWith(snip)) return QString(); int endPos = text.indexOf(QLatin1Char('>')); if (endPos == -1) { *needMoreText = l < 255; // we won't look forever return QString(); } int pos = text.indexOf(QLatin1String("encoding")); if (pos == -1 || pos >= endPos) return QString(); while (pos < endPos) { ushort uc = text.at(pos).unicode(); if (uc == '\'' || uc == '"') break; ++pos; } if (pos == endPos) return QString(); QString encoding; ++pos; while (pos < endPos) { ushort uc = text.at(pos).unicode(); if (uc == '\'' || uc == '"') break; encoding.append(uc); ++pos; } return encoding; } #endif // QT_NO_TEXTCODEC /*! This function reads the XML file from \a data and tries to recognize the encoding. It converts the raw data \a data into a QString and returns it. It tries its best to get the correct encoding for the XML file. If \a beginning is true, this function assumes that the data starts at the beginning of a new XML document and looks for an encoding declaration. If \a beginning is false, it converts the raw data using the encoding determined from prior calls. */ QString QXmlInputSource::fromRawData(const QByteArray &data, bool beginning) { #ifdef QT_NO_TEXTCODEC Q_UNUSED(beginning); return QString::fromLatin1(data.constData(), data.size()); #else if (data.size() == 0) return QString(); if (beginning) { delete d->encMapper; d->encMapper = 0; } int mib = 106; // UTF-8 // This is the initial UTF codec we will read the encoding declaration with if (d->encMapper == 0) { d->encodingDeclBytes.clear(); d->encodingDeclChars.clear(); d->lookingForEncodingDecl = true; // look for byte order mark and read the first 5 characters if (data.size() >= 4) { uchar ch1 = data.at(0); uchar ch2 = data.at(1); uchar ch3 = data.at(2); uchar ch4 = data.at(3); if ((ch1 == 0 && ch2 == 0 && ch3 == 0xfe && ch4 == 0xff) || (ch1 == 0xff && ch2 == 0xfe && ch3 == 0 && ch4 == 0)) mib = 1017; // UTF-32 with byte order mark else if (ch1 == 0x3c && ch2 == 0x00 && ch3 == 0x00 && ch4 == 0x00) mib = 1019; // UTF-32LE else if (ch1 == 0x00 && ch2 == 0x00 && ch3 == 0x00 && ch4 == 0x3c) mib = 1018; // UTF-32BE } if (mib == 106 && data.size() >= 2) { uchar ch1 = data.at(0); uchar ch2 = data.at(1); if ((ch1 == 0xfe && ch2 == 0xff) || (ch1 == 0xff && ch2 == 0xfe)) mib = 1015; // UTF-16 with byte order mark else if (ch1 == 0x3c && ch2 == 0x00) mib = 1014; // UTF-16LE else if (ch1 == 0x00 && ch2 == 0x3c) mib = 1013; // UTF-16BE } QTextCodec *codec = QTextCodec::codecForMib(mib); Q_ASSERT(codec); d->encMapper = codec->makeDecoder(); } QString input = d->encMapper->toUnicode(data.constData(), data.size()); if (d->lookingForEncodingDecl) { d->encodingDeclChars += input; bool needMoreText; QString encoding = extractEncodingDecl(d->encodingDeclChars, &needMoreText); if (!encoding.isEmpty()) { if (QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1())) { /* If the encoding is the same, we don't have to do toUnicode() all over again. */ if(codec->mibEnum() != mib) { delete d->encMapper; d->encMapper = codec->makeDecoder(); /* The variable input can potentially be large, so we deallocate * it before calling toUnicode() in order to avoid having two * large QStrings in memory simultaneously. */ input.clear(); // prime the decoder with the data so far d->encMapper->toUnicode(d->encodingDeclBytes.constData(), d->encodingDeclBytes.size()); // now feed it the new data input = d->encMapper->toUnicode(data.constData(), data.size()); } } } d->encodingDeclBytes += data; d->lookingForEncodingDecl = needMoreText; } return input; #endif } /********************************************* * * QXmlDefaultHandler * *********************************************/ /*! \class QXmlContentHandler \reentrant \brief The QXmlContentHandler class provides an interface to report the logical content of XML data. \inmodule QtXml \ingroup xml-tools If the application needs to be informed of basic parsing events, it can implement this interface and activate it using QXmlReader::setContentHandler(). The reader can then report basic document-related events like the start and end of elements and character data through this interface. The order of events in this interface is very important, and mirrors the order of information in the document itself. For example, all of an element's content (character data, processing instructions, and sub-elements) appears, in order, between the startElement() event and the corresponding endElement() event. The class QXmlDefaultHandler provides a default implementation for this interface; subclassing from the QXmlDefaultHandler class is very convenient if you only want to be informed of some parsing events. The startDocument() function is called at the start of the document, and endDocument() is called at the end. Before parsing begins setDocumentLocator() is called. For each element startElement() is called, with endElement() being called at the end of each element. The characters() function is called with chunks of character data; ignorableWhitespace() is called with chunks of whitespace and processingInstruction() is called with processing instructions. If an entity is skipped skippedEntity() is called. At the beginning of prefix-URI scopes startPrefixMapping() is called. \sa QXmlDTDHandler, QXmlDeclHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler, {Introduction to SAX2} */ /*! \fn QXmlContentHandler::~QXmlContentHandler() Destroys the content handler. */ /*! \fn void QXmlContentHandler::setDocumentLocator(QXmlLocator* locator) The reader calls this function before it starts parsing the document. The argument \a locator is a pointer to a QXmlLocator which allows the application to get the parsing position within the document. Do not destroy the \a locator; it is destroyed when the reader is destroyed. (Do not use the \a locator after the reader is destroyed). */ /*! \fn bool QXmlContentHandler::startDocument() The reader calls this function when it starts parsing the document. The reader calls this function just once, after the call to setDocumentLocator(), and before any other functions in this class or in the QXmlDTDHandler class are called. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa endDocument() */ /*! \fn bool QXmlContentHandler::endDocument() The reader calls this function after it has finished parsing. It is called just once, and is the last handler function called. It is called after the reader has read all input or has abandoned parsing because of a fatal error. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa startDocument() */ /*! \fn bool QXmlContentHandler::startPrefixMapping(const QString& prefix, const QString& uri) The reader calls this function to signal the begin of a prefix-URI namespace mapping scope. This information is not necessary for normal namespace processing since the reader automatically replaces prefixes for element and attribute names. Note that startPrefixMapping() and endPrefixMapping() calls are not guaranteed to be properly nested relative to each other: all startPrefixMapping() events occur before the corresponding startElement() event, and all endPrefixMapping() events occur after the corresponding endElement() event, but their order is not otherwise guaranteed. The argument \a prefix is the namespace prefix being declared and the argument \a uri is the namespace URI the prefix is mapped to. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa endPrefixMapping(), {Namespace Support via Features} */ /*! \fn bool QXmlContentHandler::endPrefixMapping(const QString& prefix) The reader calls this function to signal the end of a prefix mapping for the prefix \a prefix. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa startPrefixMapping(), {Namespace Support via Features} */ /*! \fn bool QXmlContentHandler::startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts) The reader calls this function when it has parsed a start element tag. There is a corresponding endElement() call when the corresponding end element tag is read. The startElement() and endElement() calls are always nested correctly. Empty element tags (e.g. \c{<x/>}) cause a startElement() call to be immediately followed by an endElement() call. The attribute list provided only contains attributes with explicit values. The attribute list contains attributes used for namespace declaration (i.e. attributes starting with xmlns) only if the namespace-prefix property of the reader is true. The argument \a namespaceURI is the namespace URI, or an empty string if the element has no namespace URI or if no namespace processing is done. \a localName is the local name (without prefix), or an empty string if no namespace processing is done, \a qName is the qualified name (with prefix) and \a atts are the attributes attached to the element. If there are no attributes, \a atts is an empty attributes object. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa endElement(), {Namespace Support via Features} */ /*! \fn bool QXmlContentHandler::endElement(const QString& namespaceURI, const QString& localName, const QString& qName) The reader calls this function when it has parsed an end element tag with the qualified name \a qName, the local name \a localName and the namespace URI \a namespaceURI. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa startElement(), {Namespace Support via Features} */ /*! \fn bool QXmlContentHandler::characters(const QString& ch) The reader calls this function when it has parsed a chunk of character data (either normal character data or character data inside a CDATA section; if you need to distinguish between those two types you must use QXmlLexicalHandler::startCDATA() and QXmlLexicalHandler::endCDATA()). The character data is reported in \a ch. Some readers report whitespace in element content using the ignorableWhitespace() function rather than using this one. A reader may report the character data of an element in more than one chunk; e.g. a reader might want to report "a\<b" in three characters() events ("a ", "\<" and " b"). If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlContentHandler::ignorableWhitespace(const QString& ch) Some readers may use this function to report each chunk of whitespace in element content. The whitespace is reported in \a ch. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlContentHandler::processingInstruction(const QString& target, const QString& data) The reader calls this function when it has parsed a processing instruction. \a target is the target name of the processing instruction and \a data is the data in the processing instruction. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlContentHandler::skippedEntity(const QString& name) Some readers may skip entities if they have not seen the declarations (e.g. because they are in an external DTD). If they do so they report that they skipped the entity called \a name by calling this function. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn QString QXmlContentHandler::errorString() const The reader calls this function to get an error string, e.g. if any of the handler functions returns \c false. */ /*! \class QXmlErrorHandler \reentrant \brief The QXmlErrorHandler class provides an interface to report errors in XML data. \inmodule QtXml \ingroup xml-tools If you want your application to report errors to the user or to perform customized error handling, you should subclass this class. You can set the error handler with QXmlReader::setErrorHandler(). Errors can be reported using warning(), error() and fatalError(), with the error text being reported with errorString(). \sa QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlLexicalHandler, {Introduction to SAX2} */ /*! \fn QXmlErrorHandler::~QXmlErrorHandler() Destroys the error handler. */ /*! \fn bool QXmlErrorHandler::warning(const QXmlParseException& exception) A reader might use this function to report a warning. Warnings are conditions that are not errors or fatal errors as defined by the XML 1.0 specification. Details of the warning are stored in \a exception. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlErrorHandler::error(const QXmlParseException& exception) A reader might use this function to report a recoverable error. A recoverable error corresponds to the definiton of "error" in section 1.2 of the XML 1.0 specification. Details of the error are stored in \a exception. The reader must continue to provide normal parsing events after invoking this function. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlErrorHandler::fatalError(const QXmlParseException& exception) A reader must use this function to report a non-recoverable error. Details of the error are stored in \a exception. If this function returns \c true the reader might try to go on parsing and reporting further errors, but no regular parsing events are reported. */ /*! \fn QString QXmlErrorHandler::errorString() const The reader calls this function to get an error string if any of the handler functions returns \c false. */ /*! \class QXmlDTDHandler \reentrant \brief The QXmlDTDHandler class provides an interface to report DTD content of XML data. \inmodule QtXml \ingroup xml-tools If an application needs information about notations and unparsed entities, it can implement this interface and register an instance with QXmlReader::setDTDHandler(). Note that this interface includes only those DTD events that the XML recommendation requires processors to report, i.e. notation and unparsed entity declarations using notationDecl() and unparsedEntityDecl() respectively. \sa QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler, {Introduction to SAX2} */ /*! \fn QXmlDTDHandler::~QXmlDTDHandler() Destroys the DTD handler. */ /*! \fn bool QXmlDTDHandler::notationDecl(const QString& name, const QString& publicId, const QString& systemId) The reader calls this function when it has parsed a notation declaration. The argument \a name is the notation name, \a publicId is the notation's public identifier and \a systemId is the notation's system identifier. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlDTDHandler::unparsedEntityDecl(const QString& name, const QString& publicId, const QString& systemId, const QString& notationName) The reader calls this function when it finds an unparsed entity declaration. The argument \a name is the unparsed entity's name, \a publicId is the entity's public identifier, \a systemId is the entity's system identifier and \a notationName is the name of the associated notation. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn QString QXmlDTDHandler::errorString() const The reader calls this function to get an error string if any of the handler functions returns \c false. */ /*! \class QXmlEntityResolver \reentrant \brief The QXmlEntityResolver class provides an interface to resolve external entities contained in XML data. \inmodule QtXml \ingroup xml-tools If an application needs to implement customized handling for external entities, it must implement this interface, i.e. resolveEntity(), and register it with QXmlReader::setEntityResolver(). \sa QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlErrorHandler, QXmlLexicalHandler, {Introduction to SAX2} */ /*! \fn QXmlEntityResolver::~QXmlEntityResolver() Destroys the entity resolver. */ /*! \fn bool QXmlEntityResolver::resolveEntity(const QString& publicId, const QString& systemId, QXmlInputSource*& ret) The reader calls this function before it opens any external entity, except the top-level document entity. The application may request the reader to resolve the entity itself (\a ret is 0) or to use an entirely different input source (\a ret points to the input source). The reader deletes the input source \a ret when it no longer needs it, so you should allocate it on the heap with \c new. The argument \a publicId is the public identifier of the external entity, \a systemId is the system identifier of the external entity and \a ret is the return value of this function. If \a ret is 0 the reader should resolve the entity itself, if it is non-zero it must point to an input source which the reader uses instead. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn QString QXmlEntityResolver::errorString() const The reader calls this function to get an error string if any of the handler functions returns \c false. */ /*! \class QXmlLexicalHandler \reentrant \brief The QXmlLexicalHandler class provides an interface to report the lexical content of XML data. \inmodule QtXml \ingroup xml-tools The events in the lexical handler apply to the entire document, not just to the document element, and all lexical handler events appear between the content handler's startDocument and endDocument events. You can set the lexical handler with QXmlReader::setLexicalHandler(). This interface's design is based on the SAX2 extension LexicalHandler. The interface provides the startDTD(), endDTD(), startEntity(), endEntity(), startCDATA(), endCDATA() and comment() functions. \sa QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, {Introduction to SAX2} */ /*! \fn QXmlLexicalHandler::~QXmlLexicalHandler() Destroys the lexical handler. */ /*! \fn bool QXmlLexicalHandler::startDTD(const QString& name, const QString& publicId, const QString& systemId) The reader calls this function to report the start of a DTD declaration, if any. It reports the name of the document type in \a name, the public identifier in \a publicId and the system identifier in \a systemId. If the public identifier is missing, \a publicId is set to an empty string. If the system identifier is missing, \a systemId is set to an empty string. Note that it is not valid XML to have a public identifier but no system identifier; in such cases a parse error will occur. All declarations reported through QXmlDTDHandler or QXmlDeclHandler appear between the startDTD() and endDTD() calls. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa endDTD() */ /*! \fn bool QXmlLexicalHandler::endDTD() The reader calls this function to report the end of a DTD declaration, if any. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa startDTD() */ /*! \fn bool QXmlLexicalHandler::startEntity(const QString& name) The reader calls this function to report the start of an entity called \a name. Note that if the entity is unknown, the reader reports it through QXmlContentHandler::skippedEntity() and not through this function. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa endEntity(), QXmlSimpleReader::setFeature() */ /*! \fn bool QXmlLexicalHandler::endEntity(const QString& name) The reader calls this function to report the end of an entity called \a name. For every startEntity() call, there is a corresponding endEntity() call. The calls to startEntity() and endEntity() are properly nested. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa startEntity(), QXmlContentHandler::skippedEntity(), QXmlSimpleReader::setFeature() */ /*! \fn bool QXmlLexicalHandler::startCDATA() The reader calls this function to report the start of a CDATA section. The content of the CDATA section is reported through the QXmlContentHandler::characters() function. This function is intended only to report the boundary. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa endCDATA() */ /*! \fn bool QXmlLexicalHandler::endCDATA() The reader calls this function to report the end of a CDATA section. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. \sa startCDATA(), QXmlContentHandler::characters() */ /*! \fn bool QXmlLexicalHandler::comment(const QString& ch) The reader calls this function to report an XML comment anywhere in the document. It reports the text of the comment in \a ch. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn QString QXmlLexicalHandler::errorString() const The reader calls this function to get an error string if any of the handler functions returns \c false. */ /*! \class QXmlDeclHandler \reentrant \brief The QXmlDeclHandler class provides an interface to report declaration content of XML data. \inmodule QtXml \ingroup xml-tools You can set the declaration handler with QXmlReader::setDeclHandler(). This interface is based on the SAX2 extension DeclHandler. The interface provides attributeDecl(), internalEntityDecl() and externalEntityDecl() functions. \sa QXmlDTDHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler, {Introduction to SAX2} */ /*! \fn QXmlDeclHandler::~QXmlDeclHandler() Destroys the declaration handler. */ /*! \fn bool QXmlDeclHandler::attributeDecl(const QString& eName, const QString& aName, const QString& type, const QString& valueDefault, const QString& value) The reader calls this function to report an attribute type declaration. Only the effective (first) declaration for an attribute is reported. The reader passes the name of the associated element in \a eName and the name of the attribute in \a aName. It passes a string that represents the attribute type in \a type and a string that represents the attribute default in \a valueDefault. This string is one of "#IMPLIED", "#REQUIRED", "#FIXED" or an empty string (if none of the others applies). The reader passes the attribute's default value in \a value. If no default value is specified in the XML file, \a value is an empty string. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlDeclHandler::internalEntityDecl(const QString& name, const QString& value) The reader calls this function to report an internal entity declaration. Only the effective (first) declaration is reported. The reader passes the name of the entity in \a name and the value of the entity in \a value. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn bool QXmlDeclHandler::externalEntityDecl(const QString& name, const QString& publicId, const QString& systemId) The reader calls this function to report a parsed external entity declaration. Only the effective (first) declaration for each entity is reported. The reader passes the name of the entity in \a name, the public identifier in \a publicId and the system identifier in \a systemId. If there is no public identifier specified, it passes an empty string in \a publicId. If this function returns \c false the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message. */ /*! \fn QString QXmlDeclHandler::errorString() const The reader calls this function to get an error string if any of the handler functions returns \c false. */ /*! \class QXmlDefaultHandler \reentrant \brief The QXmlDefaultHandler class provides a default implementation of all the XML handler classes. \inmodule QtXml \ingroup xml-tools This class gathers together the features of the specialized handler classes, making it a convenient starting point when implementing custom handlers for subclasses of QXmlReader, particularly QXmlSimpleReader. The virtual functions from each of the base classes are reimplemented in this class, providing sensible default behavior for many common cases. By subclassing this class, and overriding these functions, you can concentrate on implementing the parts of the handler relevant to your application. The XML reader must be told which handler to use for different kinds of events during parsing. This means that, although QXmlDefaultHandler provides default implementations of functions inherited from all its base classes, we can still use specialized handlers for particular kinds of events. For example, QXmlDefaultHandler subclasses both QXmlContentHandler and QXmlErrorHandler, so by subclassing it we can use the same handler for both of the following reader functions: \snippet rsslisting/listing.cpp 0 Since the reader will inform the handler of parsing errors, it is necessary to reimplement QXmlErrorHandler::fatalError() if, for example, we want to stop parsing when such an error occurs: \snippet rsslisting/handler.cpp 0 The above function returns \c false, which tells the reader to stop parsing. To continue to use the same reader, it is necessary to create a new handler instance, and set up the reader to use it in the manner described above. It is useful to examine some of the functions inherited by QXmlDefaultHandler, and consider why they might be reimplemented in a custom handler. Custom handlers will typically reimplement QXmlContentHandler::startDocument() to prepare the handler for new content. Document elements and the text within them can be processed by reimplementing QXmlContentHandler::startElement(), QXmlContentHandler::endElement(), and QXmlContentHandler::characters(). You may want to reimplement QXmlContentHandler::endDocument() to perform some finalization or validation on the content once the document has been read completely. \sa QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler, {Introduction to SAX2} */ /*! \fn QXmlDefaultHandler::QXmlDefaultHandler() Constructs a handler for use with subclasses of QXmlReader. */ QXmlDefaultHandler::QXmlDefaultHandler() { // ### In Qt 5.0, this function was inlined and d was not initialized // The member cannot be used until Qt 6.0 Q_UNUSED(d); } /*! \fn QXmlDefaultHandler::~QXmlDefaultHandler() Destroys the handler. */ QXmlDefaultHandler::~QXmlDefaultHandler() { } /*! \reimp This reimplementation does nothing. */ void QXmlDefaultHandler::setDocumentLocator(QXmlLocator*) { } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::startDocument() { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::endDocument() { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::startPrefixMapping(const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::endPrefixMapping(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::startElement(const QString&, const QString&, const QString&, const QXmlAttributes&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::endElement(const QString&, const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::characters(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::ignorableWhitespace(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::processingInstruction(const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::skippedEntity(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::warning(const QXmlParseException&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::error(const QXmlParseException&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::fatalError(const QXmlParseException&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::notationDecl(const QString&, const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::unparsedEntityDecl(const QString&, const QString&, const QString&, const QString&) { return true; } /*! \reimp Sets \a ret to 0, so that the reader uses the system identifier provided in the XML document. */ bool QXmlDefaultHandler::resolveEntity(const QString&, const QString&, QXmlInputSource*& ret) { ret = 0; return true; } /*! \reimp Returns the default error string. */ QString QXmlDefaultHandler::errorString() const { return QString::fromLatin1(XMLERR_ERRORBYCONSUMER); } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::startDTD(const QString&, const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::endDTD() { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::startEntity(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::endEntity(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::startCDATA() { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::endCDATA() { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::comment(const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::attributeDecl(const QString&, const QString&, const QString&, const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::internalEntityDecl(const QString&, const QString&) { return true; } /*! \reimp This reimplementation does nothing. */ bool QXmlDefaultHandler::externalEntityDecl(const QString&, const QString&, const QString&) { return true; } /********************************************* * * QXmlSimpleReaderPrivate * *********************************************/ inline bool QXmlSimpleReaderPrivate::atEnd() { return (c.unicode()|0x0001) == 0xffff; } inline void QXmlSimpleReaderPrivate::stringClear() { stringValueLen = 0; stringArrayPos = 0; } inline void QXmlSimpleReaderPrivate::nameClear() { nameValueLen = 0; nameArrayPos = 0; } inline void QXmlSimpleReaderPrivate::refClear() { refValueLen = 0; refArrayPos = 0; } QXmlSimpleReaderPrivate::QXmlSimpleReaderPrivate(QXmlSimpleReader *reader) { q_ptr = reader; parseStack = 0; locator.reset(new QXmlSimpleReaderLocator(reader)); entityRes = 0; dtdHnd = 0; contentHnd = 0; errorHnd = 0; lexicalHnd = 0; declHnd = 0; // default feature settings useNamespaces = true; useNamespacePrefixes = false; reportWhitespaceCharData = true; reportEntities = false; } QXmlSimpleReaderPrivate::~QXmlSimpleReaderPrivate() { delete parseStack; } void QXmlSimpleReaderPrivate::initIncrementalParsing() { if(parseStack) parseStack->clear(); else parseStack = new QStack<ParseState>; } /********************************************* * * QXmlSimpleReader * *********************************************/ /*! \class QXmlReader \reentrant \brief The QXmlReader class provides an interface for XML readers (i.e. parsers). \inmodule QtXml \ingroup xml-tools This abstract class provides an interface for all of Qt's XML readers. Currently there is only one implementation of a reader included in Qt's XML module: QXmlSimpleReader. In future releases there might be more readers with different properties available (e.g. a validating parser). The design of the XML classes follows the \l{SAX2 Java interface}, with the names adapted to fit Qt naming conventions. It should be very easy for anybody who has worked with SAX2 to get started with the Qt XML classes. All readers use the class QXmlInputSource to read the input document. Since you are normally interested in particular content in the XML document, the reader reports the content through special handler classes (QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler and QXmlLexicalHandler), which you must subclass, if you want to process the contents. Since the handler classes only describe interfaces you must implement all the functions. We provide the QXmlDefaultHandler class to make this easier: it implements a default behavior (do nothing) for all functions, so you can subclass it and just implement the functions you are interested in. Features and properties of the reader can be set with setFeature() and setProperty() respectively. You can set the reader to use your own subclasses with setEntityResolver(), setDTDHandler(), setContentHandler(), setErrorHandler(), setLexicalHandler() and setDeclHandler(). The parse itself is started with a call to parse(). \sa QXmlSimpleReader */ /*! \fn QXmlReader::~QXmlReader() Destroys the reader. */ /*! \fn bool QXmlReader::feature(const QString& name, bool *ok) const If the reader has the feature called \a name, the feature's value is returned. If no such feature exists the return value is undefined. If \a ok is not 0: \c{*}\a{ok} is set to true if the reader has the feature called \a name; otherwise \c{*}\a{ok} is set to false. \sa setFeature(), hasFeature() */ /*! \fn void QXmlReader::setFeature(const QString& name, bool value) Sets the feature called \a name to the given \a value. If the reader doesn't have the feature nothing happens. \sa feature(), hasFeature() */ /*! \fn bool QXmlReader::hasFeature(const QString& name) const Returns \c true if the reader has the feature called \a name; otherwise returns \c false. \sa feature(), setFeature() */ /*! \fn void* QXmlReader::property(const QString& name, bool *ok) const If the reader has the property \a name, this function returns the value of the property; otherwise the return value is undefined. If \a ok is not 0: if the reader has the \a name property \c{*}\a{ok} is set to true; otherwise \c{*}\a{ok} is set to false. \sa setProperty(), hasProperty() */ /*! \fn void QXmlReader::setProperty(const QString& name, void* value) Sets the property \a name to \a value. If the reader doesn't have the property nothing happens. \sa property(), hasProperty() */ /*! \fn bool QXmlReader::hasProperty(const QString& name) const Returns \c true if the reader has the property \a name; otherwise returns \c false. \sa property(), setProperty() */ /*! \fn void QXmlReader::setEntityResolver(QXmlEntityResolver* handler) Sets the entity resolver to \a handler. \sa entityResolver() */ /*! \fn QXmlEntityResolver* QXmlReader::entityResolver() const Returns the entity resolver or 0 if none was set. \sa setEntityResolver() */ /*! \fn void QXmlReader::setDTDHandler(QXmlDTDHandler* handler) Sets the DTD handler to \a handler. \sa DTDHandler() */ /*! \fn QXmlDTDHandler* QXmlReader::DTDHandler() const Returns the DTD handler or 0 if none was set. \sa setDTDHandler() */ /*! \fn void QXmlReader::setContentHandler(QXmlContentHandler* handler) Sets the content handler to \a handler. \sa contentHandler() */ /*! \fn QXmlContentHandler* QXmlReader::contentHandler() const Returns the content handler or 0 if none was set. \sa setContentHandler() */ /*! \fn void QXmlReader::setErrorHandler(QXmlErrorHandler* handler) Sets the error handler to \a handler. Clears the error handler if \a handler is 0. \sa errorHandler() */ /*! \fn QXmlErrorHandler* QXmlReader::errorHandler() const Returns the error handler or 0 if none is set. \sa setErrorHandler() */ /*! \fn void QXmlReader::setLexicalHandler(QXmlLexicalHandler* handler) Sets the lexical handler to \a handler. \sa lexicalHandler() */ /*! \fn QXmlLexicalHandler* QXmlReader::lexicalHandler() const Returns the lexical handler or 0 if none was set. \sa setLexicalHandler() */ /*! \fn void QXmlReader::setDeclHandler(QXmlDeclHandler* handler) Sets the declaration handler to \a handler. \sa declHandler() */ /*! \fn QXmlDeclHandler* QXmlReader::declHandler() const Returns the declaration handler or 0 if none was set. \sa setDeclHandler() */ /*! \fn bool QXmlReader::parse(const QXmlInputSource &input) \obsolete Parses the given \a input. */ /*! \fn bool QXmlReader::parse(const QXmlInputSource *input) Reads an XML document from \a input and parses it. Returns \c true if the parsing was successful; otherwise returns \c false. */ /*! \class QXmlSimpleReader \nonreentrant \brief The QXmlSimpleReader class provides an implementation of a simple XML parser. \inmodule QtXml \ingroup xml-tools This XML reader is suitable for a wide range of applications. It is able to parse well-formed XML and can report the namespaces of elements to a content handler; however, it does not parse any external entities. For historical reasons, Attribute Value Normalization and End-of-Line Handling as described in the XML 1.0 specification is not performed. The easiest pattern of use for this class is to create a reader instance, define an input source, specify the handlers to be used by the reader, and parse the data. For example, we could use a QFile to supply the input. Here, we create a reader, and define an input source to be used by the reader: \snippet simpleparse/main.cpp 0 A handler lets us perform actions when the reader encounters certain types of content, or if errors in the input are found. The reader must be told which handler to use for each type of event. For many common applications, we can create a custom handler by subclassing QXmlDefaultHandler, and use this to handle both error and content events: \snippet simpleparse/main.cpp 1 If you don't set at least the content and error handlers, the parser will fall back on its default behavior---and will do nothing. The most convenient way to handle the input is to read it in a single pass using the parse() function with an argument that specifies the input source: \snippet simpleparse/main.cpp 2 If you can't parse the entire input in one go (for example, it is huge, or is being delivered over a network connection), data can be fed to the parser in pieces. This is achieved by telling parse() to work incrementally, and making subsequent calls to the parseContinue() function, until all the data has been processed. A common way to perform incremental parsing is to connect the \c readyRead() signal of a \l{QNetworkReply} {network reply} a slot, and handle the incoming data there. See QNetworkAccessManager. Aspects of the parsing behavior can be adapted using setFeature() and setProperty(). \snippet code/src_xml_sax_qxml.cpp 0 QXmlSimpleReader is not reentrant. If you want to use the class in threaded code, lock the code using QXmlSimpleReader with a locking mechanism, such as a QMutex. */ static inline bool is_S(QChar ch) { ushort uc = ch.unicode(); return (uc == ' ' || uc == '\t' || uc == '\n' || uc == '\r'); } enum NameChar { NameBeginning, NameNotBeginning, NotName }; static const char Begi = (char)NameBeginning; static const char NtBg = (char)NameNotBeginning; static const char NotN = (char)NotName; static const char nameCharTable[128] = { // 0x00 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, // 0x10 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, // 0x20 (0x2D is '-', 0x2E is '.') NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN, NtBg, NtBg, NotN, // 0x30 (0x30..0x39 are '0'..'9', 0x3A is ':') NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, Begi, NotN, NotN, NotN, NotN, NotN, // 0x40 (0x41..0x5A are 'A'..'Z') NotN, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, // 0x50 (0x5F is '_') Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, NotN, NotN, NotN, NotN, Begi, // 0x60 (0x61..0x7A are 'a'..'z') NotN, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, // 0x70 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi, NotN, NotN, NotN, NotN, NotN }; static inline NameChar fastDetermineNameChar(QChar ch) { ushort uc = ch.unicode(); if (!(uc & ~0x7f)) // uc < 128 return (NameChar)nameCharTable[uc]; QChar::Category cat = ch.category(); // ### some these categories might be slightly wrong if ((cat >= QChar::Letter_Uppercase && cat <= QChar::Letter_Other) || cat == QChar::Number_Letter) return NameBeginning; if ((cat >= QChar::Number_DecimalDigit && cat <= QChar::Number_Other) || (cat >= QChar::Mark_NonSpacing && cat <= QChar::Mark_Enclosing)) return NameNotBeginning; return NotName; } static NameChar determineNameChar(QChar ch) { return fastDetermineNameChar(ch); } /*! Constructs a simple XML reader. */ QXmlSimpleReader::QXmlSimpleReader() : d_ptr(new QXmlSimpleReaderPrivate(this)) { } /*! Destroys the simple XML reader. */ QXmlSimpleReader::~QXmlSimpleReader() { } /*! \reimp */ bool QXmlSimpleReader::feature(const QString& name, bool *ok) const { const QXmlSimpleReaderPrivate *d = d_func(); if (ok != 0) *ok = true; if (name == QLatin1String("http://xml.org/sax/features/namespaces")) { return d->useNamespaces; } else if (name == QLatin1String("http://xml.org/sax/features/namespace-prefixes")) { return d->useNamespacePrefixes; } else if (name == QLatin1String("http://trolltech.com/xml/features/report-whitespace-only-CharData") // For compat with Qt 4 || name == QLatin1String("http://qt-project.org/xml/features/report-whitespace-only-CharData")) { return d->reportWhitespaceCharData; } else if (name == QLatin1String("http://trolltech.com/xml/features/report-start-end-entity") // For compat with Qt 4 || name == QLatin1String("http://qt-project.org/xml/features/report-start-end-entity")) { return d->reportEntities; } else { qWarning("Unknown feature %s", name.toLatin1().data()); if (ok != 0) *ok = false; } return false; } /*! Turns on the feature \a name if \a enable is true; otherwise turns it off. The \a name parameter must be one of the following strings: \table \header \li Feature \li Default \li Notes \row \li \e http://xml.org/sax/features/namespaces \li true \li If enabled, namespaces are reported to the content handler. \row \li \e http://xml.org/sax/features/namespace-prefixes \li false \li If enabled, the original prefixed names and attributes used for namespace declarations are reported. \row \li \e http://trolltech.com/xml/features/report-whitespace-only-CharData \li true \li Obsolete, use the following string instead. If enabled, CharData that consist of only whitespace characters are reported using QXmlContentHandler::characters(). If disabled, whitespace is silently discarded. \row \li \e http://qt-project.org/xml/features/report-whitespace-only-CharData \li true \li If enabled, CharData that consist of only whitespace characters are reported using QXmlContentHandler::characters(). If disabled, whitespace is silently discarded. \row \li \e http://trolltech.com/xml/features/report-start-end-entity \li false \li Obsolete, use the following string instead. If enabled, the parser reports QXmlContentHandler::startEntity() and QXmlContentHandler::endEntity() events, so character data might be reported in chunks. If disabled, the parser does not report these events, but silently substitutes the entities, and reports the character data in one chunk. \row \li \e http://qt-project.org/xml/features/report-start-end-entity \li false \li If enabled, the parser reports QXmlContentHandler::startEntity() and QXmlContentHandler::endEntity() events, so character data might be reported in chunks. If disabled, the parser does not report these events, but silently substitutes the entities, and reports the character data in one chunk. \endtable \sa feature(), hasFeature(), {SAX2 Features} */ void QXmlSimpleReader::setFeature(const QString& name, bool enable) { Q_D(QXmlSimpleReader); if (name == QLatin1String("http://xml.org/sax/features/namespaces")) { d->useNamespaces = enable; } else if (name == QLatin1String("http://xml.org/sax/features/namespace-prefixes")) { d->useNamespacePrefixes = enable; } else if (name == QLatin1String("http://trolltech.com/xml/features/report-whitespace-only-CharData") // For compat with Qt 4 || name == QLatin1String("http://qt-project.org/xml/features/report-whitespace-only-CharData")) { d->reportWhitespaceCharData = enable; } else if (name == QLatin1String("http://trolltech.com/xml/features/report-start-end-entity") // For compat with Qt 4 || name == QLatin1String("http://trolltech.com/xml/features/report-start-end-entity")) { d->reportEntities = enable; } else { qWarning("Unknown feature %s", name.toLatin1().data()); } } /*! \reimp */ bool QXmlSimpleReader::hasFeature(const QString& name) const { if (name == QLatin1String("http://xml.org/sax/features/namespaces") || name == QLatin1String("http://xml.org/sax/features/namespace-prefixes") || name == QLatin1String("http://trolltech.com/xml/features/report-whitespace-only-CharData") // For compat with Qt 4 || name == QLatin1String("http://qt-project.org/xml/features/report-whitespace-only-CharData") || name == QLatin1String("http://trolltech.com/xml/features/report-start-end-entity") // For compat with Qt 4 || name == QLatin1String("http://qt-project.org/xml/features/report-start-end-entity")) { return true; } else { return false; } } /*! \reimp */ void* QXmlSimpleReader::property(const QString&, bool *ok) const { if (ok != 0) *ok = false; return 0; } /*! \reimp */ void QXmlSimpleReader::setProperty(const QString&, void*) { } /*! \reimp */ bool QXmlSimpleReader::hasProperty(const QString&) const { return false; } /*! \reimp */ void QXmlSimpleReader::setEntityResolver(QXmlEntityResolver* handler) { Q_D(QXmlSimpleReader); d->entityRes = handler; } /*! \reimp */ QXmlEntityResolver* QXmlSimpleReader::entityResolver() const { const QXmlSimpleReaderPrivate *d = d_func(); return d->entityRes; } /*! \reimp */ void QXmlSimpleReader::setDTDHandler(QXmlDTDHandler* handler) { Q_D(QXmlSimpleReader); d->dtdHnd = handler; } /*! \reimp */ QXmlDTDHandler* QXmlSimpleReader::DTDHandler() const { const QXmlSimpleReaderPrivate *d = d_func(); return d->dtdHnd; } /*! \reimp */ void QXmlSimpleReader::setContentHandler(QXmlContentHandler* handler) { Q_D(QXmlSimpleReader); d->contentHnd = handler; } /*! \reimp */ QXmlContentHandler* QXmlSimpleReader::contentHandler() const { const QXmlSimpleReaderPrivate *d = d_func(); return d->contentHnd; } /*! \reimp */ void QXmlSimpleReader::setErrorHandler(QXmlErrorHandler* handler) { Q_D(QXmlSimpleReader); d->errorHnd = handler; } /*! \reimp */ QXmlErrorHandler* QXmlSimpleReader::errorHandler() const { const QXmlSimpleReaderPrivate *d = d_func(); return d->errorHnd; } /*! \reimp */ void QXmlSimpleReader::setLexicalHandler(QXmlLexicalHandler* handler) { Q_D(QXmlSimpleReader); d->lexicalHnd = handler; } /*! \reimp */ QXmlLexicalHandler* QXmlSimpleReader::lexicalHandler() const { const QXmlSimpleReaderPrivate *d = d_func(); return d->lexicalHnd; } /*! \reimp */ void QXmlSimpleReader::setDeclHandler(QXmlDeclHandler* handler) { Q_D(QXmlSimpleReader); d->declHnd = handler; } /*! \reimp */ QXmlDeclHandler* QXmlSimpleReader::declHandler() const { const QXmlSimpleReaderPrivate *d = d_func(); return d->declHnd; } /*! \reimp */ bool QXmlSimpleReader::parse(const QXmlInputSource& input) { return parse(&input, false); } /*! Reads an XML document from \a input and parses it in one pass (non-incrementally). Returns \c true if the parsing was successful; otherwise returns \c false. */ bool QXmlSimpleReader::parse(const QXmlInputSource* input) { return parse(input, false); } /*! Reads an XML document from \a input and parses it. Returns \c true if the parsing is completed successfully; otherwise returns \c false, indicating that an error occurred. If \a incremental is false, this function will return false if the XML file is not read completely. The parsing cannot be continued in this case. If \a incremental is true, the parser does not return false if it reaches the end of the \a input before reaching the end of the XML file. Instead, it stores the state of the parser so that parsing can be continued later when more data is available. In such a case, you can use the function parseContinue() to continue with parsing. This class stores a pointer to the input source \a input and the parseContinue() function tries to read from that input source. Therefore, you should not delete the input source \a input until you no longer need to call parseContinue(). If this function is called with \a incremental set to true while an incremental parse is in progress, a new parsing session will be started, and the previous session will be lost. \sa parseContinue(), QTcpSocket */ bool QXmlSimpleReader::parse(const QXmlInputSource *input, bool incremental) { Q_D(QXmlSimpleReader); d->literalEntitySizes.clear(); d->referencesToOtherEntities.clear(); d->expandedSizes.clear(); if (incremental) { d->initIncrementalParsing(); } else { delete d->parseStack; d->parseStack = 0; } d->init(input); // call the handler if (d->contentHnd) { d->contentHnd->setDocumentLocator(d->locator.data()); if (!d->contentHnd->startDocument()) { d->reportParseError(d->contentHnd->errorString()); d->tags.clear(); return false; } } qt_xml_skipped_entity_in_content = false; return d->parseBeginOrContinue(0, incremental); } /*! Continues incremental parsing, taking input from the QXmlInputSource that was specified with the most recent call to parse(). To use this function, you \e must have called parse() with the incremental argument set to true. Returns \c false if a parsing error occurs; otherwise returns \c true, even if the end of the XML file has not been reached. You can continue parsing at a later stage by calling this function again when there is more data available to parse. Calling this function when there is no data available in the input source indicates to the reader that the end of the XML file has been reached. If the input supplied up to this point was not well-formed then a parsing error occurs, and false is returned. If the input supplied was well-formed, true is returned. It is important to end the input in this way because it allows you to reuse the reader to parse other XML files. Calling this function after the end of file has been reached, but without available data will cause false to be returned whether the previous input was well-formed or not. \sa parse(), QXmlInputSource::data(), QXmlInputSource::next() */ bool QXmlSimpleReader::parseContinue() { Q_D(QXmlSimpleReader); if (d->parseStack == 0 || d->parseStack->isEmpty()) return false; d->initData(); int state = d->parseStack->pop().state; return d->parseBeginOrContinue(state, true); } /* Common part of parse() and parseContinue() */ bool QXmlSimpleReaderPrivate::parseBeginOrContinue(int state, bool incremental) { bool atEndOrig = atEnd(); if (state==0) { if (!parseProlog()) { if (incremental && error.isNull()) { pushParseState(0, 0); return true; } else { tags.clear(); return false; } } state = 1; } if (state==1) { if (!parseElement()) { if (incremental && error.isNull()) { pushParseState(0, 1); return true; } else { tags.clear(); return false; } } state = 2; } // parse Misc* while (!atEnd()) { if (!parseMisc()) { if (incremental && error.isNull()) { pushParseState(0, 2); return true; } else { tags.clear(); return false; } } } if (!atEndOrig && incremental) { // we parsed something at all, so be prepared to come back later pushParseState(0, 2); return true; } // is stack empty? if (!tags.isEmpty() && !error.isNull()) { reportParseError(QLatin1String(XMLERR_UNEXPECTEDEOF)); tags.clear(); return false; } // call the handler if (contentHnd) { delete parseStack; parseStack = 0; if (!contentHnd->endDocument()) { reportParseError(contentHnd->errorString()); return false; } } return true; } // // The following private parse functions have another semantics for the return // value: They return true iff parsing has finished successfully (i.e. the end // of the XML file must be reached!). If one of these functions return false, // there is only an error when d->error.isNULL() is also false. // /* For the incremental parsing, it is very important that the parse...() functions have a certain structure. Since it might be hard to understand how they work, here is a description of the layout of these functions: bool QXmlSimpleReader::parse...() { (1) const signed char Init = 0; ... (2) const signed char Inp... = 0; ... (3) static const signed char table[3][2] = { ... }; signed char state; signed char input; (4) if (d->parseStack == 0 || d->parseStack->isEmpty()) { (4a) ... } else { (4b) ... } for (; ;) { (5) switch (state) { ... } (6) (6a) if (atEnd()) { unexpectedEof(&QXmlSimpleReader::parseNmtoken, state); return false; } (6b) if (determineNameChar(c) != NotName) { ... } (7) state = table[state][input]; (8) switch (state) { ... } } } Explanation: ad 1: constants for the states (used in the transition table) ad 2: constants for the input (used in the transition table) ad 3: the transition table for the state machine ad 4: test if we are in a parseContinue() step a) if no, do inititalizations b) if yes, restore the state and call parse functions recursively ad 5: Do some actions according to the state; from the logical execution order, this code belongs after 8 (see there for an explanation) ad 6: Check the character that is at the actual "cursor" position: a) If we reached the EOF, report either error or push the state (in the case of incremental parsing). b) Otherwise, set the input character constant for the transition table. ad 7: Get the new state according to the input that was read. ad 8: Do some actions according to the state. The last line in every case statement reads new data (i.e. it move the cursor). This can also be done by calling another parse...() function. If you need processing for this state after that, you have to put it into the switch statement 5. This ensures that you have a well defined re-entry point, when you ran out of data. */ /* Parses the prolog [22]. */ bool QXmlSimpleReaderPrivate::parseProlog() { const signed char Init = 0; const signed char EatWS = 1; // eat white spaces const signed char Lt = 2; // '<' read const signed char Em = 3; // '!' read const signed char DocType = 4; // read doctype const signed char Comment = 5; // read comment const signed char CommentR = 6; // same as Comment, but already reported const signed char PInstr = 7; // read PI const signed char PInstrR = 8; // same as PInstr, but already reported const signed char Done = 9; const signed char InpWs = 0; const signed char InpLt = 1; // < const signed char InpQm = 2; // ? const signed char InpEm = 3; // ! const signed char InpD = 4; // D const signed char InpDash = 5; // - const signed char InpUnknown = 6; static const signed char table[9][7] = { /* InpWs InpLt InpQm InpEm InpD InpDash InpUnknown */ { EatWS, Lt, -1, -1, -1, -1, -1 }, // Init { -1, Lt, -1, -1, -1, -1, -1 }, // EatWS { -1, -1, PInstr,Em, Done, -1, Done }, // Lt { -1, -1, -1, -1, DocType, Comment, -1 }, // Em { EatWS, Lt, -1, -1, -1, -1, -1 }, // DocType { EatWS, Lt, -1, -1, -1, -1, -1 }, // Comment { EatWS, Lt, -1, -1, -1, -1, -1 }, // CommentR { EatWS, Lt, -1, -1, -1, -1, -1 }, // PInstr { EatWS, Lt, -1, -1, -1, -1, -1 } // PInstrR }; signed char state; signed char input; if (parseStack == 0 || parseStack->isEmpty()) { xmldecl_possible = true; doctype_read = false; state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseProlog (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseProlog, state); return false; } } } for (;;) { switch (state) { case DocType: if (doctype_read) { reportParseError(QLatin1String(XMLERR_MORETHANONEDOCTYPE)); return false; } else { doctype_read = false; } break; case Comment: if (lexicalHnd) { if (!lexicalHnd->comment(string())) { reportParseError(lexicalHnd->errorString()); return false; } } state = CommentR; break; case PInstr: // call the handler if (contentHnd) { if (xmldecl_possible && !xmlVersion.isEmpty()) { QString value(QLatin1String("version='")); value += xmlVersion; value += QLatin1Char('\''); if (!encoding.isEmpty()) { value += QLatin1String(" encoding='"); value += encoding; value += QLatin1Char('\''); } if (standalone == QXmlSimpleReaderPrivate::Yes) { value += QLatin1String(" standalone='yes'"); } else if (standalone == QXmlSimpleReaderPrivate::No) { value += QLatin1String(" standalone='no'"); } if (!contentHnd->processingInstruction(QLatin1String("xml"), value)) { reportParseError(contentHnd->errorString()); return false; } } else { if (!contentHnd->processingInstruction(name(), string())) { reportParseError(contentHnd->errorString()); return false; } } } // XML declaration only on first position possible xmldecl_possible = false; state = PInstrR; break; case Done: return true; case -1: reportParseError(QLatin1String(XMLERR_ERRORPARSINGELEMENT)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseProlog, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('<')) { input = InpLt; } else if (c == QLatin1Char('?')) { input = InpQm; } else if (c == QLatin1Char('!')) { input = InpEm; } else if (c == QLatin1Char('D')) { input = InpD; } else if (c == QLatin1Char('-')) { input = InpDash; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case EatWS: // XML declaration only on first position possible xmldecl_possible = false; if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseProlog, state); return false; } break; case Lt: next(); break; case Em: // XML declaration only on first position possible xmldecl_possible = false; next(); break; case DocType: if (!parseDoctype()) { parseFailed(&QXmlSimpleReaderPrivate::parseProlog, state); return false; } break; case Comment: case CommentR: if (!parseComment()) { parseFailed(&QXmlSimpleReaderPrivate::parseProlog, state); return false; } break; case PInstr: case PInstrR: parsePI_xmldecl = xmldecl_possible; if (!parsePI()) { parseFailed(&QXmlSimpleReaderPrivate::parseProlog, state); return false; } break; } } return false; } /* Parse an element [39]. Precondition: the opening '<' is already read. */ bool QXmlSimpleReaderPrivate::parseElement() { const int Init = 0; const int ReadName = 1; const int Ws1 = 2; const int STagEnd = 3; const int STagEnd2 = 4; const int ETagBegin = 5; const int ETagBegin2 = 6; const int Ws2 = 7; const int EmptyTag = 8; const int Attrib = 9; const int AttribPro = 10; // like Attrib, but processAttribute was already called const int Ws3 = 11; const int Done = 12; const int InpWs = 0; // whitespace const int InpNameBe = 1; // NameBeginning const int InpGt = 2; // > const int InpSlash = 3; // / const int InpUnknown = 4; static const int table[12][5] = { /* InpWs InpNameBe InpGt InpSlash InpUnknown */ { -1, ReadName, -1, -1, -1 }, // Init { Ws1, Attrib, STagEnd, EmptyTag, -1 }, // ReadName { -1, Attrib, STagEnd, EmptyTag, -1 }, // Ws1 { STagEnd2, STagEnd2, STagEnd2, STagEnd2, STagEnd2 }, // STagEnd { -1, -1, -1, ETagBegin, -1 }, // STagEnd2 { -1, ETagBegin2, -1, -1, -1 }, // ETagBegin { Ws2, -1, Done, -1, -1 }, // ETagBegin2 { -1, -1, Done, -1, -1 }, // Ws2 { -1, -1, Done, -1, -1 }, // EmptyTag { Ws3, Attrib, STagEnd, EmptyTag, -1 }, // Attrib { Ws3, Attrib, STagEnd, EmptyTag, -1 }, // AttribPro { -1, Attrib, STagEnd, EmptyTag, -1 } // Ws3 }; int state; int input; if (parseStack == 0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseElement (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseElement, state); return false; } } } for (;;) { switch (state) { case ReadName: // store it on the stack tags.push(name()); // empty the attributes attList.clear(); if (useNamespaces) namespaceSupport.pushContext(); break; case ETagBegin2: if (!processElementETagBegin2()) return false; break; case Attrib: if (!processElementAttribute()) return false; state = AttribPro; break; case Done: return true; case -1: reportParseError(QLatin1String(XMLERR_ERRORPARSINGELEMENT)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseElement, state); return false; } if (fastDetermineNameChar(c) == NameBeginning) { input = InpNameBe; } else if (c == QLatin1Char('>')) { input = InpGt; } else if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('/')) { input = InpSlash; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case ReadName: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseElement, state); return false; } break; case Ws1: case Ws2: case Ws3: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElement, state); return false; } break; case STagEnd: // call the handler if (contentHnd) { const QString &tagsTop = tags.top(); if (useNamespaces) { QString uri, lname; namespaceSupport.processName(tagsTop, false, uri, lname); if (!contentHnd->startElement(uri, lname, tagsTop, attList)) { reportParseError(contentHnd->errorString()); return false; } } else { if (!contentHnd->startElement(QString(), QString(), tagsTop, attList)) { reportParseError(contentHnd->errorString()); return false; } } } next(); break; case STagEnd2: if (!parseContent()) { parseFailed(&QXmlSimpleReaderPrivate::parseElement, state); return false; } break; case ETagBegin: next(); break; case ETagBegin2: // get the name of the tag parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseElement, state); return false; } break; case EmptyTag: if (tags.isEmpty()) { reportParseError(QLatin1String(XMLERR_TAGMISMATCH)); return false; } if (!processElementEmptyTag()) return false; next(); break; case Attrib: case AttribPro: // get name and value of attribute if (!parseAttribute()) { parseFailed(&QXmlSimpleReaderPrivate::parseElement, state); return false; } break; case Done: next(); break; } } return false; } /* Helper to break down the size of the code in the case statement. Return false on error, otherwise true. */ bool QXmlSimpleReaderPrivate::processElementEmptyTag() { QString uri, lname; // pop the stack and call the handler if (contentHnd) { if (useNamespaces) { // report startElement first... namespaceSupport.processName(tags.top(), false, uri, lname); if (!contentHnd->startElement(uri, lname, tags.top(), attList)) { reportParseError(contentHnd->errorString()); return false; } // ... followed by endElement... if (!contentHnd->endElement(uri, lname, tags.pop())) { reportParseError(contentHnd->errorString()); return false; } // ... followed by endPrefixMapping QStringList prefixesBefore, prefixesAfter; if (contentHnd) { prefixesBefore = namespaceSupport.prefixes(); } namespaceSupport.popContext(); // call the handler for prefix mapping prefixesAfter = namespaceSupport.prefixes(); for (QStringList::Iterator it = prefixesBefore.begin(); it != prefixesBefore.end(); ++it) { if (!prefixesAfter.contains(*it)) { if (!contentHnd->endPrefixMapping(*it)) { reportParseError(contentHnd->errorString()); return false; } } } } else { // report startElement first... if (!contentHnd->startElement(QString(), QString(), tags.top(), attList)) { reportParseError(contentHnd->errorString()); return false; } // ... followed by endElement if (!contentHnd->endElement(QString(), QString(), tags.pop())) { reportParseError(contentHnd->errorString()); return false; } } } else { tags.pop_back(); namespaceSupport.popContext(); } return true; } /* Helper to break down the size of the code in the case statement. Return false on error, otherwise true. */ bool QXmlSimpleReaderPrivate::processElementETagBegin2() { const QString &name = QXmlSimpleReaderPrivate::name(); // pop the stack and compare it with the name if (tags.pop() != name) { reportParseError(QLatin1String(XMLERR_TAGMISMATCH)); return false; } // call the handler if (contentHnd) { QString uri, lname; if (useNamespaces) namespaceSupport.processName(name, false, uri, lname); if (!contentHnd->endElement(uri, lname, name)) { reportParseError(contentHnd->errorString()); return false; } } if (useNamespaces) { NamespaceMap prefixesBefore, prefixesAfter; if (contentHnd) prefixesBefore = namespaceSupport.d->ns; namespaceSupport.popContext(); // call the handler for prefix mapping if (contentHnd) { prefixesAfter = namespaceSupport.d->ns; if (prefixesBefore.size() != prefixesAfter.size()) { for (NamespaceMap::const_iterator it = prefixesBefore.constBegin(); it != prefixesBefore.constEnd(); ++it) { if (!it.key().isEmpty() && !prefixesAfter.contains(it.key())) { if (!contentHnd->endPrefixMapping(it.key())) { reportParseError(contentHnd->errorString()); return false; } } } } } } return true; } /* Helper to break down the size of the code in the case statement. Return false on error, otherwise true. */ bool QXmlSimpleReaderPrivate::processElementAttribute() { QString uri, lname, prefix; const QString &name = QXmlSimpleReaderPrivate::name(); const QString &string = QXmlSimpleReaderPrivate::string(); // add the attribute to the list if (useNamespaces) { // is it a namespace declaration? namespaceSupport.splitName(name, prefix, lname); if (prefix == QLatin1String("xmlns")) { // namespace declaration namespaceSupport.setPrefix(lname, string); if (useNamespacePrefixes) { // according to http://www.w3.org/2000/xmlns/, the "prefix" // xmlns maps to the namespace name // http://www.w3.org/2000/xmlns/ attList.append(name, QLatin1String("http://www.w3.org/2000/xmlns/"), lname, string); } // call the handler for prefix mapping if (contentHnd) { if (!contentHnd->startPrefixMapping(lname, string)) { reportParseError(contentHnd->errorString()); return false; } } } else { // no namespace delcaration namespaceSupport.processName(name, true, uri, lname); attList.append(name, uri, lname, string); } } else { // no namespace support attList.append(name, uri, lname, string); } return true; } /* Parse a content [43]. A content is only used between tags. If a end tag is found the < is already read and the head stand on the '/' of the end tag '</name>'. */ bool QXmlSimpleReaderPrivate::parseContent() { const signed char Init = 0; const signed char ChD = 1; // CharData const signed char ChD1 = 2; // CharData help state const signed char ChD2 = 3; // CharData help state const signed char Ref = 4; // Reference const signed char Lt = 5; // '<' read const signed char PInstr = 6; // PI const signed char PInstrR = 7; // same as PInstr, but already reported const signed char Elem = 8; // Element const signed char Em = 9; // '!' read const signed char Com = 10; // Comment const signed char ComR = 11; // same as Com, but already reported const signed char CDS = 12; // CDSect const signed char CDS1 = 13; // read a CDSect const signed char CDS2 = 14; // read a CDSect (help state) const signed char CDS3 = 15; // read a CDSect (help state) const signed char Done = 16; // finished reading content const signed char InpLt = 0; // < const signed char InpGt = 1; // > const signed char InpSlash = 2; // / const signed char InpQMark = 3; // ? const signed char InpEMark = 4; // ! const signed char InpAmp = 5; // & const signed char InpDash = 6; // - const signed char InpOpenB = 7; // [ const signed char InpCloseB = 8; //] const signed char InpUnknown = 9; static const signed char mapCLT2FSMChar[] = { InpUnknown, // white space InpUnknown, // % InpAmp, // & InpGt, // > InpLt, // < InpSlash, // / InpQMark, // ? InpEMark, // ! InpDash, // - InpCloseB, //] InpOpenB, // [ InpUnknown, // = InpUnknown, // " InpUnknown, // ' InpUnknown // unknown }; static const signed char table[16][10] = { /* InpLt InpGt InpSlash InpQMark InpEMark InpAmp InpDash InpOpenB InpCloseB InpUnknown */ { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD1, ChD }, // Init { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD1, ChD }, // ChD { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD2, ChD }, // ChD1 { Lt, -1, ChD, ChD, ChD, Ref, ChD, ChD, ChD2, ChD }, // ChD2 { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD, ChD }, // Ref (same as Init) { -1, -1, Done, PInstr, Em, -1, -1, -1, -1, Elem }, // Lt { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD, ChD }, // PInstr (same as Init) { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD, ChD }, // PInstrR { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD, ChD }, // Elem (same as Init) { -1, -1, -1, -1, -1, -1, Com, CDS, -1, -1 }, // Em { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD, ChD }, // Com (same as Init) { Lt, ChD, ChD, ChD, ChD, Ref, ChD, ChD, ChD, ChD }, // ComR { CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS2, CDS1 }, // CDS { CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS2, CDS1 }, // CDS1 { CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS3, CDS1 }, // CDS2 { CDS1, Init, CDS1, CDS1, CDS1, CDS1, CDS1, CDS1, CDS3, CDS1 } // CDS3 }; signed char state; signed char input; if (parseStack == 0 || parseStack->isEmpty()) { contentCharDataRead = false; state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseContent (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } } } for (;;) { switch (state) { case Ref: if (!contentCharDataRead) contentCharDataRead = parseReference_charDataRead; break; case PInstr: if (contentHnd) { if (!contentHnd->processingInstruction(name(),string())) { reportParseError(contentHnd->errorString()); return false; } } state = PInstrR; break; case Com: if (lexicalHnd) { if (!lexicalHnd->comment(string())) { reportParseError(lexicalHnd->errorString()); return false; } } state = ComR; break; case CDS: stringClear(); break; case CDS2: if (!atEnd() && c != QLatin1Char(']')) stringAddC(QLatin1Char(']')); break; case CDS3: // test if this skipping was legal if (!atEnd()) { if (c == QLatin1Char('>')) { // the end of the CDSect if (lexicalHnd) { if (!lexicalHnd->startCDATA()) { reportParseError(lexicalHnd->errorString()); return false; } } if (contentHnd) { if (!contentHnd->characters(string())) { reportParseError(contentHnd->errorString()); return false; } } if (lexicalHnd) { if (!lexicalHnd->endCDATA()) { reportParseError(lexicalHnd->errorString()); return false; } } } else if (c == QLatin1Char(']')) { // three or more ']' stringAddC(QLatin1Char(']')); } else { // after ']]' comes another character stringAddC(QLatin1Char(']')); stringAddC(QLatin1Char(']')); } } break; case Done: // call the handler for CharData if (contentHnd) { if (contentCharDataRead) { if (reportWhitespaceCharData || !string().simplified().isEmpty()) { if (!contentHnd->characters(string())) { reportParseError(contentHnd->errorString()); return false; } } } } // Done return true; case -1: // Error reportParseError(QLatin1String(XMLERR_ERRORPARSINGCONTENT)); return false; } // get input (use lookup-table instead of nested ifs for performance // reasons) if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseContent, state); return false; } if (c.row()) { input = InpUnknown; } else { input = mapCLT2FSMChar[charLookupTable[c.cell()]]; } state = table[state][input]; switch (state) { case Init: // skip the ending '>' of a CDATASection next(); break; case ChD: // on first call: clear string if (!contentCharDataRead) { contentCharDataRead = true; stringClear(); } stringAddC(); if (reportEntities) { if (!reportEndEntities()) return false; } next(); break; case ChD1: // on first call: clear string if (!contentCharDataRead) { contentCharDataRead = true; stringClear(); } stringAddC(); if (reportEntities) { if (!reportEndEntities()) return false; } next(); break; case ChD2: stringAddC(); if (reportEntities) { if (!reportEndEntities()) return false; } next(); break; case Ref: if (!contentCharDataRead) { // reference may be CharData; so clear string to be safe stringClear(); parseReference_context = InContent; if (!parseReference()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } } else { if (reportEntities) { // report character data in chunks if (contentHnd) { if (reportWhitespaceCharData || !string().simplified().isEmpty()) { if (!contentHnd->characters(string())) { reportParseError(contentHnd->errorString()); return false; } } } stringClear(); } parseReference_context = InContent; if (!parseReference()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } } break; case Lt: // call the handler for CharData if (contentHnd) { if (contentCharDataRead) { if (reportWhitespaceCharData || !string().simplified().isEmpty()) { if (!contentHnd->characters(string())) { reportParseError(contentHnd->errorString()); return false; } } } } contentCharDataRead = false; next(); break; case PInstr: case PInstrR: parsePI_xmldecl = false; if (!parsePI()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } break; case Elem: if (!parseElement()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } break; case Em: next(); break; case Com: case ComR: if (!parseComment()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } break; case CDS: parseString_s = QLatin1String("[CDATA["); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseContent, state); return false; } break; case CDS1: stringAddC(); next(); break; case CDS2: // skip ']' next(); break; case CDS3: // skip ']'... next(); break; } } return false; } bool QXmlSimpleReaderPrivate::reportEndEntities() { int count = (int)xmlRefStack.count(); while (count != 0 && xmlRefStack.top().isEmpty()) { if (contentHnd) { if (reportWhitespaceCharData || !string().simplified().isEmpty()) { if (!contentHnd->characters(string())) { reportParseError(contentHnd->errorString()); return false; } } } stringClear(); if (lexicalHnd) { if (!lexicalHnd->endEntity(xmlRefStack.top().name)) { reportParseError(lexicalHnd->errorString()); return false; } } xmlRefStack.pop_back(); count--; } return true; } /* Parse Misc [27]. */ bool QXmlSimpleReaderPrivate::parseMisc() { const signed char Init = 0; const signed char Lt = 1; // '<' was read const signed char Comment = 2; // read comment const signed char eatWS = 3; // eat whitespaces const signed char PInstr = 4; // read PI const signed char Comment2 = 5; // read comment const signed char InpWs = 0; // S const signed char InpLt = 1; // < const signed char InpQm = 2; // ? const signed char InpEm = 3; // ! const signed char InpUnknown = 4; static const signed char table[3][5] = { /* InpWs InpLt InpQm InpEm InpUnknown */ { eatWS, Lt, -1, -1, -1 }, // Init { -1, -1, PInstr,Comment, -1 }, // Lt { -1, -1, -1, -1, Comment2 } // Comment }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseMisc (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseMisc, state); return false; } } } for (;;) { switch (state) { case eatWS: return true; case PInstr: if (contentHnd) { if (!contentHnd->processingInstruction(name(),string())) { reportParseError(contentHnd->errorString()); return false; } } return true; case Comment2: if (lexicalHnd) { if (!lexicalHnd->comment(string())) { reportParseError(lexicalHnd->errorString()); return false; } } return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseMisc, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('<')) { input = InpLt; } else if (c == QLatin1Char('?')) { input = InpQm; } else if (c == QLatin1Char('!')) { input = InpEm; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case eatWS: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseMisc, state); return false; } break; case Lt: next(); break; case PInstr: parsePI_xmldecl = false; if (!parsePI()) { parseFailed(&QXmlSimpleReaderPrivate::parseMisc, state); return false; } break; case Comment: next(); break; case Comment2: if (!parseComment()) { parseFailed(&QXmlSimpleReaderPrivate::parseMisc, state); return false; } break; } } return false; } /* Parse a processing instruction [16]. If xmldec is true, it tries to parse a PI or a XML declaration [23]. Precondition: the beginning '<' of the PI is already read and the head stand on the '?' of '<?'. If this funktion was successful, the head-position is on the first character after the PI. */ bool QXmlSimpleReaderPrivate::parsePI() { const signed char Init = 0; const signed char QmI = 1; // ? was read const signed char Name = 2; // read Name const signed char XMLDecl = 3; // read XMLDecl const signed char Ws1 = 4; // eat ws after "xml" of XMLDecl const signed char PInstr = 5; // read PI const signed char Ws2 = 6; // eat ws after Name of PI const signed char Version = 7; // read versionInfo const signed char Ws3 = 8; // eat ws after versionInfo const signed char EorSD = 9; // read EDecl or SDDecl const signed char Ws4 = 10; // eat ws after EDecl or SDDecl const signed char SD = 11; // read SDDecl const signed char Ws5 = 12; // eat ws after SDDecl const signed char ADone = 13; // almost done const signed char Char = 14; // Char was read const signed char Qm = 15; // Qm was read const signed char Done = 16; // finished reading content const signed char InpWs = 0; // whitespace const signed char InpNameBe = 1; // NameBeginning const signed char InpGt = 2; // > const signed char InpQm = 3; // ? const signed char InpUnknown = 4; static const signed char table[16][5] = { /* InpWs, InpNameBe InpGt InpQm InpUnknown */ { -1, -1, -1, QmI, -1 }, // Init { -1, Name, -1, -1, -1 }, // QmI { -1, -1, -1, -1, -1 }, // Name (this state is left not through input) { Ws1, -1, -1, -1, -1 }, // XMLDecl { -1, Version, -1, -1, -1 }, // Ws1 { Ws2, -1, -1, Qm, -1 }, // PInstr { Char, Char, Char, Qm, Char }, // Ws2 { Ws3, -1, -1, ADone, -1 }, // Version { -1, EorSD, -1, ADone, -1 }, // Ws3 { Ws4, -1, -1, ADone, -1 }, // EorSD { -1, SD, -1, ADone, -1 }, // Ws4 { Ws5, -1, -1, ADone, -1 }, // SD { -1, -1, -1, ADone, -1 }, // Ws5 { -1, -1, Done, -1, -1 }, // ADone { Char, Char, Char, Qm, Char }, // Char { Char, Char, Done, Qm, Char }, // Qm }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parsePI (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parsePI, state); return false; } } } for (;;) { switch (state) { case Name: // test what name was read and determine the next state // (not very beautiful, I admit) if (name().toLower() == QLatin1String("xml")) { if (parsePI_xmldecl && name() == QLatin1String("xml")) { state = XMLDecl; } else { reportParseError(QLatin1String(XMLERR_INVALIDNAMEFORPI)); return false; } } else { state = PInstr; stringClear(); } break; case Version: // get version (syntax like an attribute) if (name() != QLatin1String("version")) { reportParseError(QLatin1String(XMLERR_VERSIONEXPECTED)); return false; } xmlVersion = string(); break; case EorSD: // get the EDecl or SDDecl (syntax like an attribute) if (name() == QLatin1String("standalone")) { if (string()== QLatin1String("yes")) { standalone = QXmlSimpleReaderPrivate::Yes; } else if (string() == QLatin1String("no")) { standalone = QXmlSimpleReaderPrivate::No; } else { reportParseError(QLatin1String(XMLERR_WRONGVALUEFORSDECL)); return false; } } else if (name() == QLatin1String("encoding")) { encoding = string(); } else { reportParseError(QLatin1String(XMLERR_EDECLORSDDECLEXPECTED)); return false; } break; case SD: if (name() != QLatin1String("standalone")) { reportParseError(QLatin1String(XMLERR_SDDECLEXPECTED)); return false; } if (string() == QLatin1String("yes")) { standalone = QXmlSimpleReaderPrivate::Yes; } else if (string() == QLatin1String("no")) { standalone = QXmlSimpleReaderPrivate::No; } else { reportParseError(QLatin1String(XMLERR_WRONGVALUEFORSDECL)); return false; } break; case Qm: // test if the skipping was legal if (!atEnd() && c != QLatin1Char('>')) stringAddC(QLatin1Char('?')); break; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parsePI, state); return false; } if (is_S(c)) { input = InpWs; } else if (determineNameChar(c) == NameBeginning) { input = InpNameBe; } else if (c == QLatin1Char('>')) { input = InpGt; } else if (c == QLatin1Char('?')) { input = InpQm; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case QmI: next(); break; case Name: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parsePI, state); return false; } break; case Ws1: case Ws2: case Ws3: case Ws4: case Ws5: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parsePI, state); return false; } break; case Version: if (!parseAttribute()) { parseFailed(&QXmlSimpleReaderPrivate::parsePI, state); return false; } break; case EorSD: if (!parseAttribute()) { parseFailed(&QXmlSimpleReaderPrivate::parsePI, state); return false; } break; case SD: // get the SDDecl (syntax like an attribute) if (standalone != QXmlSimpleReaderPrivate::Unknown) { // already parsed the standalone declaration reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (!parseAttribute()) { parseFailed(&QXmlSimpleReaderPrivate::parsePI, state); return false; } break; case ADone: next(); break; case Char: stringAddC(); next(); break; case Qm: // skip the '?' next(); break; case Done: next(); break; } } return false; } /* Parse a document type definition (doctypedecl [28]). Precondition: the beginning '<!' of the doctype is already read the head stands on the 'D' of '<!DOCTYPE'. If this function was successful, the head-position is on the first character after the document type definition. */ bool QXmlSimpleReaderPrivate::parseDoctype() { const signed char Init = 0; const signed char Doctype = 1; // read the doctype const signed char Ws1 = 2; // eat_ws const signed char Doctype2 = 3; // read the doctype, part 2 const signed char Ws2 = 4; // eat_ws const signed char Sys = 5; // read SYSTEM or PUBLIC const signed char Ws3 = 6; // eat_ws const signed char MP = 7; // markupdecl or PEReference const signed char MPR = 8; // same as MP, but already reported const signed char PER = 9; // PERReference const signed char Mup = 10; // markupdecl const signed char Ws4 = 11; // eat_ws const signed char MPE = 12; // end of markupdecl or PEReference const signed char Done = 13; const signed char InpWs = 0; const signed char InpD = 1; // 'D' const signed char InpS = 2; // 'S' or 'P' const signed char InpOB = 3; // [ const signed char InpCB = 4; //] const signed char InpPer = 5; // % const signed char InpGt = 6; // > const signed char InpUnknown = 7; static const signed char table[13][8] = { /* InpWs, InpD InpS InpOB InpCB InpPer InpGt InpUnknown */ { -1, Doctype, -1, -1, -1, -1, -1, -1 }, // Init { Ws1, -1, -1, -1, -1, -1, -1, -1 }, // Doctype { -1, Doctype2, Doctype2, -1, -1, -1, -1, Doctype2 }, // Ws1 { Ws2, -1, Sys, MP, -1, -1, Done, -1 }, // Doctype2 { -1, -1, Sys, MP, -1, -1, Done, -1 }, // Ws2 { Ws3, -1, -1, MP, -1, -1, Done, -1 }, // Sys { -1, -1, -1, MP, -1, -1, Done, -1 }, // Ws3 { -1, -1, -1, -1, MPE, PER, -1, Mup }, // MP { -1, -1, -1, -1, MPE, PER, -1, Mup }, // MPR { Ws4, -1, -1, -1, MPE, PER, -1, Mup }, // PER { Ws4, -1, -1, -1, MPE, PER, -1, Mup }, // Mup { -1, -1, -1, -1, MPE, PER, -1, Mup }, // Ws4 { -1, -1, -1, -1, -1, -1, Done, -1 } // MPE }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { startDTDwasReported = false; systemId.clear(); publicId.clear(); state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseDoctype (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } } } for (;;) { switch (state) { case Doctype2: doctype = name(); break; case MP: if (!startDTDwasReported && lexicalHnd ) { startDTDwasReported = true; if (!lexicalHnd->startDTD(doctype, publicId, systemId)) { reportParseError(lexicalHnd->errorString()); return false; } } state = MPR; break; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_ERRORPARSINGDOCTYPE)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('D')) { input = InpD; } else if (c == QLatin1Char('S')) { input = InpS; } else if (c == QLatin1Char('P')) { input = InpS; } else if (c == QLatin1Char('[')) { input = InpOB; } else if (c == QLatin1Char(']')) { input = InpCB; } else if (c == QLatin1Char('%')) { input = InpPer; } else if (c == QLatin1Char('>')) { input = InpGt; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Doctype: parseString_s = QLatin1String("DOCTYPE"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case Ws1: case Ws2: case Ws3: case Ws4: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case Doctype2: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case Sys: parseExternalID_allowPublicID = false; if (!parseExternalID()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } thisPublicId = publicId; thisSystemId = systemId; break; case MP: case MPR: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case PER: parsePEReference_context = InDTD; if (!parsePEReference()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case Mup: if (dtdRecursionLimit > 0 && parameterEntities.size() > dtdRecursionLimit) { reportParseError(QString::fromLatin1( "DTD parsing exceeded recursion limit of %1.").arg(dtdRecursionLimit)); return false; } if (!parseMarkupdecl()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case MPE: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseDoctype, state); return false; } break; case Done: if (lexicalHnd) { if (!startDTDwasReported) { startDTDwasReported = true; if (!lexicalHnd->startDTD(doctype, publicId, systemId)) { reportParseError(lexicalHnd->errorString()); return false; } } if (!lexicalHnd->endDTD()) { reportParseError(lexicalHnd->errorString()); return false; } } next(); break; } } return false; } /* Parse a ExternalID [75]. If allowPublicID is true parse ExternalID [75] or PublicID [83]. */ bool QXmlSimpleReaderPrivate::parseExternalID() { const signed char Init = 0; const signed char Sys = 1; // parse 'SYSTEM' const signed char SysWS = 2; // parse the whitespace after 'SYSTEM' const signed char SysSQ = 3; // parse SystemLiteral with ' const signed char SysSQ2 = 4; // parse SystemLiteral with ' const signed char SysDQ = 5; // parse SystemLiteral with " const signed char SysDQ2 = 6; // parse SystemLiteral with " const signed char Pub = 7; // parse 'PUBLIC' const signed char PubWS = 8; // parse the whitespace after 'PUBLIC' const signed char PubSQ = 9; // parse PubidLiteral with ' const signed char PubSQ2 = 10; // parse PubidLiteral with ' const signed char PubDQ = 11; // parse PubidLiteral with " const signed char PubDQ2 = 12; // parse PubidLiteral with " const signed char PubE = 13; // finished parsing the PubidLiteral const signed char PubWS2 = 14; // parse the whitespace after the PubidLiteral const signed char PDone = 15; // done if allowPublicID is true const signed char Done = 16; const signed char InpSQ = 0; // ' const signed char InpDQ = 1; // " const signed char InpS = 2; // S const signed char InpP = 3; // P const signed char InpWs = 4; // white space const signed char InpUnknown = 5; static const signed char table[15][6] = { /* InpSQ InpDQ InpS InpP InpWs InpUnknown */ { -1, -1, Sys, Pub, -1, -1 }, // Init { -1, -1, -1, -1, SysWS, -1 }, // Sys { SysSQ, SysDQ, -1, -1, -1, -1 }, // SysWS { Done, SysSQ2, SysSQ2, SysSQ2, SysSQ2, SysSQ2 }, // SysSQ { Done, SysSQ2, SysSQ2, SysSQ2, SysSQ2, SysSQ2 }, // SysSQ2 { SysDQ2, Done, SysDQ2, SysDQ2, SysDQ2, SysDQ2 }, // SysDQ { SysDQ2, Done, SysDQ2, SysDQ2, SysDQ2, SysDQ2 }, // SysDQ2 { -1, -1, -1, -1, PubWS, -1 }, // Pub { PubSQ, PubDQ, -1, -1, -1, -1 }, // PubWS { PubE, -1, PubSQ2, PubSQ2, PubSQ2, PubSQ2 }, // PubSQ { PubE, -1, PubSQ2, PubSQ2, PubSQ2, PubSQ2 }, // PubSQ2 { -1, PubE, PubDQ2, PubDQ2, PubDQ2, PubDQ2 }, // PubDQ { -1, PubE, PubDQ2, PubDQ2, PubDQ2, PubDQ2 }, // PubDQ2 { PDone, PDone, PDone, PDone, PubWS2, PDone }, // PubE { SysSQ, SysDQ, PDone, PDone, PDone, PDone } // PubWS2 }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { systemId.clear(); publicId.clear(); state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseExternalID (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } } } for (;;) { switch (state) { case PDone: if (parseExternalID_allowPublicID) { publicId = string(); return true; } else { reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('\'')) { input = InpSQ; } else if (c == QLatin1Char('"')) { input = InpDQ; } else if (c == QLatin1Char('S')) { input = InpS; } else if (c == QLatin1Char('P')) { input = InpP; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Sys: parseString_s = QLatin1String("SYSTEM"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } break; case SysWS: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } break; case SysSQ: case SysDQ: stringClear(); next(); break; case SysSQ2: case SysDQ2: stringAddC(); next(); break; case Pub: parseString_s = QLatin1String("PUBLIC"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } break; case PubWS: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } break; case PubSQ: case PubDQ: stringClear(); next(); break; case PubSQ2: case PubDQ2: stringAddC(); next(); break; case PubE: next(); break; case PubWS2: publicId = string(); if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseExternalID, state); return false; } break; case Done: systemId = string(); next(); break; } } return false; } /* Parse a markupdecl [29]. */ bool QXmlSimpleReaderPrivate::parseMarkupdecl() { const signed char Init = 0; const signed char Lt = 1; // < was read const signed char Em = 2; // ! was read const signed char CE = 3; // E was read const signed char Qm = 4; // ? was read const signed char Dash = 5; // - was read const signed char CA = 6; // A was read const signed char CEL = 7; // EL was read const signed char CEN = 8; // EN was read const signed char CN = 9; // N was read const signed char Done = 10; const signed char InpLt = 0; // < const signed char InpQm = 1; // ? const signed char InpEm = 2; // ! const signed char InpDash = 3; // - const signed char InpA = 4; // A const signed char InpE = 5; // E const signed char InpL = 6; // L const signed char InpN = 7; // N const signed char InpUnknown = 8; static const signed char table[4][9] = { /* InpLt InpQm InpEm InpDash InpA InpE InpL InpN InpUnknown */ { Lt, -1, -1, -1, -1, -1, -1, -1, -1 }, // Init { -1, Qm, Em, -1, -1, -1, -1, -1, -1 }, // Lt { -1, -1, -1, Dash, CA, CE, -1, CN, -1 }, // Em { -1, -1, -1, -1, -1, -1, CEL, CEN, -1 } // CE }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseMarkupdecl (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } } } for (;;) { switch (state) { case Qm: if (contentHnd) { if (!contentHnd->processingInstruction(name(),string())) { reportParseError(contentHnd->errorString()); return false; } } return true; case Dash: if (lexicalHnd) { if (!lexicalHnd->comment(string())) { reportParseError(lexicalHnd->errorString()); return false; } } return true; case CA: return true; case CEL: return true; case CEN: return true; case CN: return true; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } if (c == QLatin1Char('<')) { input = InpLt; } else if (c == QLatin1Char('?')) { input = InpQm; } else if (c == QLatin1Char('!')) { input = InpEm; } else if (c == QLatin1Char('-')) { input = InpDash; } else if (c == QLatin1Char('A')) { input = InpA; } else if (c == QLatin1Char('E')) { input = InpE; } else if (c == QLatin1Char('L')) { input = InpL; } else if (c == QLatin1Char('N')) { input = InpN; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Lt: next(); break; case Em: next(); break; case CE: next(); break; case Qm: parsePI_xmldecl = false; if (!parsePI()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } break; case Dash: if (!parseComment()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } break; case CA: if (!parseAttlistDecl()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } break; case CEL: if (!parseElementDecl()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } break; case CEN: if (!parseEntityDecl()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } break; case CN: if (!parseNotationDecl()) { parseFailed(&QXmlSimpleReaderPrivate::parseMarkupdecl, state); return false; } break; } } return false; } /* Parse a PEReference [69] */ bool QXmlSimpleReaderPrivate::parsePEReference() { const signed char Init = 0; const signed char Next = 1; const signed char Name = 2; const signed char NameR = 3; // same as Name, but already reported const signed char Done = 4; const signed char InpSemi = 0; // ; const signed char InpPer = 1; // % const signed char InpUnknown = 2; static const signed char table[4][3] = { /* InpSemi InpPer InpUnknown */ { -1, Next, -1 }, // Init { -1, -1, Name }, // Next { Done, -1, -1 }, // Name { Done, -1, -1 } // NameR }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parsePEReference (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parsePEReference, state); return false; } } } for (;;) { switch (state) { case Name: { bool skipIt = true; QString xmlRefString; QMap<QString,QString>::Iterator it; it = parameterEntities.find(ref()); if (it != parameterEntities.end()) { skipIt = false; xmlRefString = *it; } else if (entityRes) { QMap<QString,QXmlSimpleReaderPrivate::ExternParameterEntity>::Iterator it2; it2 = externParameterEntities.find(ref()); QXmlInputSource *ret = 0; if (it2 != externParameterEntities.end()) { if (!entityRes->resolveEntity((*it2).publicId, (*it2).systemId, ret)) { delete ret; reportParseError(entityRes->errorString()); return false; } if (ret) { xmlRefString = ret->data(); delete ret; if (!stripTextDecl(xmlRefString)) { reportParseError(QLatin1String(XMLERR_ERRORINTEXTDECL)); return false; } skipIt = false; } } } if (skipIt) { if (contentHnd) { if (!contentHnd->skippedEntity(QLatin1Char('%') + ref())) { reportParseError(contentHnd->errorString()); return false; } } } else { if (parsePEReference_context == InEntityValue) { // Included in literal if (!insertXmlRef(xmlRefString, ref(), true)) return false; } else if (parsePEReference_context == InDTD) { // Included as PE if (!insertXmlRef(QLatin1Char(' ') + xmlRefString + QLatin1Char(' '), ref(), false)) return false; } } } state = NameR; break; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parsePEReference, state); return false; } if (c == QLatin1Char(';')) { input = InpSemi; } else if (c == QLatin1Char('%')) { input = InpPer; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Next: next(); break; case Name: case NameR: parseName_useRef = true; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parsePEReference, state); return false; } break; case Done: next(); break; } } return false; } /* Parse a AttlistDecl [52]. Precondition: the beginning '<!' is already read and the head stands on the 'A' of '<!ATTLIST' */ bool QXmlSimpleReaderPrivate::parseAttlistDecl() { const signed char Init = 0; const signed char Attlist = 1; // parse the string "ATTLIST" const signed char Ws = 2; // whitespace read const signed char Name = 3; // parse name const signed char Ws1 = 4; // whitespace read const signed char Attdef = 5; // parse the AttDef const signed char Ws2 = 6; // whitespace read const signed char Atttype = 7; // parse the AttType const signed char Ws3 = 8; // whitespace read const signed char DDecH = 9; // DefaultDecl with # const signed char DefReq = 10; // parse the string "REQUIRED" const signed char DefImp = 11; // parse the string "IMPLIED" const signed char DefFix = 12; // parse the string "FIXED" const signed char Attval = 13; // parse the AttValue const signed char Ws4 = 14; // whitespace read const signed char Done = 15; const signed char InpWs = 0; // white space const signed char InpGt = 1; // > const signed char InpHash = 2; // # const signed char InpA = 3; // A const signed char InpI = 4; // I const signed char InpF = 5; // F const signed char InpR = 6; // R const signed char InpUnknown = 7; static const signed char table[15][8] = { /* InpWs InpGt InpHash InpA InpI InpF InpR InpUnknown */ { -1, -1, -1, Attlist, -1, -1, -1, -1 }, // Init { Ws, -1, -1, -1, -1, -1, -1, -1 }, // Attlist { -1, -1, -1, Name, Name, Name, Name, Name }, // Ws { Ws1, Done, Attdef, Attdef, Attdef, Attdef, Attdef, Attdef }, // Name { -1, Done, Attdef, Attdef, Attdef, Attdef, Attdef, Attdef }, // Ws1 { Ws2, -1, -1, -1, -1, -1, -1, -1 }, // Attdef { -1, Atttype, Atttype, Atttype, Atttype, Atttype, Atttype, Atttype }, // Ws2 { Ws3, -1, -1, -1, -1, -1, -1, -1 }, // Attype { -1, Attval, DDecH, Attval, Attval, Attval, Attval, Attval }, // Ws3 { -1, -1, -1, -1, DefImp, DefFix, DefReq, -1 }, // DDecH { Ws4, Ws4, -1, -1, -1, -1, -1, -1 }, // DefReq { Ws4, Ws4, -1, -1, -1, -1, -1, -1 }, // DefImp { Ws3, -1, -1, -1, -1, -1, -1, -1 }, // DefFix { Ws4, Ws4, -1, -1, -1, -1, -1, -1 }, // Attval { -1, Done, Attdef, Attdef, Attdef, Attdef, Attdef, Attdef } // Ws4 }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseAttlistDecl (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } } } for (;;) { switch (state) { case Name: attDeclEName = name(); break; case Attdef: attDeclAName = name(); break; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('>')) { input = InpGt; } else if (c == QLatin1Char('#')) { input = InpHash; } else if (c == QLatin1Char('A')) { input = InpA; } else if (c == QLatin1Char('I')) { input = InpI; } else if (c == QLatin1Char('F')) { input = InpF; } else if (c == QLatin1Char('R')) { input = InpR; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Attlist: parseString_s = QLatin1String("ATTLIST"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Ws: case Ws1: case Ws2: case Ws3: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Name: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Attdef: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Atttype: if (!parseAttType()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case DDecH: next(); break; case DefReq: parseString_s = QLatin1String("REQUIRED"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case DefImp: parseString_s = QLatin1String("IMPLIED"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case DefFix: parseString_s = QLatin1String("FIXED"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Attval: if (!parseAttValue()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Ws4: if (declHnd) { // ### not all values are computed yet... if (!declHnd->attributeDecl(attDeclEName, attDeclAName, QLatin1String(""), QLatin1String(""), QLatin1String(""))) { reportParseError(declHnd->errorString()); return false; } } if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttlistDecl, state); return false; } break; case Done: next(); break; } } return false; } /* Parse a AttType [54] */ bool QXmlSimpleReaderPrivate::parseAttType() { const signed char Init = 0; const signed char ST = 1; // StringType const signed char TTI = 2; // TokenizedType starting with 'I' const signed char TTI2 = 3; // TokenizedType helpstate const signed char TTI3 = 4; // TokenizedType helpstate const signed char TTE = 5; // TokenizedType starting with 'E' const signed char TTEY = 6; // TokenizedType starting with 'ENTITY' const signed char TTEI = 7; // TokenizedType starting with 'ENTITI' const signed char N = 8; // N read (TokenizedType or Notation) const signed char TTNM = 9; // TokenizedType starting with 'NM' const signed char TTNM2 = 10; // TokenizedType helpstate const signed char NO = 11; // Notation const signed char NO2 = 12; // Notation helpstate const signed char NO3 = 13; // Notation helpstate const signed char NOName = 14; // Notation, read name const signed char NO4 = 15; // Notation helpstate const signed char EN = 16; // Enumeration const signed char ENNmt = 17; // Enumeration, read Nmtoken const signed char EN2 = 18; // Enumeration helpstate const signed char ADone = 19; // almost done (make next and accept) const signed char Done = 20; const signed char InpWs = 0; // whitespace const signed char InpOp = 1; // ( const signed char InpCp = 2; //) const signed char InpPipe = 3; // | const signed char InpC = 4; // C const signed char InpE = 5; // E const signed char InpI = 6; // I const signed char InpM = 7; // M const signed char InpN = 8; // N const signed char InpO = 9; // O const signed char InpR = 10; // R const signed char InpS = 11; // S const signed char InpY = 12; // Y const signed char InpUnknown = 13; static const signed char table[19][14] = { /* InpWs InpOp InpCp InpPipe InpC InpE InpI InpM InpN InpO InpR InpS InpY InpUnknown */ { -1, EN, -1, -1, ST, TTE, TTI, -1, N, -1, -1, -1, -1, -1 }, // Init { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done }, // ST { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, TTI2, Done, Done, Done }, // TTI { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, TTI3, Done, Done }, // TTI2 { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done }, // TTI3 { -1, -1, -1, -1, -1, -1, TTEI, -1, -1, -1, -1, -1, TTEY, -1 }, // TTE { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done }, // TTEY { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done }, // TTEI { -1, -1, -1, -1, -1, -1, -1, TTNM, -1, NO, -1, -1, -1, -1 }, // N { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, TTNM2, Done, Done }, // TTNM { Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done, Done }, // TTNM2 { NO2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // NO { -1, NO3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // NO2 { NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName, NOName }, // NO3 { NO4, -1, ADone, NO3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // NOName { -1, -1, ADone, NO3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // NO4 { -1, -1, ENNmt, -1, ENNmt, ENNmt, ENNmt, ENNmt, ENNmt, ENNmt, ENNmt, ENNmt, ENNmt, ENNmt }, // EN { EN2, -1, ADone, EN, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // ENNmt { -1, -1, ADone, EN, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } // EN2 }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseAttType (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } } } for (;;) { switch (state) { case ADone: return true; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('(')) { input = InpOp; } else if (c == QLatin1Char(')')) { input = InpCp; } else if (c == QLatin1Char('|')) { input = InpPipe; } else if (c == QLatin1Char('C')) { input = InpC; } else if (c == QLatin1Char('E')) { input = InpE; } else if (c == QLatin1Char('I')) { input = InpI; } else if (c == QLatin1Char('M')) { input = InpM; } else if (c == QLatin1Char('N')) { input = InpN; } else if (c == QLatin1Char('O')) { input = InpO; } else if (c == QLatin1Char('R')) { input = InpR; } else if (c == QLatin1Char('S')) { input = InpS; } else if (c == QLatin1Char('Y')) { input = InpY; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case ST: parseString_s = QLatin1String("CDATA"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case TTI: parseString_s = QLatin1String("ID"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case TTI2: parseString_s = QLatin1String("REF"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case TTI3: next(); // S break; case TTE: parseString_s = QLatin1String("ENTIT"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case TTEY: next(); // Y break; case TTEI: parseString_s = QLatin1String("IES"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case N: next(); // N break; case TTNM: parseString_s = QLatin1String("MTOKEN"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case TTNM2: next(); // S break; case NO: parseString_s = QLatin1String("OTATION"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case NO2: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case NO3: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case NOName: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case NO4: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case EN: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case ENNmt: if (!parseNmtoken()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case EN2: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttType, state); return false; } break; case ADone: next(); break; } } return false; } /* Parse a AttValue [10] Precondition: the head stands on the beginning " or ' If this function was successful, the head stands on the first character after the closing " or ' and the value of the attribute is in string(). */ bool QXmlSimpleReaderPrivate::parseAttValue() { const signed char Init = 0; const signed char Dq = 1; // double quotes were read const signed char DqRef = 2; // read references in double quotes const signed char DqC = 3; // signed character read in double quotes const signed char Sq = 4; // single quotes were read const signed char SqRef = 5; // read references in single quotes const signed char SqC = 6; // signed character read in single quotes const signed char Done = 7; const signed char InpDq = 0; // " const signed char InpSq = 1; // ' const signed char InpAmp = 2; // & const signed char InpLt = 3; // < const signed char InpUnknown = 4; static const signed char table[7][5] = { /* InpDq InpSq InpAmp InpLt InpUnknown */ { Dq, Sq, -1, -1, -1 }, // Init { Done, DqC, DqRef, -1, DqC }, // Dq { Done, DqC, DqRef, -1, DqC }, // DqRef { Done, DqC, DqRef, -1, DqC }, // DqC { SqC, Done, SqRef, -1, SqC }, // Sq { SqC, Done, SqRef, -1, SqC }, // SqRef { SqC, Done, SqRef, -1, SqC } // SqRef }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseAttValue (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttValue, state); return false; } } } for (;;) { switch (state) { case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseAttValue, state); return false; } if (c == QLatin1Char('"')) { input = InpDq; } else if (c == QLatin1Char('\'')) { input = InpSq; } else if (c == QLatin1Char('&')) { input = InpAmp; } else if (c == QLatin1Char('<')) { input = InpLt; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Dq: case Sq: stringClear(); next(); break; case DqRef: case SqRef: parseReference_context = InAttributeValue; if (!parseReference()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttValue, state); return false; } break; case DqC: case SqC: stringAddC(); next(); break; case Done: next(); break; } } return false; } /* Parse a elementdecl [45]. Precondition: the beginning '<!E' is already read and the head stands on the 'L' of '<!ELEMENT' */ bool QXmlSimpleReaderPrivate::parseElementDecl() { const signed char Init = 0; const signed char Elem = 1; // parse the beginning string const signed char Ws1 = 2; // whitespace required const signed char Nam = 3; // parse Name const signed char Ws2 = 4; // whitespace required const signed char Empty = 5; // read EMPTY const signed char Any = 6; // read ANY const signed char Cont = 7; // read contentspec (except ANY or EMPTY) const signed char Mix = 8; // read Mixed const signed char Mix2 = 9; // const signed char Mix3 = 10; // const signed char MixN1 = 11; // const signed char MixN2 = 12; // const signed char MixN3 = 13; // const signed char MixN4 = 14; // const signed char Cp = 15; // parse cp const signed char Cp2 = 16; // const signed char WsD = 17; // eat whitespace before Done const signed char Done = 18; const signed char InpWs = 0; const signed char InpGt = 1; // > const signed char InpPipe = 2; // | const signed char InpOp = 3; // ( const signed char InpCp = 4; //) const signed char InpHash = 5; // # const signed char InpQm = 6; // ? const signed char InpAst = 7; // * const signed char InpPlus = 8; // + const signed char InpA = 9; // A const signed char InpE = 10; // E const signed char InpL = 11; // L const signed char InpUnknown = 12; static const signed char table[18][13] = { /* InpWs InpGt InpPipe InpOp InpCp InpHash InpQm InpAst InpPlus InpA InpE InpL InpUnknown */ { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, Elem, -1 }, // Init { Ws1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // Elem { -1, -1, -1, -1, -1, -1, -1, -1, -1, Nam, Nam, Nam, Nam }, // Ws1 { Ws2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // Nam { -1, -1, -1, Cont, -1, -1, -1, -1, -1, Any, Empty, -1, -1 }, // Ws2 { WsD, Done, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // Empty { WsD, Done, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // Any { -1, -1, -1, Cp, Cp, Mix, -1, -1, -1, Cp, Cp, Cp, Cp }, // Cont { Mix2, -1, MixN1, -1, Mix3, -1, -1, -1, -1, -1, -1, -1, -1 }, // Mix { -1, -1, MixN1, -1, Mix3, -1, -1, -1, -1, -1, -1, -1, -1 }, // Mix2 { WsD, Done, -1, -1, -1, -1, -1, WsD, -1, -1, -1, -1, -1 }, // Mix3 { -1, -1, -1, -1, -1, -1, -1, -1, -1, MixN2, MixN2, MixN2, MixN2 }, // MixN1 { MixN3, -1, MixN1, -1, MixN4, -1, -1, -1, -1, -1, -1, -1, -1 }, // MixN2 { -1, -1, MixN1, -1, MixN4, -1, -1, -1, -1, -1, -1, -1, -1 }, // MixN3 { -1, -1, -1, -1, -1, -1, -1, WsD, -1, -1, -1, -1, -1 }, // MixN4 { WsD, Done, -1, -1, -1, -1, Cp2, Cp2, Cp2, -1, -1, -1, -1 }, // Cp { WsD, Done, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, // Cp2 { -1, Done, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } // WsD }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseElementDecl (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } } } for (;;) { switch (state) { case Done: return true; case -1: reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('>')) { input = InpGt; } else if (c == QLatin1Char('|')) { input = InpPipe; } else if (c == QLatin1Char('(')) { input = InpOp; } else if (c == QLatin1Char(')')) { input = InpCp; } else if (c == QLatin1Char('#')) { input = InpHash; } else if (c == QLatin1Char('?')) { input = InpQm; } else if (c == QLatin1Char('*')) { input = InpAst; } else if (c == QLatin1Char('+')) { input = InpPlus; } else if (c == QLatin1Char('A')) { input = InpA; } else if (c == QLatin1Char('E')) { input = InpE; } else if (c == QLatin1Char('L')) { input = InpL; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Elem: parseString_s = QLatin1String("LEMENT"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Ws1: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Nam: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Ws2: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Empty: parseString_s = QLatin1String("EMPTY"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Any: parseString_s = QLatin1String("ANY"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Cont: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Mix: parseString_s = QLatin1String("#PCDATA"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Mix2: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Mix3: next(); break; case MixN1: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case MixN2: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case MixN3: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case MixN4: next(); break; case Cp: if (!parseChoiceSeq()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Cp2: next(); break; case WsD: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseElementDecl, state); return false; } break; case Done: next(); break; } } return false; } /* Parse a NotationDecl [82]. Precondition: the beginning '<!' is already read and the head stands on the 'N' of '<!NOTATION' */ bool QXmlSimpleReaderPrivate::parseNotationDecl() { const signed char Init = 0; const signed char Not = 1; // read NOTATION const signed char Ws1 = 2; // eat whitespaces const signed char Nam = 3; // read Name const signed char Ws2 = 4; // eat whitespaces const signed char ExtID = 5; // parse ExternalID const signed char ExtIDR = 6; // same as ExtID, but already reported const signed char Ws3 = 7; // eat whitespaces const signed char Done = 8; const signed char InpWs = 0; const signed char InpGt = 1; // > const signed char InpN = 2; // N const signed char InpUnknown = 3; static const signed char table[8][4] = { /* InpWs InpGt InpN InpUnknown */ { -1, -1, Not, -1 }, // Init { Ws1, -1, -1, -1 }, // Not { -1, -1, Nam, Nam }, // Ws1 { Ws2, Done, -1, -1 }, // Nam { -1, Done, ExtID, ExtID }, // Ws2 { Ws3, Done, -1, -1 }, // ExtID { Ws3, Done, -1, -1 }, // ExtIDR { -1, Done, -1, -1 } // Ws3 }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseNotationDecl (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } } } for (;;) { switch (state) { case ExtID: // call the handler if (dtdHnd) { if (!dtdHnd->notationDecl(name(), publicId, systemId)) { reportParseError(dtdHnd->errorString()); return false; } } state = ExtIDR; break; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('>')) { input = InpGt; } else if (c == QLatin1Char('N')) { input = InpN; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Not: parseString_s = QLatin1String("NOTATION"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } break; case Ws1: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } break; case Nam: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } break; case Ws2: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } break; case ExtID: case ExtIDR: parseExternalID_allowPublicID = true; if (!parseExternalID()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } break; case Ws3: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseNotationDecl, state); return false; } break; case Done: next(); break; } } return false; } /* Parse choice [49] or seq [50]. Precondition: the beginning '('S? is already read and the head stands on the first non-whitespace character after it. */ bool QXmlSimpleReaderPrivate::parseChoiceSeq() { const signed char Init = 0; const signed char Ws1 = 1; // eat whitespace const signed char CoS = 2; // choice or set const signed char Ws2 = 3; // eat whitespace const signed char More = 4; // more cp to read const signed char Name = 5; // read name const signed char Done = 6; // const signed char InpWs = 0; // S const signed char InpOp = 1; // ( const signed char InpCp = 2; //) const signed char InpQm = 3; // ? const signed char InpAst = 4; // * const signed char InpPlus = 5; // + const signed char InpPipe = 6; // | const signed char InpComm = 7; // , const signed char InpUnknown = 8; static const signed char table[6][9] = { /* InpWs InpOp InpCp InpQm InpAst InpPlus InpPipe InpComm InpUnknown */ { -1, Ws1, -1, -1, -1, -1, -1, -1, Name }, // Init { -1, CoS, -1, -1, -1, -1, -1, -1, CoS }, // Ws1 { Ws2, -1, Done, Ws2, Ws2, Ws2, More, More, -1 }, // CS { -1, -1, Done, -1, -1, -1, More, More, -1 }, // Ws2 { -1, Ws1, -1, -1, -1, -1, -1, -1, Name }, // More (same as Init) { Ws2, -1, Done, Ws2, Ws2, Ws2, More, More, -1 } // Name (same as CS) }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseChoiceSeq (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } } } for (;;) { switch (state) { case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('(')) { input = InpOp; } else if (c == QLatin1Char(')')) { input = InpCp; } else if (c == QLatin1Char('?')) { input = InpQm; } else if (c == QLatin1Char('*')) { input = InpAst; } else if (c == QLatin1Char('+')) { input = InpPlus; } else if (c == QLatin1Char('|')) { input = InpPipe; } else if (c == QLatin1Char(',')) { input = InpComm; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Ws1: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } break; case CoS: if (!parseChoiceSeq()) { parseFailed(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } break; case Ws2: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } break; case More: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } break; case Name: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseChoiceSeq, state); return false; } break; case Done: next(); break; } } return false; } bool QXmlSimpleReaderPrivate::isExpandedEntityValueTooLarge(QString *errorMessage) { QString entityNameBuffer; // For every entity, check how many times all entity names were referenced in its value. for (QMap<QString,QString>::const_iterator toSearchIt = entities.constBegin(); toSearchIt != entities.constEnd(); ++toSearchIt) { const QString &toSearch = toSearchIt.key(); // Don't check the same entities twice. if (!literalEntitySizes.contains(toSearch)) { // The amount of characters that weren't entity names, but literals, like 'X'. QString leftOvers = entities.value(toSearch); // How many times was entityName referenced by toSearch? for (QMap<QString,QString>::const_iterator referencedIt = entities.constBegin(); referencedIt != entities.constEnd(); ++referencedIt) { const QString &entityName = referencedIt.key(); for (int i = 0; i < leftOvers.size() && i != -1; ) { entityNameBuffer = QLatin1Char('&') + entityName + QLatin1Char(';'); i = leftOvers.indexOf(entityNameBuffer, i); if (i != -1) { leftOvers.remove(i, entityName.size() + 2); // The entityName we're currently trying to find was matched in this string; increase our count. ++referencesToOtherEntities[toSearch][entityName]; } } } literalEntitySizes[toSearch] = leftOvers.size(); } } for (QHash<QString, QHash<QString, int> >::const_iterator entityIt = referencesToOtherEntities.constBegin(); entityIt != referencesToOtherEntities.constEnd(); ++entityIt) { const QString &entity = entityIt.key(); QHash<QString, int>::iterator expandedIt = expandedSizes.find(entity); if (expandedIt == expandedSizes.end()) { expandedIt = expandedSizes.insert(entity, literalEntitySizes.value(entity)); for (QHash<QString, int>::const_iterator referenceIt = entityIt->constBegin(); referenceIt != entityIt->constEnd(); ++referenceIt) { const QString &referenceTo = referenceIt.key(); const int references = referencesToOtherEntities.value(entity).value(referenceTo); // The total size of an entity's value is the expanded size of all of its referenced entities, plus its literal size. *expandedIt += expandedSizes.value(referenceTo) * references + literalEntitySizes.value(referenceTo) * references; } if (*expandedIt > entityCharacterLimit) { if (errorMessage) { *errorMessage = QString::fromLatin1("The XML entity \"%1\" expands to a string that is too large to process (%2 characters > %3).") .arg(entity, *expandedIt, entityCharacterLimit); } return true; } } } return false; } /* Parse a EntityDecl [70]. Precondition: the beginning '<!E' is already read and the head stand on the 'N' of '<!ENTITY' */ bool QXmlSimpleReaderPrivate::parseEntityDecl() { const signed char Init = 0; const signed char Ent = 1; // parse "ENTITY" const signed char Ws1 = 2; // white space read const signed char Name = 3; // parse name const signed char Ws2 = 4; // white space read const signed char EValue = 5; // parse entity value const signed char EValueR = 6; // same as EValue, but already reported const signed char ExtID = 7; // parse ExternalID const signed char Ws3 = 8; // white space read const signed char Ndata = 9; // parse "NDATA" const signed char Ws4 = 10; // white space read const signed char NNam = 11; // parse name const signed char NNamR = 12; // same as NNam, but already reported const signed char PEDec = 13; // parse PEDecl const signed char Ws6 = 14; // white space read const signed char PENam = 15; // parse name const signed char Ws7 = 16; // white space read const signed char PEVal = 17; // parse entity value const signed char PEValR = 18; // same as PEVal, but already reported const signed char PEEID = 19; // parse ExternalID const signed char PEEIDR = 20; // same as PEEID, but already reported const signed char WsE = 21; // white space read const signed char Done = 22; const signed char EDDone = 23; // done, but also report an external, unparsed entity decl const signed char InpWs = 0; // white space const signed char InpPer = 1; // % const signed char InpQuot = 2; // " or ' const signed char InpGt = 3; // > const signed char InpN = 4; // N const signed char InpUnknown = 5; static const signed char table[22][6] = { /* InpWs InpPer InpQuot InpGt InpN InpUnknown */ { -1, -1, -1, -1, Ent, -1 }, // Init { Ws1, -1, -1, -1, -1, -1 }, // Ent { -1, PEDec, -1, -1, Name, Name }, // Ws1 { Ws2, -1, -1, -1, -1, -1 }, // Name { -1, -1, EValue, -1, -1, ExtID }, // Ws2 { WsE, -1, -1, Done, -1, -1 }, // EValue { WsE, -1, -1, Done, -1, -1 }, // EValueR { Ws3, -1, -1, EDDone,-1, -1 }, // ExtID { -1, -1, -1, EDDone,Ndata, -1 }, // Ws3 { Ws4, -1, -1, -1, -1, -1 }, // Ndata { -1, -1, -1, -1, NNam, NNam }, // Ws4 { WsE, -1, -1, Done, -1, -1 }, // NNam { WsE, -1, -1, Done, -1, -1 }, // NNamR { Ws6, -1, -1, -1, -1, -1 }, // PEDec { -1, -1, -1, -1, PENam, PENam }, // Ws6 { Ws7, -1, -1, -1, -1, -1 }, // PENam { -1, -1, PEVal, -1, -1, PEEID }, // Ws7 { WsE, -1, -1, Done, -1, -1 }, // PEVal { WsE, -1, -1, Done, -1, -1 }, // PEValR { WsE, -1, -1, Done, -1, -1 }, // PEEID { WsE, -1, -1, Done, -1, -1 }, // PEEIDR { -1, -1, -1, Done, -1, -1 } // WsE }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseEntityDecl (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } } } for (;;) { switch (state) { case EValue: if ( !entityExist(name())) { QString errorMessage; if (isExpandedEntityValueTooLarge(&errorMessage)) { reportParseError(errorMessage); return false; } entities.insert(name(), string()); if (declHnd) { if (!declHnd->internalEntityDecl(name(), string())) { reportParseError(declHnd->errorString()); return false; } } } state = EValueR; break; case NNam: if ( !entityExist(name())) { externEntities.insert(name(), QXmlSimpleReaderPrivate::ExternEntity(publicId, systemId, ref())); if (dtdHnd) { if (!dtdHnd->unparsedEntityDecl(name(), publicId, systemId, ref())) { reportParseError(declHnd->errorString()); return false; } } } state = NNamR; break; case PEVal: if ( !entityExist(name())) { parameterEntities.insert(name(), string()); if (declHnd) { if (!declHnd->internalEntityDecl(QLatin1Char('%') + name(), string())) { reportParseError(declHnd->errorString()); return false; } } } state = PEValR; break; case PEEID: if ( !entityExist(name())) { externParameterEntities.insert(name(), QXmlSimpleReaderPrivate::ExternParameterEntity(publicId, systemId)); if (declHnd) { if (!declHnd->externalEntityDecl(QLatin1Char('%') + name(), publicId, systemId)) { reportParseError(declHnd->errorString()); return false; } } } state = PEEIDR; break; case EDDone: if ( !entityExist(name())) { externEntities.insert(name(), QXmlSimpleReaderPrivate::ExternEntity(publicId, systemId, QString())); if (declHnd) { if (!declHnd->externalEntityDecl(name(), publicId, systemId)) { reportParseError(declHnd->errorString()); return false; } } } return true; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } if (is_S(c)) { input = InpWs; } else if (c == QLatin1Char('%')) { input = InpPer; } else if (c == QLatin1Char('"') || c == QLatin1Char('\'')) { input = InpQuot; } else if (c == QLatin1Char('>')) { input = InpGt; } else if (c == QLatin1Char('N')) { input = InpN; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Ent: parseString_s = QLatin1String("NTITY"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Ws1: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Name: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Ws2: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case EValue: case EValueR: if (!parseEntityValue()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case ExtID: parseExternalID_allowPublicID = false; if (!parseExternalID()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Ws3: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Ndata: parseString_s = QLatin1String("NDATA"); if (!parseString()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Ws4: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case NNam: case NNamR: parseName_useRef = true; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case PEDec: next(); break; case Ws6: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case PENam: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case Ws7: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case PEVal: case PEValR: if (!parseEntityValue()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case PEEID: case PEEIDR: parseExternalID_allowPublicID = false; if (!parseExternalID()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case WsE: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityDecl, state); return false; } break; case EDDone: next(); break; case Done: next(); break; } } return false; } /* Parse a EntityValue [9] */ bool QXmlSimpleReaderPrivate::parseEntityValue() { const signed char Init = 0; const signed char Dq = 1; // EntityValue is double quoted const signed char DqC = 2; // signed character const signed char DqPER = 3; // PERefence const signed char DqRef = 4; // Reference const signed char Sq = 5; // EntityValue is double quoted const signed char SqC = 6; // signed character const signed char SqPER = 7; // PERefence const signed char SqRef = 8; // Reference const signed char Done = 9; const signed char InpDq = 0; // " const signed char InpSq = 1; // ' const signed char InpAmp = 2; // & const signed char InpPer = 3; // % const signed char InpUnknown = 4; static const signed char table[9][5] = { /* InpDq InpSq InpAmp InpPer InpUnknown */ { Dq, Sq, -1, -1, -1 }, // Init { Done, DqC, DqRef, DqPER, DqC }, // Dq { Done, DqC, DqRef, DqPER, DqC }, // DqC { Done, DqC, DqRef, DqPER, DqC }, // DqPER { Done, DqC, DqRef, DqPER, DqC }, // DqRef { SqC, Done, SqRef, SqPER, SqC }, // Sq { SqC, Done, SqRef, SqPER, SqC }, // SqC { SqC, Done, SqRef, SqPER, SqC }, // SqPER { SqC, Done, SqRef, SqPER, SqC } // SqRef }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseEntityValue (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityValue, state); return false; } } } for (;;) { switch (state) { case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseEntityValue, state); return false; } if (c == QLatin1Char('"')) { input = InpDq; } else if (c == QLatin1Char('\'')) { input = InpSq; } else if (c == QLatin1Char('&')) { input = InpAmp; } else if (c == QLatin1Char('%')) { input = InpPer; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Dq: case Sq: stringClear(); next(); break; case DqC: case SqC: stringAddC(); next(); break; case DqPER: case SqPER: parsePEReference_context = InEntityValue; if (!parsePEReference()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityValue, state); return false; } break; case DqRef: case SqRef: parseReference_context = InEntityValue; if (!parseReference()) { parseFailed(&QXmlSimpleReaderPrivate::parseEntityValue, state); return false; } break; case Done: next(); break; } } return false; } /* Parse a comment [15]. Precondition: the beginning '<!' of the comment is already read and the head stands on the first '-' of '<!--'. If this funktion was successful, the head-position is on the first character after the comment. */ bool QXmlSimpleReaderPrivate::parseComment() { const signed char Init = 0; const signed char Dash1 = 1; // the first dash was read const signed char Dash2 = 2; // the second dash was read const signed char Com = 3; // read comment const signed char Com2 = 4; // read comment (help state) const signed char ComE = 5; // finished reading comment const signed char Done = 6; const signed char InpDash = 0; // - const signed char InpGt = 1; // > const signed char InpUnknown = 2; static const signed char table[6][3] = { /* InpDash InpGt InpUnknown */ { Dash1, -1, -1 }, // Init { Dash2, -1, -1 }, // Dash1 { Com2, Com, Com }, // Dash2 { Com2, Com, Com }, // Com { ComE, Com, Com }, // Com2 { -1, Done, -1 } // ComE }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseComment (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseComment, state); return false; } } } for (;;) { switch (state) { case Dash2: stringClear(); break; case Com2: // if next character is not a dash than don't skip it if (!atEnd() && c != QLatin1Char('-')) stringAddC(QLatin1Char('-')); break; case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_ERRORPARSINGCOMMENT)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseComment, state); return false; } if (c == QLatin1Char('-')) { input = InpDash; } else if (c == QLatin1Char('>')) { input = InpGt; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case Dash1: next(); break; case Dash2: next(); break; case Com: stringAddC(); next(); break; case Com2: next(); break; case ComE: next(); break; case Done: next(); break; } } return false; } /* Parse an Attribute [41]. Precondition: the head stands on the first character of the name of the attribute (i.e. all whitespaces are already parsed). The head stand on the next character after the end quotes. The variable name contains the name of the attribute and the variable string contains the value of the attribute. */ bool QXmlSimpleReaderPrivate::parseAttribute() { const int Init = 0; const int PName = 1; // parse name const int Ws = 2; // eat ws const int Eq = 3; // the '=' was read const int Quotes = 4; // " or ' were read const int InpNameBe = 0; const int InpEq = 1; // = const int InpDq = 2; // " const int InpSq = 3; // ' const int InpUnknown = 4; static const int table[4][5] = { /* InpNameBe InpEq InpDq InpSq InpUnknown */ { PName, -1, -1, -1, -1 }, // Init { -1, Eq, -1, -1, Ws }, // PName { -1, Eq, -1, -1, -1 }, // Ws { -1, -1, Quotes, Quotes, -1 } // Eq }; int state; int input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseAttribute (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttribute, state); return false; } } } for (;;) { switch (state) { case Quotes: // Done return true; case -1: // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseAttribute, state); return false; } if (determineNameChar(c) == NameBeginning) { input = InpNameBe; } else if (c == QLatin1Char('=')) { input = InpEq; } else if (c == QLatin1Char('"')) { input = InpDq; } else if (c == QLatin1Char('\'')) { input = InpSq; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case PName: parseName_useRef = false; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttribute, state); return false; } break; case Ws: if (!eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttribute, state); return false; } break; case Eq: if (!next_eat_ws()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttribute, state); return false; } break; case Quotes: if (!parseAttValue()) { parseFailed(&QXmlSimpleReaderPrivate::parseAttribute, state); return false; } break; } } return false; } /* Parse a Name [5] and store the name in name or ref (if useRef is true). */ bool QXmlSimpleReaderPrivate::parseName() { const int Init = 0; const int Name1 = 1; // parse first character of the name const int Name = 2; // parse name const int Done = 3; static const int table[3][3] = { /* InpNameBe InpNameCh InpUnknown */ { Name1, -1, -1 }, // Init { Name, Name, Done }, // Name1 { Name, Name, Done } // Name }; int state; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseName (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseName, state); return false; } } } for (;;) { switch (state) { case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseName, state); return false; } // we can safely do the (int) cast thanks to the Q_ASSERTs earlier in this function state = table[state][(int)fastDetermineNameChar(c)]; switch (state) { case Name1: if (parseName_useRef) { refClear(); refAddC(); } else { nameClear(); nameAddC(); } next(); break; case Name: if (parseName_useRef) { refAddC(); } else { nameAddC(); } next(); break; } } return false; } /* Parse a Nmtoken [7] and store the name in name. */ bool QXmlSimpleReaderPrivate::parseNmtoken() { const signed char Init = 0; const signed char NameF = 1; const signed char Name = 2; const signed char Done = 3; const signed char InpNameCh = 0; // NameChar without InpNameBe const signed char InpUnknown = 1; static const signed char table[3][2] = { /* InpNameCh InpUnknown */ { NameF, -1 }, // Init { Name, Done }, // NameF { Name, Done } // Name }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseNmtoken (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseNmtoken, state); return false; } } } for (;;) { switch (state) { case Done: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_LETTEREXPECTED)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseNmtoken, state); return false; } if (determineNameChar(c) == NotName) { input = InpUnknown; } else { input = InpNameCh; } state = table[state][input]; switch (state) { case NameF: nameClear(); nameAddC(); next(); break; case Name: nameAddC(); next(); break; } } return false; } /* Parse a Reference [67]. parseReference_charDataRead is set to true if the reference must not be parsed. The character(s) which the reference mapped to are appended to string. The head stands on the first character after the reference. parseReference_charDataRead is set to false if the reference must be parsed. The charachter(s) which the reference mapped to are inserted at the reference position. The head stands on the first character of the replacement). */ bool QXmlSimpleReaderPrivate::parseReference() { // temporary variables (only used in very local context, so they don't // interfere with incremental parsing) uint tmp; bool ok; const signed char Init = 0; const signed char SRef = 1; // start of a reference const signed char ChRef = 2; // parse CharRef const signed char ChDec = 3; // parse CharRef decimal const signed char ChHexS = 4; // start CharRef hexadecimal const signed char ChHex = 5; // parse CharRef hexadecimal const signed char Name = 6; // parse name const signed char DoneD = 7; // done CharRef decimal const signed char DoneH = 8; // done CharRef hexadecimal const signed char DoneN = 9; // done EntityRef const signed char InpAmp = 0; // & const signed char InpSemi = 1; // ; const signed char InpHash = 2; // # const signed char InpX = 3; // x const signed char InpNum = 4; // 0-9 const signed char InpHex = 5; // a-f A-F const signed char InpUnknown = 6; static const signed char table[8][7] = { /* InpAmp InpSemi InpHash InpX InpNum InpHex InpUnknown */ { SRef, -1, -1, -1, -1, -1, -1 }, // Init { -1, -1, ChRef, Name, Name, Name, Name }, // SRef { -1, -1, -1, ChHexS, ChDec, -1, -1 }, // ChRef { -1, DoneD, -1, -1, ChDec, -1, -1 }, // ChDec { -1, -1, -1, -1, ChHex, ChHex, -1 }, // ChHexS { -1, DoneH, -1, -1, ChHex, ChHex, -1 }, // ChHex { -1, DoneN, -1, -1, -1, -1, -1 } // Name }; signed char state; signed char input; if (parseStack==0 || parseStack->isEmpty()) { parseReference_charDataRead = false; state = Init; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseReference (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseReference, state); return false; } } } for (;;) { switch (state) { case DoneD: return true; case DoneH: return true; case DoneN: return true; case -1: // Error reportParseError(QLatin1String(XMLERR_ERRORPARSINGREFERENCE)); return false; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseReference, state); return false; } if (c.row()) { input = InpUnknown; } else if (c.cell() == '&') { input = InpAmp; } else if (c.cell() == ';') { input = InpSemi; } else if (c.cell() == '#') { input = InpHash; } else if (c.cell() == 'x') { input = InpX; } else if ('0' <= c.cell() && c.cell() <= '9') { input = InpNum; } else if ('a' <= c.cell() && c.cell() <= 'f') { input = InpHex; } else if ('A' <= c.cell() && c.cell() <= 'F') { input = InpHex; } else { input = InpUnknown; } state = table[state][input]; switch (state) { case SRef: refClear(); next(); break; case ChRef: next(); break; case ChDec: refAddC(); next(); break; case ChHexS: next(); break; case ChHex: refAddC(); next(); break; case Name: // read the name into the ref parseName_useRef = true; if (!parseName()) { parseFailed(&QXmlSimpleReaderPrivate::parseReference, state); return false; } break; case DoneD: tmp = ref().toUInt(&ok, 10); if (ok) { stringAddC(QChar(tmp)); } else { reportParseError(QLatin1String(XMLERR_ERRORPARSINGREFERENCE)); return false; } parseReference_charDataRead = true; next(); break; case DoneH: tmp = ref().toUInt(&ok, 16); if (ok) { stringAddC(QChar(tmp)); } else { reportParseError(QLatin1String(XMLERR_ERRORPARSINGREFERENCE)); return false; } parseReference_charDataRead = true; next(); break; case DoneN: if (!processReference()) return false; next(); break; } } return false; } /* Helper function for parseReference() */ bool QXmlSimpleReaderPrivate::processReference() { QString reference = ref(); if (reference == QLatin1String("amp")) { if (parseReference_context == InEntityValue) { // Bypassed stringAddC(QLatin1Char('&')); stringAddC(QLatin1Char('a')); stringAddC(QLatin1Char('m')); stringAddC(QLatin1Char('p')); stringAddC(QLatin1Char(';')); } else { // Included or Included in literal stringAddC(QLatin1Char('&')); } parseReference_charDataRead = true; } else if (reference == QLatin1String("lt")) { if (parseReference_context == InEntityValue) { // Bypassed stringAddC(QLatin1Char('&')); stringAddC(QLatin1Char('l')); stringAddC(QLatin1Char('t')); stringAddC(QLatin1Char(';')); } else { // Included or Included in literal stringAddC(QLatin1Char('<')); } parseReference_charDataRead = true; } else if (reference == QLatin1String("gt")) { if (parseReference_context == InEntityValue) { // Bypassed stringAddC(QLatin1Char('&')); stringAddC(QLatin1Char('g')); stringAddC(QLatin1Char('t')); stringAddC(QLatin1Char(';')); } else { // Included or Included in literal stringAddC(QLatin1Char('>')); } parseReference_charDataRead = true; } else if (reference == QLatin1String("apos")) { if (parseReference_context == InEntityValue) { // Bypassed stringAddC(QLatin1Char('&')); stringAddC(QLatin1Char('a')); stringAddC(QLatin1Char('p')); stringAddC(QLatin1Char('o')); stringAddC(QLatin1Char('s')); stringAddC(QLatin1Char(';')); } else { // Included or Included in literal stringAddC(QLatin1Char('\'')); } parseReference_charDataRead = true; } else if (reference == QLatin1String("quot")) { if (parseReference_context == InEntityValue) { // Bypassed stringAddC(QLatin1Char('&')); stringAddC(QLatin1Char('q')); stringAddC(QLatin1Char('u')); stringAddC(QLatin1Char('o')); stringAddC(QLatin1Char('t')); stringAddC(QLatin1Char(';')); } else { // Included or Included in literal stringAddC(QLatin1Char('"')); } parseReference_charDataRead = true; } else { QMap<QString,QString>::Iterator it; it = entities.find(reference); if (it != entities.end()) { // "Internal General" switch (parseReference_context) { case InContent: // Included if (!insertXmlRef(*it, reference, false)) return false; parseReference_charDataRead = false; break; case InAttributeValue: // Included in literal if (!insertXmlRef(*it, reference, true)) return false; parseReference_charDataRead = false; break; case InEntityValue: { // Bypassed stringAddC(QLatin1Char('&')); for (int i=0; i<(int)reference.length(); i++) { stringAddC(reference[i]); } stringAddC(QLatin1Char(';')); parseReference_charDataRead = true; } break; case InDTD: // Forbidden parseReference_charDataRead = false; reportParseError(QLatin1String(XMLERR_INTERNALGENERALENTITYINDTD)); return false; } } else { QMap<QString,QXmlSimpleReaderPrivate::ExternEntity>::Iterator itExtern; itExtern = externEntities.find(reference); if (itExtern == externEntities.end()) { // entity not declared // ### check this case for conformance if (parseReference_context == InEntityValue) { // Bypassed stringAddC(QLatin1Char('&')); for (int i=0; i<(int)reference.length(); i++) { stringAddC(reference[i]); } stringAddC(QLatin1Char(';')); parseReference_charDataRead = true; } else { // if we have some char data read, report it now if (parseReference_context == InContent) { if (contentCharDataRead) { if (reportWhitespaceCharData || !string().simplified().isEmpty()) { if (contentHnd != 0 && !contentHnd->characters(string())) { reportParseError(contentHnd->errorString()); return false; } } stringClear(); contentCharDataRead = false; } } if (contentHnd) { qt_xml_skipped_entity_in_content = parseReference_context == InContent; if (!contentHnd->skippedEntity(reference)) { qt_xml_skipped_entity_in_content = false; reportParseError(contentHnd->errorString()); return false; // error } qt_xml_skipped_entity_in_content = false; } } } else if ((*itExtern).notation.isNull()) { // "External Parsed General" switch (parseReference_context) { case InContent: { // Included if validating bool skipIt = true; if (entityRes) { QXmlInputSource *ret = 0; if (!entityRes->resolveEntity((*itExtern).publicId, (*itExtern).systemId, ret)) { delete ret; reportParseError(entityRes->errorString()); return false; } if (ret) { QString xmlRefString = ret->data(); delete ret; if (!stripTextDecl(xmlRefString)) { reportParseError(QLatin1String(XMLERR_ERRORINTEXTDECL)); return false; } if (!insertXmlRef(xmlRefString, reference, false)) return false; skipIt = false; } } if (skipIt && contentHnd) { qt_xml_skipped_entity_in_content = true; if (!contentHnd->skippedEntity(reference)) { qt_xml_skipped_entity_in_content = false; reportParseError(contentHnd->errorString()); return false; // error } qt_xml_skipped_entity_in_content = false; } parseReference_charDataRead = false; } break; case InAttributeValue: // Forbidden parseReference_charDataRead = false; reportParseError(QLatin1String(XMLERR_EXTERNALGENERALENTITYINAV)); return false; case InEntityValue: { // Bypassed stringAddC(QLatin1Char('&')); for (int i=0; i<(int)reference.length(); i++) { stringAddC(reference[i]); } stringAddC(QLatin1Char(';')); parseReference_charDataRead = true; } break; case InDTD: // Forbidden parseReference_charDataRead = false; reportParseError(QLatin1String(XMLERR_EXTERNALGENERALENTITYINDTD)); return false; } } else { // "Unparsed" // ### notify for "Occurs as Attribute Value" missing (but this is no refence, anyway) // Forbidden parseReference_charDataRead = false; reportParseError(QLatin1String(XMLERR_UNPARSEDENTITYREFERENCE)); return false; // error } } } return true; // no error } /* Parses over a simple string. After the string was successfully parsed, the head is on the first character after the string. */ bool QXmlSimpleReaderPrivate::parseString() { const signed char InpCharExpected = 0; // the character that was expected const signed char InpUnknown = 1; signed char state; // state in this function is the position in the string s signed char input; if (parseStack==0 || parseStack->isEmpty()) { Done = parseString_s.length(); state = 0; } else { state = parseStack->pop().state; #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: parseString (cont) in state %d", state); #endif if (!parseStack->isEmpty()) { ParseFunction function = parseStack->top().function; if (function == &QXmlSimpleReaderPrivate::eat_ws) { parseStack->pop(); #if defined(QT_QXML_DEBUG) qDebug("QXmlSimpleReader: eat_ws (cont)"); #endif } if (!(this->*function)()) { parseFailed(&QXmlSimpleReaderPrivate::parseString, state); return false; } } } for (;;) { if (state == Done) { return true; } if (atEnd()) { unexpectedEof(&QXmlSimpleReaderPrivate::parseString, state); return false; } if (c == parseString_s[(int)state]) { input = InpCharExpected; } else { input = InpUnknown; } if (input == InpCharExpected) { state++; } else { // Error reportParseError(QLatin1String(XMLERR_UNEXPECTEDCHARACTER)); return false; } next(); } return false; } /* This private function inserts and reports an entity substitution. The substituted string is \a data and the name of the entity reference is \a name. If \a inLiteral is true, the entity is IncludedInLiteral (i.e., " and ' must be quoted. Otherwise they are not quoted. This function returns \c false on error. */ bool QXmlSimpleReaderPrivate::insertXmlRef(const QString &data, const QString &name, bool inLiteral) { if (inLiteral) { QString tmp = data; xmlRefStack.push(XmlRef(name, tmp.replace(QLatin1Char('\"'), QLatin1String("&quot;")).replace(QLatin1Char('\''), QLatin1String("&apos;")))); } else { xmlRefStack.push(XmlRef(name, data)); } int n = qMax(parameterEntities.count(), entities.count()); if (xmlRefStack.count() > n+1) { // recursive entities reportParseError(QLatin1String(XMLERR_RECURSIVEENTITIES)); return false; } if (reportEntities && lexicalHnd) { if (!lexicalHnd->startEntity(name)) { reportParseError(lexicalHnd->errorString()); return false; } } return true; } /* This private function moves the cursor to the next character. */ void QXmlSimpleReaderPrivate::next() { int count = xmlRefStack.size(); while (count != 0) { if (xmlRefStack.top().isEmpty()) { xmlRefStack.pop_back(); count--; } else { c = xmlRefStack.top().next(); return; } } // the following could be written nicer, but since it is a time-critical // function, rather optimize for speed ushort uc = c.unicode(); c = inputSource->next(); // If we are not incremental parsing, we just skip over EndOfData chars to give the // parser an uninterrupted stream of document chars. if (c == QXmlInputSource::EndOfData && parseStack == 0) c = inputSource->next(); if (uc == '\n') { lineNr++; columnNr = -1; } else if (uc == '\r') { if (c != QLatin1Char('\n')) { lineNr++; columnNr = -1; } } ++columnNr; } /* This private function moves the cursor to the next non-whitespace character. This function does not move the cursor if the actual cursor position is a non-whitespace charcter. Returns \c false when you use incremental parsing and this function reaches EOF with reading only whitespace characters. In this case it also poplulates the parseStack with useful information. In all other cases, this function returns true. */ bool QXmlSimpleReaderPrivate::eat_ws() { while (!atEnd()) { if (!is_S(c)) { return true; } next(); } if (parseStack != 0) { unexpectedEof(&QXmlSimpleReaderPrivate::eat_ws, 0); return false; } return true; } bool QXmlSimpleReaderPrivate::next_eat_ws() { next(); return eat_ws(); } /* This private function initializes the reader. \a i is the input source to read the data from. */ void QXmlSimpleReaderPrivate::init(const QXmlInputSource *i) { lineNr = 0; columnNr = -1; inputSource = const_cast<QXmlInputSource *>(i); initData(); externParameterEntities.clear(); parameterEntities.clear(); externEntities.clear(); entities.clear(); tags.clear(); doctype.clear(); xmlVersion.clear(); encoding.clear(); standalone = QXmlSimpleReaderPrivate::Unknown; error.clear(); } /* This private function initializes the XML data related variables. Especially, it reads the data from the input source. */ void QXmlSimpleReaderPrivate::initData() { c = QXmlInputSource::EndOfData; xmlRefStack.clear(); next(); } /* Returns \c true if a entity with the name \a e exists, otherwise returns \c false. */ bool QXmlSimpleReaderPrivate::entityExist(const QString& e) const { if ( parameterEntities.find(e) == parameterEntities.end() && externParameterEntities.find(e) == externParameterEntities.end() && externEntities.find(e) == externEntities.end() && entities.find(e) == entities.end()) { return false; } else { return true; } } void QXmlSimpleReaderPrivate::reportParseError(const QString& error) { this->error = error; if (errorHnd) { if (this->error.isNull()) { const QXmlParseException ex(QLatin1String(XMLERR_OK), columnNr+1, lineNr+1, thisPublicId, thisSystemId); errorHnd->fatalError(ex); } else { const QXmlParseException ex(this->error, columnNr+1, lineNr+1, thisPublicId, thisSystemId); errorHnd->fatalError(ex); } } } /* This private function is called when a parsing function encounters an unexpected EOF. It decides what to do (depending on incremental parsing or not). \a where is a pointer to the function where the error occurred and \a state is the parsing state in this function. */ void QXmlSimpleReaderPrivate::unexpectedEof(ParseFunction where, int state) { if (parseStack == 0) { reportParseError(QLatin1String(XMLERR_UNEXPECTEDEOF)); } else { if (c == QXmlInputSource::EndOfDocument) { reportParseError(QLatin1String(XMLERR_UNEXPECTEDEOF)); } else { pushParseState(where, state); } } } /* This private function is called when a parse...() function returned false. It determines if there was an error or if incremental parsing simply went out of data and does the right thing for the case. \a where is a pointer to the function where the error occurred and \a state is the parsing state in this function. */ void QXmlSimpleReaderPrivate::parseFailed(ParseFunction where, int state) { if (parseStack!=0 && error.isNull()) { pushParseState(where, state); } } /* This private function pushes the function pointer \a function and state \a state to the parse stack. This is used when you are doing an incremental parsing and reach the end of file too early. Only call this function when d->parseStack!=0. */ void QXmlSimpleReaderPrivate::pushParseState(ParseFunction function, int state) { QXmlSimpleReaderPrivate::ParseState ps; ps.function = function; ps.state = state; parseStack->push(ps); } inline static void updateValue(QString &value, const QChar *array, int &arrayPos, int &valueLen) { value.resize(valueLen + arrayPos); memcpy(value.data() + valueLen, array, arrayPos * sizeof(QChar)); valueLen += arrayPos; arrayPos = 0; } // use buffers instead of QString::operator+= when single characters are read const QString& QXmlSimpleReaderPrivate::string() { updateValue(stringValue, stringArray, stringArrayPos, stringValueLen); return stringValue; } const QString& QXmlSimpleReaderPrivate::name() { updateValue(nameValue, nameArray, nameArrayPos, nameValueLen); return nameValue; } const QString& QXmlSimpleReaderPrivate::ref() { updateValue(refValue, refArray, refArrayPos, refValueLen); return refValue; } void QXmlSimpleReaderPrivate::stringAddC(QChar ch) { if (stringArrayPos == 256) updateValue(stringValue, stringArray, stringArrayPos, stringValueLen); stringArray[stringArrayPos++] = ch; } void QXmlSimpleReaderPrivate::nameAddC(QChar ch) { if (nameArrayPos == 256) updateValue(nameValue, nameArray, nameArrayPos, nameValueLen); nameArray[nameArrayPos++] = ch; } void QXmlSimpleReaderPrivate::refAddC(QChar ch) { if (refArrayPos == 256) updateValue(refValue, refArray, refArrayPos, refValueLen); refArray[refArrayPos++] = ch; } QT_END_NAMESPACE
CodeDJ/qt5-hidpi
qt/qtbase/src/xml/sax/qxml.cpp
C++
lgpl-2.1
281,806
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "H5LT.h" #define RANK 2 int main( void ) { hid_t file_id; hsize_t dims[RANK]={2,3}; int data[6]={1,2,3,4,5,6}; herr_t status; /* create a HDF5 file */ file_id = H5Fcreate ("ex_lite1.h5", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); /* create and write an integer type dataset named "dset" */ status = H5LTmake_dataset(file_id,"/dset",RANK,dims,H5T_NATIVE_INT,data); /* close file */ status = H5Fclose (file_id); return 0; }
einon/affymetrix-power-tools
external/hdf5/hl/examples/ex_lite1.c
C
lgpl-2.1
1,588
/* Copyright (C) 2014-2015 Alexandr Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. 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. */ #include "TLTypesDebug.hpp" // Generated TLTypes debug operators QDebug operator<<(QDebug d, const TLAccountDaysTTL &type) { d << "TLAccountDaysTTL(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AccountDaysTTL: d << "days:" << type.days; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAccountSentChangePhoneCode &type) { d << "TLAccountSentChangePhoneCode(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AccountSentChangePhoneCode: d << "phoneCodeHash:" << type.phoneCodeHash; d << "sendCallTimeout:" << type.sendCallTimeout; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAudio &type) { d << "TLAudio(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AudioEmpty: d << "id:" << type.id; break; case TLValue::Audio: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "userId:" << type.userId; d << "date:" << type.date; d << "duration:" << type.duration; d << "mimeType:" << type.mimeType; d << "size:" << type.size; d << "dcId:" << type.dcId; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAuthCheckedPhone &type) { d << "TLAuthCheckedPhone(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AuthCheckedPhone: d << "phoneRegistered:" << type.phoneRegistered; d << "phoneInvited:" << type.phoneInvited; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAuthExportedAuthorization &type) { d << "TLAuthExportedAuthorization(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AuthExportedAuthorization: d << "id:" << type.id; d << "bytes:" << type.bytes; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAuthSentCode &type) { d << "TLAuthSentCode(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AuthSentCode: d << "phoneRegistered:" << type.phoneRegistered; d << "phoneCodeHash:" << type.phoneCodeHash; d << "sendCallTimeout:" << type.sendCallTimeout; d << "isPassword:" << type.isPassword; break; case TLValue::AuthSentAppCode: d << "phoneRegistered:" << type.phoneRegistered; d << "phoneCodeHash:" << type.phoneCodeHash; d << "sendCallTimeout:" << type.sendCallTimeout; d << "isPassword:" << type.isPassword; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLChatLocated &type) { d << "TLChatLocated(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ChatLocated: d << "chatId:" << type.chatId; d << "distance:" << type.distance; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLChatParticipant &type) { d << "TLChatParticipant(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ChatParticipant: d << "userId:" << type.userId; d << "inviterId:" << type.inviterId; d << "date:" << type.date; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLChatParticipants &type) { d << "TLChatParticipants(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ChatParticipantsForbidden: d << "chatId:" << type.chatId; break; case TLValue::ChatParticipants: d << "chatId:" << type.chatId; d << "adminId:" << type.adminId; d << "participants:" << type.participants; d << "version:" << type.version; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContact &type) { d << "TLContact(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::Contact: d << "userId:" << type.userId; d << "mutual:" << type.mutual; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactBlocked &type) { d << "TLContactBlocked(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactBlocked: d << "userId:" << type.userId; d << "date:" << type.date; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactFound &type) { d << "TLContactFound(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactFound: d << "userId:" << type.userId; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactSuggested &type) { d << "TLContactSuggested(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactSuggested: d << "userId:" << type.userId; d << "mutualContacts:" << type.mutualContacts; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsForeignLink &type) { d << "TLContactsForeignLink(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsForeignLinkUnknown: break; case TLValue::ContactsForeignLinkRequested: d << "hasPhone:" << type.hasPhone; break; case TLValue::ContactsForeignLinkMutual: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsMyLink &type) { d << "TLContactsMyLink(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsMyLinkEmpty: break; case TLValue::ContactsMyLinkRequested: d << "contact:" << type.contact; break; case TLValue::ContactsMyLinkContact: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLDcOption &type) { d << "TLDcOption(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::DcOption: d << "id:" << type.id; d << "hostname:" << type.hostname; d << "ipAddress:" << type.ipAddress; d << "port:" << type.port; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLDisabledFeature &type) { d << "TLDisabledFeature(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::DisabledFeature: d << "feature:" << type.feature; d << "description:" << type.description; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLDocumentAttribute &type) { d << "TLDocumentAttribute(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::DocumentAttributeImageSize: d << "w:" << type.w; d << "h:" << type.h; break; case TLValue::DocumentAttributeAnimated: break; case TLValue::DocumentAttributeSticker: break; case TLValue::DocumentAttributeVideo: d << "duration:" << type.duration; d << "w:" << type.w; d << "h:" << type.h; break; case TLValue::DocumentAttributeAudio: d << "duration:" << type.duration; break; case TLValue::DocumentAttributeFilename: d << "fileName:" << type.fileName; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLEncryptedChat &type) { d << "TLEncryptedChat(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::EncryptedChatEmpty: d << "id:" << type.id; break; case TLValue::EncryptedChatWaiting: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "date:" << type.date; d << "adminId:" << type.adminId; d << "participantId:" << type.participantId; break; case TLValue::EncryptedChatRequested: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "date:" << type.date; d << "adminId:" << type.adminId; d << "participantId:" << type.participantId; d << "gA:" << type.gA; break; case TLValue::EncryptedChat: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "date:" << type.date; d << "adminId:" << type.adminId; d << "participantId:" << type.participantId; d << "gAOrB:" << type.gAOrB; d << "keyFingerprint:" << type.keyFingerprint; break; case TLValue::EncryptedChatDiscarded: d << "id:" << type.id; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLEncryptedFile &type) { d << "TLEncryptedFile(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::EncryptedFileEmpty: break; case TLValue::EncryptedFile: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "size:" << type.size; d << "dcId:" << type.dcId; d << "keyFingerprint:" << type.keyFingerprint; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLEncryptedMessage &type) { d << "TLEncryptedMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::EncryptedMessage: d << "randomId:" << type.randomId; d << "chatId:" << type.chatId; d << "date:" << type.date; d << "bytes:" << type.bytes; d << "file:" << type.file; break; case TLValue::EncryptedMessageService: d << "randomId:" << type.randomId; d << "chatId:" << type.chatId; d << "date:" << type.date; d << "bytes:" << type.bytes; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLError &type) { d << "TLError(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::Error: d << "code:" << type.code; d << "text:" << type.text; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLFileLocation &type) { d << "TLFileLocation(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::FileLocationUnavailable: d << "volumeId:" << type.volumeId; d << "localId:" << type.localId; d << "secret:" << type.secret; break; case TLValue::FileLocation: d << "dcId:" << type.dcId; d << "volumeId:" << type.volumeId; d << "localId:" << type.localId; d << "secret:" << type.secret; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLGeoPoint &type) { d << "TLGeoPoint(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::GeoPointEmpty: break; case TLValue::GeoPoint: d << "longitude:" << type.longitude; d << "latitude:" << type.latitude; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLHelpAppUpdate &type) { d << "TLHelpAppUpdate(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::HelpAppUpdate: d << "id:" << type.id; d << "critical:" << type.critical; d << "url:" << type.url; d << "text:" << type.text; break; case TLValue::HelpNoAppUpdate: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLHelpInviteText &type) { d << "TLHelpInviteText(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::HelpInviteText: d << "message:" << type.message; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLImportedContact &type) { d << "TLImportedContact(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ImportedContact: d << "userId:" << type.userId; d << "clientId:" << type.clientId; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputAppEvent &type) { d << "TLInputAppEvent(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputAppEvent: d << "time:" << type.time; d << "type:" << type.type; d << "peer:" << type.peer; d << "data:" << type.data; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputAudio &type) { d << "TLInputAudio(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputAudioEmpty: break; case TLValue::InputAudio: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputContact &type) { d << "TLInputContact(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPhoneContact: d << "clientId:" << type.clientId; d << "phone:" << type.phone; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputDocument &type) { d << "TLInputDocument(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputDocumentEmpty: break; case TLValue::InputDocument: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputEncryptedChat &type) { d << "TLInputEncryptedChat(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputEncryptedChat: d << "chatId:" << type.chatId; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputEncryptedFile &type) { d << "TLInputEncryptedFile(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputEncryptedFileEmpty: break; case TLValue::InputEncryptedFileUploaded: d << "id:" << type.id; d << "parts:" << type.parts; d << "md5Checksum:" << type.md5Checksum; d << "keyFingerprint:" << type.keyFingerprint; break; case TLValue::InputEncryptedFile: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; case TLValue::InputEncryptedFileBigUploaded: d << "id:" << type.id; d << "parts:" << type.parts; d << "keyFingerprint:" << type.keyFingerprint; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputFile &type) { d << "TLInputFile(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputFile: d << "id:" << type.id; d << "parts:" << type.parts; d << "name:" << type.name; d << "md5Checksum:" << type.md5Checksum; break; case TLValue::InputFileBig: d << "id:" << type.id; d << "parts:" << type.parts; d << "name:" << type.name; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputFileLocation &type) { d << "TLInputFileLocation(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputFileLocation: d << "volumeId:" << type.volumeId; d << "localId:" << type.localId; d << "secret:" << type.secret; break; case TLValue::InputVideoFileLocation: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; case TLValue::InputEncryptedFileLocation: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; case TLValue::InputAudioFileLocation: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; case TLValue::InputDocumentFileLocation: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputGeoChat &type) { d << "TLInputGeoChat(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputGeoChat: d << "chatId:" << type.chatId; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputGeoPoint &type) { d << "TLInputGeoPoint(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputGeoPointEmpty: break; case TLValue::InputGeoPoint: d << "latitude:" << type.latitude; d << "longitude:" << type.longitude; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPeer &type) { d << "TLInputPeer(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPeerEmpty: break; case TLValue::InputPeerSelf: break; case TLValue::InputPeerContact: d << "userId:" << type.userId; break; case TLValue::InputPeerForeign: d << "userId:" << type.userId; d << "accessHash:" << type.accessHash; break; case TLValue::InputPeerChat: d << "chatId:" << type.chatId; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPeerNotifyEvents &type) { d << "TLInputPeerNotifyEvents(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPeerNotifyEventsEmpty: break; case TLValue::InputPeerNotifyEventsAll: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPeerNotifySettings &type) { d << "TLInputPeerNotifySettings(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPeerNotifySettings: d << "muteUntil:" << type.muteUntil; d << "sound:" << type.sound; d << "showPreviews:" << type.showPreviews; d << "eventsMask:" << type.eventsMask; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPhoto &type) { d << "TLInputPhoto(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPhotoEmpty: break; case TLValue::InputPhoto: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPhotoCrop &type) { d << "TLInputPhotoCrop(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPhotoCropAuto: break; case TLValue::InputPhotoCrop: d << "cropLeft:" << type.cropLeft; d << "cropTop:" << type.cropTop; d << "cropWidth:" << type.cropWidth; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPrivacyKey &type) { d << "TLInputPrivacyKey(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPrivacyKeyStatusTimestamp: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputUser &type) { d << "TLInputUser(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputUserEmpty: break; case TLValue::InputUserSelf: break; case TLValue::InputUserContact: d << "userId:" << type.userId; break; case TLValue::InputUserForeign: d << "userId:" << type.userId; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputVideo &type) { d << "TLInputVideo(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputVideoEmpty: break; case TLValue::InputVideo: d << "id:" << type.id; d << "accessHash:" << type.accessHash; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesAffectedHistory &type) { d << "TLMessagesAffectedHistory(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesAffectedHistory: d << "pts:" << type.pts; d << "seq:" << type.seq; d << "offset:" << type.offset; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesDhConfig &type) { d << "TLMessagesDhConfig(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesDhConfigNotModified: d << "random:" << type.random; break; case TLValue::MessagesDhConfig: d << "g:" << type.g; d << "p:" << type.p; d << "version:" << type.version; d << "random:" << type.random; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesFilter &type) { d << "TLMessagesFilter(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputMessagesFilterEmpty: break; case TLValue::InputMessagesFilterPhotos: break; case TLValue::InputMessagesFilterVideo: break; case TLValue::InputMessagesFilterPhotoVideo: break; case TLValue::InputMessagesFilterPhotoVideoDocuments: break; case TLValue::InputMessagesFilterDocument: break; case TLValue::InputMessagesFilterAudio: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesSentEncryptedMessage &type) { d << "TLMessagesSentEncryptedMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesSentEncryptedMessage: d << "date:" << type.date; break; case TLValue::MessagesSentEncryptedFile: d << "date:" << type.date; d << "file:" << type.file; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLNearestDc &type) { d << "TLNearestDc(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::NearestDc: d << "country:" << type.country; d << "thisDc:" << type.thisDc; d << "nearestDc:" << type.nearestDc; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPeer &type) { d << "TLPeer(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PeerUser: d << "userId:" << type.userId; break; case TLValue::PeerChat: d << "chatId:" << type.chatId; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPeerNotifyEvents &type) { d << "TLPeerNotifyEvents(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PeerNotifyEventsEmpty: break; case TLValue::PeerNotifyEventsAll: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPeerNotifySettings &type) { d << "TLPeerNotifySettings(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PeerNotifySettingsEmpty: break; case TLValue::PeerNotifySettings: d << "muteUntil:" << type.muteUntil; d << "sound:" << type.sound; d << "showPreviews:" << type.showPreviews; d << "eventsMask:" << type.eventsMask; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPhotoSize &type) { d << "TLPhotoSize(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PhotoSizeEmpty: d << "type:" << type.type; break; case TLValue::PhotoSize: d << "type:" << type.type; d << "location:" << type.location; d << "w:" << type.w; d << "h:" << type.h; d << "size:" << type.size; break; case TLValue::PhotoCachedSize: d << "type:" << type.type; d << "location:" << type.location; d << "w:" << type.w; d << "h:" << type.h; d << "bytes:" << type.bytes; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPrivacyKey &type) { d << "TLPrivacyKey(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PrivacyKeyStatusTimestamp: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPrivacyRule &type) { d << "TLPrivacyRule(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PrivacyValueAllowContacts: break; case TLValue::PrivacyValueAllowAll: break; case TLValue::PrivacyValueAllowUsers: d << "users:" << type.users; break; case TLValue::PrivacyValueDisallowContacts: break; case TLValue::PrivacyValueDisallowAll: break; case TLValue::PrivacyValueDisallowUsers: d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLSendMessageAction &type) { d << "TLSendMessageAction(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::SendMessageTypingAction: break; case TLValue::SendMessageCancelAction: break; case TLValue::SendMessageRecordVideoAction: break; case TLValue::SendMessageUploadVideoAction: break; case TLValue::SendMessageRecordAudioAction: break; case TLValue::SendMessageUploadAudioAction: break; case TLValue::SendMessageUploadPhotoAction: break; case TLValue::SendMessageUploadDocumentAction: break; case TLValue::SendMessageGeoLocationAction: break; case TLValue::SendMessageChooseContactAction: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLStickerPack &type) { d << "TLStickerPack(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::StickerPack: d << "emoticon:" << type.emoticon; d << "documents:" << type.documents; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLStorageFileType &type) { d << "TLStorageFileType(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::StorageFileUnknown: break; case TLValue::StorageFileJpeg: break; case TLValue::StorageFileGif: break; case TLValue::StorageFilePng: break; case TLValue::StorageFilePdf: break; case TLValue::StorageFileMp3: break; case TLValue::StorageFileMov: break; case TLValue::StorageFilePartial: break; case TLValue::StorageFileMp4: break; case TLValue::StorageFileWebp: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUpdatesState &type) { d << "TLUpdatesState(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UpdatesState: d << "pts:" << type.pts; d << "qts:" << type.qts; d << "date:" << type.date; d << "seq:" << type.seq; d << "unreadCount:" << type.unreadCount; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUploadFile &type) { d << "TLUploadFile(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UploadFile: d << "type:" << type.type; d << "mtime:" << type.mtime; d << "bytes:" << type.bytes; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUserProfilePhoto &type) { d << "TLUserProfilePhoto(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UserProfilePhotoEmpty: break; case TLValue::UserProfilePhoto: d << "photoId:" << type.photoId; d << "photoSmall:" << type.photoSmall; d << "photoBig:" << type.photoBig; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUserStatus &type) { d << "TLUserStatus(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UserStatusEmpty: break; case TLValue::UserStatusOnline: d << "expires:" << type.expires; break; case TLValue::UserStatusOffline: d << "wasOnline:" << type.wasOnline; break; case TLValue::UserStatusRecently: break; case TLValue::UserStatusLastWeek: break; case TLValue::UserStatusLastMonth: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLVideo &type) { d << "TLVideo(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::VideoEmpty: d << "id:" << type.id; break; case TLValue::Video: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "userId:" << type.userId; d << "date:" << type.date; d << "caption:" << type.caption; d << "duration:" << type.duration; d << "mimeType:" << type.mimeType; d << "size:" << type.size; d << "thumb:" << type.thumb; d << "dcId:" << type.dcId; d << "w:" << type.w; d << "h:" << type.h; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLWallPaper &type) { d << "TLWallPaper(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::WallPaper: d << "id:" << type.id; d << "title:" << type.title; d << "sizes:" << type.sizes; d << "color:" << type.color; break; case TLValue::WallPaperSolid: d << "id:" << type.id; d << "title:" << type.title; d << "bgColor:" << type.bgColor; d << "color:" << type.color; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLChatPhoto &type) { d << "TLChatPhoto(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ChatPhotoEmpty: break; case TLValue::ChatPhoto: d << "photoSmall:" << type.photoSmall; d << "photoBig:" << type.photoBig; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLConfig &type) { d << "TLConfig(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::Config: d << "date:" << type.date; d << "expires:" << type.expires; d << "testMode:" << type.testMode; d << "thisDc:" << type.thisDc; d << "dcOptions:" << type.dcOptions; d << "chatBigSize:" << type.chatBigSize; d << "chatSizeMax:" << type.chatSizeMax; d << "broadcastSizeMax:" << type.broadcastSizeMax; d << "disabledFeatures:" << type.disabledFeatures; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactStatus &type) { d << "TLContactStatus(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactStatus: d << "userId:" << type.userId; d << "status:" << type.status; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLDialog &type) { d << "TLDialog(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::Dialog: d << "peer:" << type.peer; d << "topMessage:" << type.topMessage; d << "unreadCount:" << type.unreadCount; d << "notifySettings:" << type.notifySettings; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLDocument &type) { d << "TLDocument(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::DocumentEmpty: d << "id:" << type.id; break; case TLValue::Document: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "date:" << type.date; d << "mimeType:" << type.mimeType; d << "size:" << type.size; d << "thumb:" << type.thumb; d << "dcId:" << type.dcId; d << "attributes:" << type.attributes; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputChatPhoto &type) { d << "TLInputChatPhoto(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputChatPhotoEmpty: break; case TLValue::InputChatUploadedPhoto: d << "file:" << type.file; d << "crop:" << type.crop; break; case TLValue::InputChatPhoto: d << "id:" << type.id; d << "crop:" << type.crop; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputMedia &type) { d << "TLInputMedia(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputMediaEmpty: break; case TLValue::InputMediaUploadedPhoto: d << "file:" << type.file; break; case TLValue::InputMediaPhoto: d << "id:" << type.id; break; case TLValue::InputMediaGeoPoint: d << "geoPoint:" << type.geoPoint; break; case TLValue::InputMediaContact: d << "phoneNumber:" << type.phoneNumber; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; break; case TLValue::InputMediaUploadedVideo: d << "file:" << type.file; d << "duration:" << type.duration; d << "w:" << type.w; d << "h:" << type.h; d << "mimeType:" << type.mimeType; break; case TLValue::InputMediaUploadedThumbVideo: d << "file:" << type.file; d << "thumb:" << type.thumb; d << "duration:" << type.duration; d << "w:" << type.w; d << "h:" << type.h; d << "mimeType:" << type.mimeType; break; case TLValue::InputMediaVideo: d << "id:" << type.id; break; case TLValue::InputMediaUploadedAudio: d << "file:" << type.file; d << "duration:" << type.duration; d << "mimeType:" << type.mimeType; break; case TLValue::InputMediaAudio: d << "id:" << type.id; break; case TLValue::InputMediaUploadedDocument: d << "file:" << type.file; d << "mimeType:" << type.mimeType; d << "attributes:" << type.attributes; break; case TLValue::InputMediaUploadedThumbDocument: d << "file:" << type.file; d << "thumb:" << type.thumb; d << "mimeType:" << type.mimeType; d << "attributes:" << type.attributes; break; case TLValue::InputMediaDocument: d << "id:" << type.id; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputNotifyPeer &type) { d << "TLInputNotifyPeer(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputNotifyPeer: d << "peer:" << type.peer; break; case TLValue::InputNotifyUsers: break; case TLValue::InputNotifyChats: break; case TLValue::InputNotifyAll: break; case TLValue::InputNotifyGeoChatPeer: d << "peer:" << type.peer; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLInputPrivacyRule &type) { d << "TLInputPrivacyRule(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::InputPrivacyValueAllowContacts: break; case TLValue::InputPrivacyValueAllowAll: break; case TLValue::InputPrivacyValueAllowUsers: d << "users:" << type.users; break; case TLValue::InputPrivacyValueDisallowContacts: break; case TLValue::InputPrivacyValueDisallowAll: break; case TLValue::InputPrivacyValueDisallowUsers: d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesAllStickers &type) { d << "TLMessagesAllStickers(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesAllStickersNotModified: break; case TLValue::MessagesAllStickers: d << "hash:" << type.hash; d << "packs:" << type.packs; d << "documents:" << type.documents; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesStickers &type) { d << "TLMessagesStickers(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesStickersNotModified: break; case TLValue::MessagesStickers: d << "hash:" << type.hash; d << "stickers:" << type.stickers; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLNotifyPeer &type) { d << "TLNotifyPeer(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::NotifyPeer: d << "peer:" << type.peer; break; case TLValue::NotifyUsers: break; case TLValue::NotifyChats: break; case TLValue::NotifyAll: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPhoto &type) { d << "TLPhoto(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PhotoEmpty: d << "id:" << type.id; break; case TLValue::Photo: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "userId:" << type.userId; d << "date:" << type.date; d << "caption:" << type.caption; d << "geo:" << type.geo; d << "sizes:" << type.sizes; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUser &type) { d << "TLUser(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UserEmpty: d << "id:" << type.id; break; case TLValue::UserSelf: d << "id:" << type.id; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "username:" << type.username; d << "phone:" << type.phone; d << "photo:" << type.photo; d << "status:" << type.status; d << "inactive:" << type.inactive; break; case TLValue::UserContact: d << "id:" << type.id; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "username:" << type.username; d << "accessHash:" << type.accessHash; d << "phone:" << type.phone; d << "photo:" << type.photo; d << "status:" << type.status; break; case TLValue::UserRequest: d << "id:" << type.id; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "username:" << type.username; d << "accessHash:" << type.accessHash; d << "phone:" << type.phone; d << "photo:" << type.photo; d << "status:" << type.status; break; case TLValue::UserForeign: d << "id:" << type.id; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "username:" << type.username; d << "accessHash:" << type.accessHash; d << "photo:" << type.photo; d << "status:" << type.status; break; case TLValue::UserDeleted: d << "id:" << type.id; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "username:" << type.username; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAccountPrivacyRules &type) { d << "TLAccountPrivacyRules(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AccountPrivacyRules: d << "rules:" << type.rules; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLAuthAuthorization &type) { d << "TLAuthAuthorization(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::AuthAuthorization: d << "expires:" << type.expires; d << "user:" << type.user; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLChat &type) { d << "TLChat(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ChatEmpty: d << "id:" << type.id; break; case TLValue::Chat: d << "id:" << type.id; d << "title:" << type.title; d << "photo:" << type.photo; d << "participantsCount:" << type.participantsCount; d << "date:" << type.date; d << "left:" << type.left; d << "version:" << type.version; break; case TLValue::ChatForbidden: d << "id:" << type.id; d << "title:" << type.title; d << "date:" << type.date; break; case TLValue::GeoChat: d << "id:" << type.id; d << "accessHash:" << type.accessHash; d << "title:" << type.title; d << "address:" << type.address; d << "venue:" << type.venue; d << "geo:" << type.geo; d << "photo:" << type.photo; d << "participantsCount:" << type.participantsCount; d << "date:" << type.date; d << "checkedIn:" << type.checkedIn; d << "version:" << type.version; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLChatFull &type) { d << "TLChatFull(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ChatFull: d << "id:" << type.id; d << "participants:" << type.participants; d << "chatPhoto:" << type.chatPhoto; d << "notifySettings:" << type.notifySettings; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsBlocked &type) { d << "TLContactsBlocked(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsBlocked: d << "blocked:" << type.blocked; d << "users:" << type.users; break; case TLValue::ContactsBlockedSlice: d << "count:" << type.count; d << "blocked:" << type.blocked; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsContacts &type) { d << "TLContactsContacts(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsContactsNotModified: break; case TLValue::ContactsContacts: d << "contacts:" << type.contacts; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsFound &type) { d << "TLContactsFound(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsFound: d << "results:" << type.results; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsImportedContacts &type) { d << "TLContactsImportedContacts(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsImportedContacts: d << "imported:" << type.imported; d << "retryContacts:" << type.retryContacts; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsLink &type) { d << "TLContactsLink(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsLink: d << "myLink:" << type.myLink; d << "foreignLink:" << type.foreignLink; d << "user:" << type.user; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLContactsSuggested &type) { d << "TLContactsSuggested(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::ContactsSuggested: d << "results:" << type.results; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLHelpSupport &type) { d << "TLHelpSupport(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::HelpSupport: d << "phoneNumber:" << type.phoneNumber; d << "user:" << type.user; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessageAction &type) { d << "TLMessageAction(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessageActionEmpty: break; case TLValue::MessageActionChatCreate: d << "title:" << type.title; d << "users:" << type.users; break; case TLValue::MessageActionChatEditTitle: d << "title:" << type.title; break; case TLValue::MessageActionChatEditPhoto: d << "photo:" << type.photo; break; case TLValue::MessageActionChatDeletePhoto: break; case TLValue::MessageActionChatAddUser: d << "userId:" << type.userId; break; case TLValue::MessageActionChatDeleteUser: d << "userId:" << type.userId; break; case TLValue::MessageActionGeoChatCreate: d << "title:" << type.title; d << "address:" << type.address; break; case TLValue::MessageActionGeoChatCheckin: break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessageMedia &type) { d << "TLMessageMedia(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessageMediaEmpty: break; case TLValue::MessageMediaPhoto: d << "photo:" << type.photo; break; case TLValue::MessageMediaVideo: d << "video:" << type.video; break; case TLValue::MessageMediaGeo: d << "geo:" << type.geo; break; case TLValue::MessageMediaContact: d << "phoneNumber:" << type.phoneNumber; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "userId:" << type.userId; break; case TLValue::MessageMediaUnsupported: d << "bytes:" << type.bytes; break; case TLValue::MessageMediaDocument: d << "document:" << type.document; break; case TLValue::MessageMediaAudio: d << "audio:" << type.audio; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesChatFull &type) { d << "TLMessagesChatFull(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesChatFull: d << "fullChat:" << type.fullChat; d << "chats:" << type.chats; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesChats &type) { d << "TLMessagesChats(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesChats: d << "chats:" << type.chats; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesSentMessage &type) { d << "TLMessagesSentMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesSentMessage: d << "id:" << type.id; d << "date:" << type.date; d << "pts:" << type.pts; d << "seq:" << type.seq; break; case TLValue::MessagesSentMessageLink: d << "id:" << type.id; d << "date:" << type.date; d << "pts:" << type.pts; d << "seq:" << type.seq; d << "links:" << type.links; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPhotosPhoto &type) { d << "TLPhotosPhoto(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PhotosPhoto: d << "photo:" << type.photo; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLPhotosPhotos &type) { d << "TLPhotosPhotos(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::PhotosPhotos: d << "photos:" << type.photos; d << "users:" << type.users; break; case TLValue::PhotosPhotosSlice: d << "count:" << type.count; d << "photos:" << type.photos; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUserFull &type) { d << "TLUserFull(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UserFull: d << "user:" << type.user; d << "link:" << type.link; d << "profilePhoto:" << type.profilePhoto; d << "notifySettings:" << type.notifySettings; d << "blocked:" << type.blocked; d << "realFirstName:" << type.realFirstName; d << "realLastName:" << type.realLastName; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLGeoChatMessage &type) { d << "TLGeoChatMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::GeoChatMessageEmpty: d << "chatId:" << type.chatId; d << "id:" << type.id; break; case TLValue::GeoChatMessage: d << "chatId:" << type.chatId; d << "id:" << type.id; d << "fromId:" << type.fromId; d << "date:" << type.date; d << "message:" << type.message; d << "media:" << type.media; break; case TLValue::GeoChatMessageService: d << "chatId:" << type.chatId; d << "id:" << type.id; d << "fromId:" << type.fromId; d << "date:" << type.date; d << "action:" << type.action; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLGeochatsLocated &type) { d << "TLGeochatsLocated(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::GeochatsLocated: d << "results:" << type.results; d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLGeochatsMessages &type) { d << "TLGeochatsMessages(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::GeochatsMessages: d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; case TLValue::GeochatsMessagesSlice: d << "count:" << type.count; d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLGeochatsStatedMessage &type) { d << "TLGeochatsStatedMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::GeochatsStatedMessage: d << "message:" << type.message; d << "chats:" << type.chats; d << "users:" << type.users; d << "seq:" << type.seq; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessage &type) { d << "TLMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessageEmpty: d << "id:" << type.id; break; case TLValue::Message: d << "flags:" << type.flags; d << "id:" << type.id; d << "fromId:" << type.fromId; d << "toId:" << type.toId; d << "date:" << type.date; d << "message:" << type.message; d << "media:" << type.media; break; case TLValue::MessageForwarded: d << "flags:" << type.flags; d << "id:" << type.id; d << "fwdFromId:" << type.fwdFromId; d << "fwdDate:" << type.fwdDate; d << "fromId:" << type.fromId; d << "toId:" << type.toId; d << "date:" << type.date; d << "message:" << type.message; d << "media:" << type.media; break; case TLValue::MessageService: d << "flags:" << type.flags; d << "id:" << type.id; d << "fromId:" << type.fromId; d << "toId:" << type.toId; d << "date:" << type.date; d << "action:" << type.action; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesDialogs &type) { d << "TLMessagesDialogs(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesDialogs: d << "dialogs:" << type.dialogs; d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; case TLValue::MessagesDialogsSlice: d << "count:" << type.count; d << "dialogs:" << type.dialogs; d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesMessages &type) { d << "TLMessagesMessages(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesMessages: d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; case TLValue::MessagesMessagesSlice: d << "count:" << type.count; d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesStatedMessage &type) { d << "TLMessagesStatedMessage(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesStatedMessage: d << "message:" << type.message; d << "chats:" << type.chats; d << "users:" << type.users; d << "pts:" << type.pts; d << "seq:" << type.seq; break; case TLValue::MessagesStatedMessageLink: d << "message:" << type.message; d << "chats:" << type.chats; d << "users:" << type.users; d << "links:" << type.links; d << "pts:" << type.pts; d << "seq:" << type.seq; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLMessagesStatedMessages &type) { d << "TLMessagesStatedMessages(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::MessagesStatedMessages: d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; d << "pts:" << type.pts; d << "seq:" << type.seq; break; case TLValue::MessagesStatedMessagesLinks: d << "messages:" << type.messages; d << "chats:" << type.chats; d << "users:" << type.users; d << "links:" << type.links; d << "pts:" << type.pts; d << "seq:" << type.seq; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUpdate &type) { d << "TLUpdate(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UpdateNewMessage: d << "message:" << type.message; d << "pts:" << type.pts; break; case TLValue::UpdateMessageID: d << "id:" << type.id; d << "randomId:" << type.randomId; break; case TLValue::UpdateReadMessages: d << "messages:" << type.messages; d << "pts:" << type.pts; break; case TLValue::UpdateDeleteMessages: d << "messages:" << type.messages; d << "pts:" << type.pts; break; case TLValue::UpdateUserTyping: d << "userId:" << type.userId; d << "action:" << type.action; break; case TLValue::UpdateChatUserTyping: d << "chatId:" << type.chatId; d << "userId:" << type.userId; d << "action:" << type.action; break; case TLValue::UpdateChatParticipants: d << "participants:" << type.participants; break; case TLValue::UpdateUserStatus: d << "userId:" << type.userId; d << "status:" << type.status; break; case TLValue::UpdateUserName: d << "userId:" << type.userId; d << "firstName:" << type.firstName; d << "lastName:" << type.lastName; d << "username:" << type.username; break; case TLValue::UpdateUserPhoto: d << "userId:" << type.userId; d << "date:" << type.date; d << "photo:" << type.photo; d << "previous:" << type.previous; break; case TLValue::UpdateContactRegistered: d << "userId:" << type.userId; d << "date:" << type.date; break; case TLValue::UpdateContactLink: d << "userId:" << type.userId; d << "myLink:" << type.myLink; d << "foreignLink:" << type.foreignLink; break; case TLValue::UpdateNewAuthorization: d << "authKeyId:" << type.authKeyId; d << "date:" << type.date; d << "device:" << type.device; d << "location:" << type.location; break; case TLValue::UpdateNewGeoChatMessage: d << "message:" << type.message; break; case TLValue::UpdateNewEncryptedMessage: d << "message:" << type.message; d << "qts:" << type.qts; break; case TLValue::UpdateEncryptedChatTyping: d << "chatId:" << type.chatId; break; case TLValue::UpdateEncryption: d << "chat:" << type.chat; d << "date:" << type.date; break; case TLValue::UpdateEncryptedMessagesRead: d << "chatId:" << type.chatId; d << "maxDate:" << type.maxDate; d << "date:" << type.date; break; case TLValue::UpdateChatParticipantAdd: d << "chatId:" << type.chatId; d << "userId:" << type.userId; d << "inviterId:" << type.inviterId; d << "version:" << type.version; break; case TLValue::UpdateChatParticipantDelete: d << "chatId:" << type.chatId; d << "userId:" << type.userId; d << "version:" << type.version; break; case TLValue::UpdateDcOptions: d << "dcOptions:" << type.dcOptions; break; case TLValue::UpdateUserBlocked: d << "userId:" << type.userId; d << "blocked:" << type.blocked; break; case TLValue::UpdateNotifySettings: d << "peer:" << type.peer; d << "notifySettings:" << type.notifySettings; break; case TLValue::UpdateServiceNotification: d << "type:" << type.type; d << "message:" << type.message; d << "media:" << type.media; d << "popup:" << type.popup; break; case TLValue::UpdatePrivacy: d << "key:" << type.key; d << "rules:" << type.rules; break; case TLValue::UpdateUserPhone: d << "userId:" << type.userId; d << "phone:" << type.phone; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUpdates &type) { d << "TLUpdates(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UpdatesTooLong: break; case TLValue::UpdateShortMessage: d << "id:" << type.id; d << "fromId:" << type.fromId; d << "message:" << type.message; d << "pts:" << type.pts; d << "date:" << type.date; d << "seq:" << type.seq; break; case TLValue::UpdateShortChatMessage: d << "id:" << type.id; d << "fromId:" << type.fromId; d << "chatId:" << type.chatId; d << "message:" << type.message; d << "pts:" << type.pts; d << "date:" << type.date; d << "seq:" << type.seq; break; case TLValue::UpdateShort: d << "update:" << type.update; d << "date:" << type.date; break; case TLValue::UpdatesCombined: d << "updates:" << type.updates; d << "users:" << type.users; d << "chats:" << type.chats; d << "date:" << type.date; d << "seqStart:" << type.seqStart; d << "seq:" << type.seq; break; case TLValue::Updates: d << "updates:" << type.updates; d << "users:" << type.users; d << "chats:" << type.chats; d << "date:" << type.date; d << "seq:" << type.seq; break; default: break; } d << "}"; return d; } QDebug operator<<(QDebug d, const TLUpdatesDifference &type) { d << "TLUpdatesDifference(" << type.tlType.toString() << ") {"; switch (type.tlType) { case TLValue::UpdatesDifferenceEmpty: d << "date:" << type.date; d << "seq:" << type.seq; break; case TLValue::UpdatesDifference: d << "newMessages:" << type.newMessages; d << "newEncryptedMessages:" << type.newEncryptedMessages; d << "otherUpdates:" << type.otherUpdates; d << "chats:" << type.chats; d << "users:" << type.users; d << "state:" << type.state; break; case TLValue::UpdatesDifferenceSlice: d << "newMessages:" << type.newMessages; d << "newEncryptedMessages:" << type.newEncryptedMessages; d << "otherUpdates:" << type.otherUpdates; d << "chats:" << type.chats; d << "users:" << type.users; d << "intermediateState:" << type.intermediateState; break; default: break; } d << "}"; return d; } // End of generated TLTypes debug operators
TemeV/telegram-qt
telegram-qt/TLTypesDebug.cpp
C++
lgpl-2.1
65,475
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: toolbar.cpp Example File (demos/mainwindow/toolbar.cpp)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">toolbar.cpp Example File</h1> <span class="small-subtitle">demos/mainwindow/toolbar.cpp</span> <!-- $$$demos/mainwindow/toolbar.cpp-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> <span class="comment">/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/</span> <span class="preprocessor">#include &quot;toolbar.h&quot;</span> <span class="preprocessor">#include &lt;QMainWindow&gt;</span> <span class="preprocessor">#include &lt;QMenu&gt;</span> <span class="preprocessor">#include &lt;QPainter&gt;</span> <span class="preprocessor">#include &lt;QPainterPath&gt;</span> <span class="preprocessor">#include &lt;QSpinBox&gt;</span> <span class="preprocessor">#include &lt;QLabel&gt;</span> <span class="preprocessor">#include &lt;QToolTip&gt;</span> <span class="preprocessor">#include &lt;stdlib.h&gt;</span> <span class="keyword">static</span> <span class="type"><a href="qpixmap.html">QPixmap</a></span> genIcon(<span class="keyword">const</span> <span class="type"><a href="qsize.html">QSize</a></span> <span class="operator">&amp;</span>iconSize<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span><span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qcolor.html">QColor</a></span> <span class="operator">&amp;</span>color) { <span class="type">int</span> w <span class="operator">=</span> iconSize<span class="operator">.</span>width(); <span class="type">int</span> h <span class="operator">=</span> iconSize<span class="operator">.</span>height(); <span class="type"><a href="qimage.html">QImage</a></span> image(w<span class="operator">,</span> h<span class="operator">,</span> <span class="type"><a href="qimage.html">QImage</a></span><span class="operator">::</span>Format_ARGB32_Premultiplied); image<span class="operator">.</span>fill(<span class="number">0</span>); <span class="type"><a href="qpainter.html">QPainter</a></span> p(<span class="operator">&amp;</span>image); <span class="keyword">extern</span> <span class="type">void</span> render_qt_text(<span class="type"><a href="qpainter.html">QPainter</a></span> <span class="operator">*</span><span class="operator">,</span> <span class="type">int</span><span class="operator">,</span> <span class="type">int</span><span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qcolor.html">QColor</a></span> <span class="operator">&amp;</span>); render_qt_text(<span class="operator">&amp;</span>p<span class="operator">,</span> w<span class="operator">,</span> h<span class="operator">,</span> color); <span class="keyword">return</span> <span class="type"><a href="qpixmap.html">QPixmap</a></span><span class="operator">::</span>fromImage(image<span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>DiffuseDither <span class="operator">|</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>DiffuseAlphaDither); } <span class="keyword">static</span> <span class="type"><a href="qpixmap.html">QPixmap</a></span> genIcon(<span class="keyword">const</span> <span class="type"><a href="qsize.html">QSize</a></span> <span class="operator">&amp;</span>iconSize<span class="operator">,</span> <span class="type">int</span> number<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qcolor.html">QColor</a></span> <span class="operator">&amp;</span>color) { <span class="keyword">return</span> genIcon(iconSize<span class="operator">,</span> <span class="type"><a href="qstring.html">QString</a></span><span class="operator">::</span>number(number)<span class="operator">,</span> color); } ToolBar<span class="operator">::</span>ToolBar(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>title<span class="operator">,</span> <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent) : <span class="type"><a href="qtoolbar.html">QToolBar</a></span>(parent)<span class="operator">,</span> spinbox(<span class="number">0</span>)<span class="operator">,</span> spinboxAction(<span class="number">0</span>) { tip <span class="operator">=</span> <span class="number">0</span>; setWindowTitle(title); setObjectName(title); setIconSize(<span class="type"><a href="qsize.html">QSize</a></span>(<span class="number">32</span><span class="operator">,</span> <span class="number">32</span>)); <span class="type"><a href="qcolor.html">QColor</a></span> bg(palette()<span class="operator">.</span>background()<span class="operator">.</span>color()); menu <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qmenu.html">QMenu</a></span>(<span class="string">&quot;One&quot;</span><span class="operator">,</span> <span class="keyword">this</span>); menu<span class="operator">-</span><span class="operator">&gt;</span>setIcon(genIcon(iconSize()<span class="operator">,</span> <span class="number">1</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>black)); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(genIcon(iconSize()<span class="operator">,</span> <span class="string">&quot;A&quot;</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>blue)<span class="operator">,</span> <span class="string">&quot;A&quot;</span>); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(genIcon(iconSize()<span class="operator">,</span> <span class="string">&quot;B&quot;</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>blue)<span class="operator">,</span> <span class="string">&quot;B&quot;</span>); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(genIcon(iconSize()<span class="operator">,</span> <span class="string">&quot;C&quot;</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>blue)<span class="operator">,</span> <span class="string">&quot;C&quot;</span>); addAction(menu<span class="operator">-</span><span class="operator">&gt;</span>menuAction()); <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>two <span class="operator">=</span> addAction(genIcon(iconSize()<span class="operator">,</span> <span class="number">2</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>white)<span class="operator">,</span> <span class="string">&quot;Two&quot;</span>); <span class="type"><a href="qfont.html">QFont</a></span> boldFont; boldFont<span class="operator">.</span>setBold(<span class="keyword">true</span>); two<span class="operator">-</span><span class="operator">&gt;</span>setFont(boldFont); addAction(genIcon(iconSize()<span class="operator">,</span> <span class="number">3</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>red)<span class="operator">,</span> <span class="string">&quot;Three&quot;</span>); addAction(genIcon(iconSize()<span class="operator">,</span> <span class="number">4</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>green)<span class="operator">,</span> <span class="string">&quot;Four&quot;</span>); addAction(genIcon(iconSize()<span class="operator">,</span> <span class="number">5</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>blue)<span class="operator">,</span> <span class="string">&quot;Five&quot;</span>); addAction(genIcon(iconSize()<span class="operator">,</span> <span class="number">6</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>yellow)<span class="operator">,</span> <span class="string">&quot;Six&quot;</span>); orderAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="keyword">this</span>); orderAction<span class="operator">-</span><span class="operator">&gt;</span>setText(tr(<span class="string">&quot;Order Items in Tool Bar&quot;</span>)); connect(orderAction<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> SLOT(order())); randomizeAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="keyword">this</span>); randomizeAction<span class="operator">-</span><span class="operator">&gt;</span>setText(tr(<span class="string">&quot;Randomize Items in Tool Bar&quot;</span>)); connect(randomizeAction<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> SLOT(randomize())); addSpinBoxAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="keyword">this</span>); addSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setText(tr(<span class="string">&quot;Add Spin Box&quot;</span>)); connect(addSpinBoxAction<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> SLOT(addSpinBox())); removeSpinBoxAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="keyword">this</span>); removeSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setText(tr(<span class="string">&quot;Remove Spin Box&quot;</span>)); removeSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>); connect(removeSpinBoxAction<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> SLOT(removeSpinBox())); movableAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Movable&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span>); movableAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(movableAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(changeMovable(<span class="type">bool</span>))); allowedAreasActions <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qactiongroup.html">QActionGroup</a></span>(<span class="keyword">this</span>); allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>setExclusive(<span class="keyword">false</span>); allowLeftAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Allow on Left&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span>); allowLeftAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(allowLeftAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(allowLeft(<span class="type">bool</span>))); allowRightAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Allow on Right&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span>); allowRightAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(allowRightAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(allowRight(<span class="type">bool</span>))); allowTopAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Allow on Top&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span>); allowTopAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(allowTopAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(allowTop(<span class="type">bool</span>))); allowBottomAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Allow on Bottom&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span>); allowBottomAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(allowBottomAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(allowBottom(<span class="type">bool</span>))); allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(allowLeftAction); allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(allowRightAction); allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(allowTopAction); allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(allowBottomAction); areaActions <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qactiongroup.html">QActionGroup</a></span>(<span class="keyword">this</span>); areaActions<span class="operator">-</span><span class="operator">&gt;</span>setExclusive(<span class="keyword">true</span>); leftAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Place on Left&quot;</span>) <span class="operator">,</span> <span class="keyword">this</span>); leftAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(leftAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(placeLeft(<span class="type">bool</span>))); rightAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Place on Right&quot;</span>) <span class="operator">,</span> <span class="keyword">this</span>); rightAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(rightAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(placeRight(<span class="type">bool</span>))); topAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Place on Top&quot;</span>) <span class="operator">,</span> <span class="keyword">this</span>); topAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(topAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(placeTop(<span class="type">bool</span>))); bottomAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Place on Bottom&quot;</span>) <span class="operator">,</span> <span class="keyword">this</span>); bottomAction<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>); connect(bottomAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> SLOT(placeBottom(<span class="type">bool</span>))); areaActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(leftAction); areaActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(rightAction); areaActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(topAction); areaActions<span class="operator">-</span><span class="operator">&gt;</span>addAction(bottomAction); toolBarBreakAction <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">&quot;Insert break&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span>); connect(toolBarBreakAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(insertToolBarBreak())); connect(movableAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> areaActions<span class="operator">,</span> SLOT(setEnabled(<span class="type">bool</span>))); connect(movableAction<span class="operator">,</span> SIGNAL(triggered(<span class="type">bool</span>))<span class="operator">,</span> allowedAreasActions<span class="operator">,</span> SLOT(setEnabled(<span class="type">bool</span>))); menu <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qmenu.html">QMenu</a></span>(title<span class="operator">,</span> <span class="keyword">this</span>); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(toggleViewAction()); menu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator(); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(orderAction); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(randomizeAction); menu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator(); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(addSpinBoxAction); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(removeSpinBoxAction); menu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator(); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(movableAction); menu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator(); menu<span class="operator">-</span><span class="operator">&gt;</span>addActions(allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>actions()); menu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator(); menu<span class="operator">-</span><span class="operator">&gt;</span>addActions(areaActions<span class="operator">-</span><span class="operator">&gt;</span>actions()); menu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator(); menu<span class="operator">-</span><span class="operator">&gt;</span>addAction(toolBarBreakAction); connect(menu<span class="operator">,</span> SIGNAL(aboutToShow())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(updateMenu())); randomize(); } <span class="type">void</span> ToolBar<span class="operator">::</span>updateMenu() { <span class="type"><a href="qmainwindow.html">QMainWindow</a></span> <span class="operator">*</span>mainWindow <span class="operator">=</span> qobject_cast<span class="operator">&lt;</span><span class="type"><a href="qmainwindow.html">QMainWindow</a></span> <span class="operator">*</span><span class="operator">&gt;</span>(parentWidget()); Q_ASSERT(mainWindow <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span>); <span class="keyword">const</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ToolBarArea area <span class="operator">=</span> mainWindow<span class="operator">-</span><span class="operator">&gt;</span>toolBarArea(<span class="keyword">this</span>); <span class="keyword">const</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ToolBarAreas areas <span class="operator">=</span> allowedAreas(); movableAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(isMovable()); allowLeftAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(isAreaAllowed(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea)); allowRightAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(isAreaAllowed(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea)); allowTopAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(isAreaAllowed(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea)); allowBottomAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(isAreaAllowed(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea)); <span class="keyword">if</span> (allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>isEnabled()) { allowLeftAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea); allowRightAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea); allowTopAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea); allowBottomAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea); } leftAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(area <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea); rightAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(area <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea); topAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(area <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea); bottomAction<span class="operator">-</span><span class="operator">&gt;</span>setChecked(area <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea); <span class="keyword">if</span> (areaActions<span class="operator">-</span><span class="operator">&gt;</span>isEnabled()) { leftAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea); rightAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea); topAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea); bottomAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea); } } <span class="type">void</span> ToolBar<span class="operator">::</span>order() { <span class="type"><a href="qlist.html">QList</a></span><span class="operator">&lt;</span><span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span><span class="operator">&gt;</span> ordered<span class="operator">,</span> actions1 <span class="operator">=</span> actions()<span class="operator">,</span> actions2 <span class="operator">=</span> findChildren<span class="operator">&lt;</span><span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span><span class="operator">&gt;</span>(); <span class="keyword">while</span> (<span class="operator">!</span>actions2<span class="operator">.</span>isEmpty()) { <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>action <span class="operator">=</span> actions2<span class="operator">.</span>takeFirst(); <span class="keyword">if</span> (<span class="operator">!</span>actions1<span class="operator">.</span>contains(action)) <span class="keyword">continue</span>; actions1<span class="operator">.</span>removeAll(action); ordered<span class="operator">.</span>append(action); } clear(); addActions(ordered); orderAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>); } <span class="type">void</span> ToolBar<span class="operator">::</span>randomize() { <span class="type"><a href="qlist.html">QList</a></span><span class="operator">&lt;</span><span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span><span class="operator">&gt;</span> randomized<span class="operator">,</span> actions <span class="operator">=</span> <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>actions(); <span class="keyword">while</span> (<span class="operator">!</span>actions<span class="operator">.</span>isEmpty()) { <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>action <span class="operator">=</span> actions<span class="operator">.</span>takeAt(rand() <span class="operator">%</span> actions<span class="operator">.</span>size()); randomized<span class="operator">.</span>append(action); } clear(); addActions(randomized); orderAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">true</span>); } <span class="type">void</span> ToolBar<span class="operator">::</span>addSpinBox() { <span class="keyword">if</span> (<span class="operator">!</span>spinbox) { spinbox <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qspinbox.html">QSpinBox</a></span>(<span class="keyword">this</span>); } <span class="keyword">if</span> (<span class="operator">!</span>spinboxAction) spinboxAction <span class="operator">=</span> addWidget(spinbox); <span class="keyword">else</span> addAction(spinboxAction); addSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>); removeSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">true</span>); } <span class="type">void</span> ToolBar<span class="operator">::</span>removeSpinBox() { <span class="keyword">if</span> (spinboxAction) removeAction(spinboxAction); addSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">true</span>); removeSpinBoxAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>); } <span class="type">void</span> ToolBar<span class="operator">::</span>allow(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ToolBarArea area<span class="operator">,</span> <span class="type">bool</span> a) { <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ToolBarAreas areas <span class="operator">=</span> allowedAreas(); areas <span class="operator">=</span> a <span class="operator">?</span> areas <span class="operator">|</span> area : areas <span class="operator">&amp;</span> <span class="operator">~</span>area; setAllowedAreas(areas); <span class="keyword">if</span> (areaActions<span class="operator">-</span><span class="operator">&gt;</span>isEnabled()) { leftAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea); rightAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea); topAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea); bottomAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(areas <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea); } } <span class="type">void</span> ToolBar<span class="operator">::</span>place(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ToolBarArea area<span class="operator">,</span> <span class="type">bool</span> p) { <span class="keyword">if</span> (<span class="operator">!</span>p) <span class="keyword">return</span>; <span class="type"><a href="qmainwindow.html">QMainWindow</a></span> <span class="operator">*</span>mainWindow <span class="operator">=</span> qobject_cast<span class="operator">&lt;</span><span class="type"><a href="qmainwindow.html">QMainWindow</a></span> <span class="operator">*</span><span class="operator">&gt;</span>(parentWidget()); Q_ASSERT(mainWindow <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span>); mainWindow<span class="operator">-</span><span class="operator">&gt;</span>addToolBar(area<span class="operator">,</span> <span class="keyword">this</span>); <span class="keyword">if</span> (allowedAreasActions<span class="operator">-</span><span class="operator">&gt;</span>isEnabled()) { allowLeftAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea); allowRightAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea); allowTopAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea); allowBottomAction<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(area <span class="operator">!</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea); } } <span class="type">void</span> ToolBar<span class="operator">::</span>changeMovable(<span class="type">bool</span> movable) { setMovable(movable); } <span class="type">void</span> ToolBar<span class="operator">::</span>allowLeft(<span class="type">bool</span> a) { allow(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea<span class="operator">,</span> a); } <span class="type">void</span> ToolBar<span class="operator">::</span>allowRight(<span class="type">bool</span> a) { allow(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea<span class="operator">,</span> a); } <span class="type">void</span> ToolBar<span class="operator">::</span>allowTop(<span class="type">bool</span> a) { allow(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea<span class="operator">,</span> a); } <span class="type">void</span> ToolBar<span class="operator">::</span>allowBottom(<span class="type">bool</span> a) { allow(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea<span class="operator">,</span> a); } <span class="type">void</span> ToolBar<span class="operator">::</span>placeLeft(<span class="type">bool</span> p) { place(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>LeftToolBarArea<span class="operator">,</span> p); } <span class="type">void</span> ToolBar<span class="operator">::</span>placeRight(<span class="type">bool</span> p) { place(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightToolBarArea<span class="operator">,</span> p); } <span class="type">void</span> ToolBar<span class="operator">::</span>placeTop(<span class="type">bool</span> p) { place(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>TopToolBarArea<span class="operator">,</span> p); } <span class="type">void</span> ToolBar<span class="operator">::</span>placeBottom(<span class="type">bool</span> p) { place(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>BottomToolBarArea<span class="operator">,</span> p); } <span class="type">void</span> ToolBar<span class="operator">::</span>insertToolBarBreak() { <span class="type"><a href="qmainwindow.html">QMainWindow</a></span> <span class="operator">*</span>mainWindow <span class="operator">=</span> qobject_cast<span class="operator">&lt;</span><span class="type"><a href="qmainwindow.html">QMainWindow</a></span> <span class="operator">*</span><span class="operator">&gt;</span>(parentWidget()); Q_ASSERT(mainWindow <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span>); mainWindow<span class="operator">-</span><span class="operator">&gt;</span>insertToolBarBreak(<span class="keyword">this</span>); } <span class="type">void</span> ToolBar<span class="operator">::</span>enterEvent(<span class="type"><a href="qevent.html">QEvent</a></span><span class="operator">*</span>) { <span class="comment">/* These labels on top of toolbars look darn ugly if (tip == 0) { tip = new QLabel(windowTitle(), this); QPalette pal = tip-&gt;palette(); QColor c = Qt::black; c.setAlpha(100); pal.setColor(QPalette::Window, c); pal.setColor(QPalette::Foreground, Qt::white); tip-&gt;setPalette(pal); tip-&gt;setAutoFillBackground(true); tip-&gt;setMargin(3); tip-&gt;setText(windowTitle()); } QPoint c = rect().center(); QSize hint = tip-&gt;sizeHint(); tip-&gt;setGeometry(c.x() - hint.width()/2, c.y() - hint.height()/2, hint.width(), hint.height()); tip-&gt;show(); */</span> } <span class="type">void</span> ToolBar<span class="operator">::</span>leaveEvent(<span class="type"><a href="qevent.html">QEvent</a></span><span class="operator">*</span>) { <span class="keyword">if</span> (tip <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span>) tip<span class="operator">-</span><span class="operator">&gt;</span>hide(); }</pre> </div> <!-- @@@demos/mainwindow/toolbar.cpp --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2014 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
eric100lin/Qt-4.8.6
doc/html/demos-mainwindow-toolbar-cpp.html
HTML
lgpl-2.1
48,897
.t3-megamenu .mega-inner:before, .t3-megamenu .mega-inner:after { content: " "; display: table; } .t3-megamenu .mega-inner:after { clear: both; } .t3-megamenu .mega > .mega-dropdown-menu { min-width: 200px; display: none; } .t3-megamenu .mega.open > .mega-dropdown-menu, .t3-megamenu .mega.dropdown-submenu:hover > .mega-dropdown-menu { display: block; } .t3-megamenu .mega-group:before, .t3-megamenu .mega-group:after { content: " "; display: table; } .t3-megamenu .mega-group:after { clear: both; } .t3-megamenu .dropdown-header, .t3-megamenu .mega-nav .mega-group > .dropdown-header, .t3-megamenu .dropdown-menu .mega-nav .mega-group > .dropdown-header, .t3-megamenu .dropdown-menu .active .mega-nav .mega-group > .dropdown-header { margin: 0; padding: 0; background: transparent; color: #111111; font-size: 18px; line-height: normal; } .t3-megamenu .dropdown-header:hover, .t3-megamenu .mega-nav .mega-group > .dropdown-header:hover, .t3-megamenu .dropdown-menu .mega-nav .mega-group > .dropdown-header:hover, .t3-megamenu .dropdown-menu .active .mega-nav .mega-group > .dropdown-header:hover, .t3-megamenu .dropdown-header:active, .t3-megamenu .mega-nav .mega-group > .dropdown-header:active, .t3-megamenu .dropdown-menu .mega-nav .mega-group > .dropdown-header:active, .t3-megamenu .dropdown-menu .active .mega-nav .mega-group > .dropdown-header:active, .t3-megamenu .dropdown-header:focus, .t3-megamenu .mega-nav .mega-group > .dropdown-header:focus, .t3-megamenu .dropdown-menu .mega-nav .mega-group > .dropdown-header:focus, .t3-megamenu .dropdown-menu .active .mega-nav .mega-group > .dropdown-header:focus { background: inherit; color: inherit; } .t3-megamenu .mega-group-ct { margin: 0; padding: 0; } .t3-megamenu .mega-group-ct:before, .t3-megamenu .mega-group-ct:after { content: " "; display: table; } .t3-megamenu .mega-group-ct:after { clear: both; } .t3-megamenu .mega-nav, .t3-megamenu .dropdown-menu .mega-nav { margin: 0; padding: 0; list-style: none; } .t3-megamenu .mega-nav > li, .t3-megamenu .dropdown-menu .mega-nav > li { list-style: none; margin-right: 0; } .t3-megamenu .mega-nav > li a, .t3-megamenu .dropdown-menu .mega-nav > li a { white-space: normal; display: block; padding: 5px; } .t3-megamenu .mega-nav > li a:hover, .t3-megamenu .dropdown-menu .mega-nav > li a:hover, .t3-megamenu .mega-nav > li a:focus, .t3-megamenu .dropdown-menu .mega-nav > li a:focus { text-decoration: none; color: #262626; background-color: #f5f5f5; } .t3-megamenu .mega-nav > li .separator { display: block; padding: 5px; } .t3-megamenu .mega-group > .mega-nav, .t3-megamenu .dropdown-menu .mega-group > .mega-nav { margin-right: -5px; margin-left: -5px; } .t3-megamenu .mega-nav .dropdown-submenu > a::after { margin-left: 5px; } .t3-megamenu .t3-module { margin-bottom: 10px; } .t3-megamenu .t3-module .module-title { margin: 0; padding: 0; background: transparent; color: #111111; font-size: 18px; line-height: normal; margin-bottom: 5px; } .t3-megamenu .t3-module .module-title:hover, .t3-megamenu .t3-module .module-title:active, .t3-megamenu .t3-module .module-title:focus { background: inherit; color: inherit; } .t3-megamenu .t3-module .module-ct { margin: 0; padding: 0; } .t3-megamenu .mega-caption { display: block; white-space: nowrap; } .t3-megamenu .nav .caret, .t3-megamenu .dropdown-submenu .caret, .t3-megamenu .mega-menu .caret { display: none; } .t3-megamenu .nav > .dropdown > .dropdown-toggle .caret { display: inline-block; } .t3-megamenu .nav [class^="icon-"], .t3-megamenu .nav [class*=" icon-"], .t3-megamenu .nav .fa { margin-left: 5px; } .t3-megamenu .nav .input-group-addon [class^="icon-"], .t3-megamenu .nav .input-group-addon [class*=" icon-"], .t3-megamenu .nav .input-group-addon .fa { margin-left: 0; } .t3-megamenu .mega-align-left > .dropdown-menu { right: 0; } .t3-megamenu .mega-align-right > .dropdown-menu { right: auto; left: 0; } .t3-megamenu .mega-align-center > .dropdown-menu { right: 50%; -webkit-transform: translate(-50%, 0); -ms-transform: translate(-50%, 0); transform: translate(-50%, 0); } .t3-megamenu .dropdown-submenu.mega-align-left > .dropdown-menu { right: 100%; } .t3-megamenu .dropdown-submenu.mega-align-right > .dropdown-menu { right: auto; left: 100%; } .t3-megamenu .mega-align-justify { position: static; } .t3-megamenu .mega-align-justify > .dropdown-menu { right: 0; margin-right: 0; top: auto; } @media (min-width: 768px) { .t3-megamenu.animate .mega > .mega-dropdown-menu { -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; backface-visibility: hidden; opacity: 0; } .t3-megamenu.animate .mega.animating > .mega-dropdown-menu { -webkit-transition: all 400ms; transition: all 400ms; display: block!important; } .t3-megamenu.animate .mega.open > .mega-dropdown-menu, .t3-megamenu.animate .mega.animating.open > .mega-dropdown-menu { opacity: 1; } .t3-megamenu.animate.zoom .mega > .mega-dropdown-menu { -webkit-transform: scale(0, 0); -ms-transform: scale(0, 0); transform: scale(0, 0); -webkit-transform-origin: 20% 20%; -moz-transform-origin: 20% 20%; transform-origin: 20% 20%; } .t3-megamenu.animate.zoom .mega.open > .mega-dropdown-menu { -webkit-transform: scale(1, 1); -ms-transform: scale(1, 1); transform: scale(1, 1); } .t3-megamenu.animate.zoom .level0 > .mega-align-center > .mega-dropdown-menu { -webkit-transform: scale(0, 0) translate(-50%, 0); -ms-transform: scale(0, 0) translate(-50%, 0); transform: scale(0, 0) translate(-50%, 0); -webkit-transform-origin: 0% 20%; -moz-transform-origin: 0% 20%; transform-origin: 0% 20%; } .t3-megamenu.animate.zoom .level0 > .mega-align-center.open > .mega-dropdown-menu { -webkit-transform: scale(1, 1) translate(-50%, 0); -ms-transform: scale(1, 1) translate(-50%, 0); transform: scale(1, 1) translate(-50%, 0); } .t3-megamenu.animate.elastic .mega > .mega-dropdown-menu { -webkit-transform: scale(0, 1); -ms-transform: scale(0, 1); transform: scale(0, 1); -webkit-transform-origin: 10% 0; -moz-transform-origin: 10% 0; transform-origin: 10% 0; } .t3-megamenu.animate.elastic .mega.open > .mega-dropdown-menu { -webkit-transform: scale(1, 1); -ms-transform: scale(1, 1); transform: scale(1, 1); } .t3-megamenu.animate.elastic .level0 > .mega > .mega-dropdown-menu { -webkit-transform: scale(1, 0); -ms-transform: scale(1, 0); transform: scale(1, 0); } .t3-megamenu.animate.elastic .level0 .open > .mega-dropdown-menu { -webkit-transform: scale(1, 1); -ms-transform: scale(1, 1); transform: scale(1, 1); } .t3-megamenu.animate.elastic .level0 > .mega-align-center > .mega-dropdown-menu { transform: scale(1, 0) translate(-50%, 0); -webkit-transform: scale(1, 0) translate(-50%, 0); -ms-transform: scale(1, 0) translate(-50%, 0); } .t3-megamenu.animate.elastic .level0 > .mega-align-center.open > .mega-dropdown-menu { transform: scale(1, 1) translate(-50%, 0); -webkit-transform: scale(1, 1) translate(-50%, 0); -ms-transform: scale(1, 1) translate(-50%, 0); } .t3-megamenu.animate.slide .mega { } .t3-megamenu.animate.slide .mega.animating > .mega-dropdown-menu { overflow: hidden; } .t3-megamenu.animate.slide .mega > .mega-dropdown-menu > div { -webkit-transition: all 400ms; transition: all 400ms; -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; backface-visibility: hidden; margin-top: -100%; } .t3-megamenu.animate.slide .mega.open > .mega-dropdown-menu > div { margin-top: 0%; } .t3-megamenu.animate.slide .mega .mega > .mega-dropdown-menu { min-width: 0; } .t3-megamenu.animate.slide .mega .mega > .mega-dropdown-menu > div { min-width: 200px; margin-top: 0; margin-right: -500px; } .t3-megamenu.animate.slide .mega .mega.open > .mega-dropdown-menu > div { margin-right: 0; } } @media (max-width: 767px) { .t3-megamenu .row, .t3-megamenu .mega-dropdown-menu, .t3-megamenu .row [class*="col-lg-"], .t3-megamenu .row [class*="col-md-"], .t3-megamenu .row [class*="col-sm-"], .t3-megamenu .row [class*="col-xs-"] { width: 100% !important; min-width: 100% !important; right: 0 !important; margin-right: 0 !important; -webkit-transform: none !important; -ms-transform: none !important; transform: none !important; } .t3-megamenu .hidden-collapse, .t3-megamenu .always-show .caret, .t3-megamenu .always-show .dropdown-submenu > a:after .sub-hidden-collapse > .nav-child, .t3-megamenu .sub-hidden-collapse .caret, .t3-megamenu .sub-hidden-collapse > a:after { display: none !important; } .t3-megamenu .mega-caption { display: none !important; } html[dir="rtl"] .t3-megamenu .row, html[dir="rtl"] .t3-megamenu .mega-dropdown-menu, html[dir="rtl"] .t3-megamenu .row [class*="col-lg-"], html[dir="rtl"] .t3-megamenu .row [class*="col-md-"], html[dir="rtl"] .t3-megamenu .row [class*="col-sm-"], html[dir="rtl"] .t3-megamenu .row [class*="col-xs-"] { right: auto; left: 0 !important; margin-left: 0 !important; } } .t3-megamenu .mega-inner { padding: 10px 0; } .t3-megamenu .row { margin-right: auto; margin-left: 0; } .t3-megamenu .row .row { margin-right: -20px; margin-left: -20px; } .t3-megamenu .row + .row { padding-top: 10px; border-top: 1px solid #eeeeee; } .t3-megamenu .mega-dropdown-menu { border-radius: 0; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.175); box-shadow: 0 2px 2px rgba(0, 0, 0, 0.175); } .t3-megamenu .mega-dropdown-menu .mega-dropdown-inner .row { margin-right: 0; margin-left: 0; } .t3-megamenu .dropdown-submenu > .dropdown-menu { border-radius: 0; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.175); box-shadow: 0 2px 2px rgba(0, 0, 0, 0.175); } .t3-megamenu .mega-col-nav { padding-right: 0; padding-left: 0; } .t3-megamenu .col-lg-12.mega-col-nav .mega-inner, .t3-megamenu .col-md-12.mega-col-nav .mega-inner, .t3-megamenu .col-sm-12.mega-col-nav .mega-inner, .t3-megamenu .col-xs-12.mega-col-nav .mega-inner { padding: 0; } .t3-megamenu .mega-nav > li a, .t3-megamenu .dropdown-menu .mega-nav > li a, .t3-megamenu .dropdown-menu .mega-nav > li .separator { border-bottom: solid 1px #eee; background: #ffffff; color: #666; font-weight: 300; padding: 10px 20px; } .t3-megamenu .mega-nav > li a:hover, .t3-megamenu .dropdown-menu .mega-nav > li a:hover, .t3-megamenu .dropdown-menu .mega-nav > li .separator:hover, .t3-megamenu .mega-nav > li a:focus, .t3-megamenu .dropdown-menu .mega-nav > li a:focus, .t3-megamenu .dropdown-menu .mega-nav > li .separator:focus, .t3-megamenu .mega-nav > li a:active, .t3-megamenu .dropdown-menu .mega-nav > li a:active, .t3-megamenu .dropdown-menu .mega-nav > li .separator:active { background: #ffffff; color: #1abc9c; } .t3-megamenu .mega-nav > li.active a, .t3-megamenu .dropdown-menu .mega-nav > li.active a, .t3-megamenu .dropdown-menu .mega-nav > li .separator { color: #1abc9c; } .t3-megamenu .dropdown-menu .mega-nav > li.active li a, .t3-megamenu .dropdown-menu .mega-nav > li li .separator { color: #666; } .t3-megamenu .dropdown-menu .mega-nav > li.active li a:hover, .t3-megamenu .dropdown-menu .mega-nav > li li .separator:hover, .t3-megamenu .dropdown-menu .mega-nav > li.active li a:focus, .t3-megamenu .dropdown-menu .mega-nav > li li .separator:focus, .t3-megamenu .dropdown-menu .mega-nav > li.active li a:active, .t3-megamenu .dropdown-menu .mega-nav > li li .separator:active { color: #1abc9c; } .t3-megamenu .dropdown-menu .mega-nav > li.active li.active a, .t3-megamenu .dropdown-menu .mega-nav > li li.active .separator { color: #1abc9c; } .t3-megamenu .mega-nav .dropdown-submenu > a::after { margin-left: 0; } .t3-megamenu .t3-module .module-title { padding-top: 5px; padding-bottom: 5px; margin-bottom: 10px; } .t3-megamenu .t3-module ul li, .t3-megamenu .t3-module .nav li { list-style: disc; display: list-item; float: none; margin: 0; padding: 0; border: 0; } .t3-megamenu .t3-module ul li a, .t3-megamenu .t3-module .nav li a { display: inline; padding: 0; margin: 0; border: 0; font-size: 100%; background: none; font: inherit; white-space: normal; } .t3-megamenu .t3-module ul li a:hover, .t3-megamenu .t3-module .nav li a:hover, .t3-megamenu .t3-module ul li a:focus, .t3-megamenu .t3-module .nav li a:focus, .t3-megamenu .t3-module ul li a:active, .t3-megamenu .t3-module .nav li a:active { background: none; color: inherit; font: inherit; } .t3-megamenu .mega-caption { color: #999999; font-size: 12px; margin-top: 3px; font-weight: normal; } html[dir="rtl"] .t3-megamenu .mega-align-center > .dropdown-menu { -webkit-transform: translate(50%, 0); -ms-transform: translate(50%, 0); transform: translate(50%, 0); } html[dir="rtl"] .t3-megamenu .mega-nav .dropdown-submenu > a:after { direction: ltr; } html[dir="rtl"] .t3-megamenu.animate.zoom .mega > .mega-dropdown-menu { -webkit-transform-origin: 80% 20%; -moz-transform-origin: 80% 20%; transform-origin: 80% 20%; } html[dir="rtl"] .t3-megamenu.animate.zoom .level0 > .mega-align-center > .mega-dropdown-menu { -webkit-transform: scale(0, 0) translate(50%, 0); -ms-transform: scale(0, 0) translate(50%, 0); transform: scale(0, 0) translate(50%, 0); -webkit-transform-origin: 100% 20%; -moz-transform-origin: 100% 20%; transform-origin: 100% 20%; } html[dir="rtl"] .t3-megamenu.animate.zoom .level0 > .mega-align-center.open > .mega-dropdown-menu { -webkit-transform: scale(1, 1) translate(50%, 0); -ms-transform: scale(1, 1) translate(50%, 0); transform: scale(1, 1) translate(50%, 0); } html[dir="rtl"] .t3-megamenu.animate.elastic .level0 > .mega-align-center > .mega-dropdown-menu { transform: scale(1, 0) translate(50%, 0); -webkit-transform: scale(1, 0) translate(50%, 0); -ms-transform: scale(1, 0) translate(50%, 0); } html[dir="rtl"] .t3-megamenu.animate.elastic .level0 > .mega-align-center.open > .mega-dropdown-menu { transform: scale(1, 1) translate(50%, 0); -webkit-transform: scale(1, 1) translate(50%, 0); -ms-transform: scale(1, 1) translate(50%, 0); }
dhbahr/odoo-themes
theme_shasti/static/css/rtl/turquoise/megamenu.css
CSS
lgpl-2.1
14,427
/* Copyright (C) 2009 William Hart Copyright (C) 2010, 2011 Sebastian Pancratz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpz_poly.h" #include "ulong_extras.h" int main(void) { int i, result; FLINT_TEST_INIT(state); flint_printf("sqr_karatsuba...."); fflush(stdout); /* Check aliasing of a and b */ for (i = 0; i < 200 * flint_test_multiplier(); i++) { fmpz_poly_t a, b, c; fmpz_poly_init(a); fmpz_poly_init(b); fmpz_poly_init(c); fmpz_poly_randtest(a, state, n_randint(state, 50), 200); fmpz_poly_set(b, a); fmpz_poly_sqr_karatsuba(c, b); fmpz_poly_sqr_karatsuba(b, b); result = (fmpz_poly_equal(b, c)); if (!result) { flint_printf("FAIL:\n"); fmpz_poly_print(a), flint_printf("\n\n"); fmpz_poly_print(b), flint_printf("\n\n"); fmpz_poly_print(c), flint_printf("\n\n"); abort(); } fmpz_poly_clear(a); fmpz_poly_clear(b); fmpz_poly_clear(c); } /* Compare with mul_karatsuba */ for (i = 0; i < 200 * flint_test_multiplier(); i++) { fmpz_poly_t a, b, c; fmpz_poly_init(a); fmpz_poly_init(b); fmpz_poly_init(c); fmpz_poly_randtest(a, state, n_randint(state, 50), 200); fmpz_poly_sqr_karatsuba(b, a); fmpz_poly_mul_karatsuba(c, a, a); result = (fmpz_poly_equal(b, c)); if (!result) { flint_printf("FAIL:\n"); fmpz_poly_print(a), flint_printf("\n\n"); fmpz_poly_print(b), flint_printf("\n\n"); fmpz_poly_print(c), flint_printf("\n\n"); abort(); } fmpz_poly_clear(a); fmpz_poly_clear(b); fmpz_poly_clear(c); } /* Check _fmpz_poly_sqr_karatsuba directly */ for (i = 0; i < 200 * flint_test_multiplier(); i++) { slong len; fmpz_poly_t a, out1, out2; len = n_randint(state, 100) + 1; fmpz_poly_init(a); fmpz_poly_init(out1); fmpz_poly_init(out2); fmpz_poly_randtest(a, state, len, 200); fmpz_poly_sqr_karatsuba(out1, a); fmpz_poly_fit_length(a, a->alloc + n_randint(state, 10)); a->length = a->alloc; fmpz_poly_fit_length(out2, 2 * a->length - 1); _fmpz_poly_sqr_karatsuba(out2->coeffs, a->coeffs, a->length); _fmpz_poly_set_length(out2, 2 * a->length - 1); _fmpz_poly_normalise(out2); result = (fmpz_poly_equal(out1, out2)); if (!result) { flint_printf("FAIL:\n"); fmpz_poly_print(out1), flint_printf("\n\n"); fmpz_poly_print(out2), flint_printf("\n\n"); abort(); } fmpz_poly_clear(a); fmpz_poly_clear(out1); fmpz_poly_clear(out2); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
dsroche/flint2
fmpz_poly/test/t-sqr_karatsuba.c
C
lgpl-2.1
3,371
git fetch origin & git checkout origin/windows
timbertson/gup
update-win.bat
Batchfile
lgpl-2.1
47
/*************************************************************************** * Copyright (c) 2013 Jan Rheinländer <jrheinlaender[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoRotation.h> # include <Inventor/nodes/SoMultipleCopy.h> # include <Precision.hxx> #endif #include "ViewProviderFemConstraintFixed.h" #include <Mod/Fem/App/FemConstraintFixed.h> #include "TaskFemConstraintFixed.h" #include "Gui/Control.h" #include <Base/Console.h> using namespace FemGui; PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintFixed, FemGui::ViewProviderFemConstraint) ViewProviderFemConstraintFixed::ViewProviderFemConstraintFixed() { sPixmap = "Fem_ConstraintFixed"; } ViewProviderFemConstraintFixed::~ViewProviderFemConstraintFixed() { } bool ViewProviderFemConstraintFixed::setEdit(int ModNum) { Base::Console().Error("ViewProviderFemConstraintFixed::setEdit()\n"); if (ModNum == ViewProvider::Default ) { // When double-clicking on the item for this constraint the // object unsets and sets its edit mode without closing // the task panel Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); TaskDlgFemConstraintFixed *constrDlg = qobject_cast<TaskDlgFemConstraintFixed *>(dlg); if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = 0; // another constraint left open its task panel if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); if ((wizardWidget == NULL) || (wizardSubLayout == NULL)) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); if (ret == QMessageBox::Yes) Gui::Control().reject(); else return false; } else if (constraintDialog != NULL) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; } else { constraintDialog = new TaskFemConstraintFixed(this); return true; } } // clear the selection (convenience) Gui::Selection().clearSelection(); // start the edit dialog if (constrDlg) Gui::Control().showDialog(constrDlg); else Gui::Control().showDialog(new TaskDlgFemConstraintFixed(this)); return true; } else { return ViewProviderDocumentObject::setEdit(ModNum); } } #define HEIGHT 4 #define WIDTH (1.5*HEIGHT) void ViewProviderFemConstraintFixed::updateData(const App::Property* prop) { // Gets called whenever a property of the attached object changes Fem::ConstraintFixed* pcConstraint = static_cast<Fem::ConstraintFixed*>(this->getObject()); /* // This has a HUGE performance penalty as opposed to separate nodes for every symbol // The problem seems to be SoCone if (pShapeSep->getNumChildren() == 0) { // Set up the nodes SoMultipleCopy* cp = new SoMultipleCopy(); cp->ref(); cp->matrix.setNum(0); cp->addChild((SoNode*)createFixed(HEIGHT, WIDTH)); pShapeSep->addChild(cp); } */ if (strcmp(prop->getName(),"Points") == 0) { const std::vector<Base::Vector3d>& points = pcConstraint->Points.getValues(); const std::vector<Base::Vector3d>& normals = pcConstraint->Normals.getValues(); if (points.size() != normals.size()) return; std::vector<Base::Vector3d>::const_iterator n = normals.begin(); // Note: Points and Normals are always updated together pShapeSep->removeAllChildren(); /* SoMultipleCopy* cp = static_cast<SoMultipleCopy*>(pShapeSep->getChild(0)); cp->matrix.setNum(points.size()); int idx = 0; */ for (std::vector<Base::Vector3d>::const_iterator p = points.begin(); p != points.end(); p++) { SbVec3f base(p->x, p->y, p->z); SbVec3f dir(n->x, n->y, n->z); SbRotation rot(SbVec3f(0,-1,0), dir); /* SbMatrix m; m.setTransform(base, rot, SbVec3f(1,1,1)); cp->matrix.set1Value(idx, m); idx++ */ SoSeparator* sep = new SoSeparator(); createPlacement(sep, base, rot); createFixed(sep, HEIGHT, WIDTH); pShapeSep->addChild(sep); n++; } } ViewProviderFemConstraint::updateData(prop); }
timthelion/FreeCAD_sf_master
src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.cpp
C++
lgpl-2.1
6,751
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef RESTARTABLEDATAIO_H #define RESTARTABLEDATAIO_H // MOOSE includes #include "DataIO.h" // C++ includes #include <sstream> #include <string> #include <list> // Forward declarations class RestartableDatas; class RestartableDataValue; class FEProblem; /** * Helper class to hold streams for Backup and Restore operations. */ class Backup { public: Backup() { unsigned int n_threads = libMesh::n_threads(); _restartable_data.resize(n_threads); for (unsigned int i=0; i < n_threads; i++) _restartable_data[i] = new std::stringstream; } ~Backup() { unsigned int n_threads = libMesh::n_threads(); for (unsigned int i=0; i < n_threads; i++) delete _restartable_data[i]; } std::stringstream _system_data; std::vector<std::stringstream*> _restartable_data; }; template<> inline void dataStore(std::ostream & stream, Backup * & backup, void * context) { dataStore(stream, backup->_system_data, context); for (unsigned int i=0; i<backup->_restartable_data.size(); i++) dataStore(stream, backup->_restartable_data[i], context); } template<> inline void dataLoad(std::istream & stream, Backup * & backup, void * context) { dataLoad(stream, backup->_system_data, context); for (unsigned int i=0; i<backup->_restartable_data.size(); i++) dataLoad(stream, backup->_restartable_data[i], context); } /** * Class for doing restart. * * It takes care of writing and reading the restart files. */ class RestartableDataIO { public: RestartableDataIO(FEProblem & fe_problem); virtual ~RestartableDataIO(); /** * Write out the restartable data. */ void writeRestartableData(std::string base_file_name, const RestartableDatas & restartable_datas, std::set<std::string> & _recoverable_data); /** * Read restartable data header to verify that we are restarting on the correct number of processors and threads. */ void readRestartableDataHeader(std::string base_file_name); /** * Read the restartable data. */ void readRestartableData(const RestartableDatas & restartable_datas, const std::set<std::string> & _recoverable_data); /** * Create a Backup for the current system. */ MooseSharedPointer<Backup> createBackup(); /** * Restore a Backup for the current system. */ void restoreBackup(MooseSharedPointer<Backup> backup, bool for_restart = false); private: /** * Serializes the data into the stream object. */ void serializeRestartableData(const std::map<std::string, RestartableDataValue *> & restartable_data, std::ostream & stream); /** * Deserializes the data from the stream object. */ void deserializeRestartableData(const std::map<std::string, RestartableDataValue *> & restartable_data, std::istream & stream, const std::set<std::string> & recoverable_data); /** * Serializes the data for the Systems in FEProblem */ void serializeSystems(std::ostream & stream); /** * Deserializes the data for the Systems in FEProblem */ void deserializeSystems(std::istream & stream); /// Reference to a FEProblem being restarted FEProblem & _fe_problem; /// A vector of file handles, one per thread std::vector<std::ifstream *> _in_file_handles; }; #endif /* RESTARTABLEDATAIO_H */
wgapl/moose
framework/include/restart/RestartableDataIO.h
C
lgpl-2.1
4,132
include ../Makefile.tests_common BOARD_INSUFFICIENT_MEMORY := arduino-duemilanove arduino-nano arduino-uno # These boards only have a single timer in their periph_conf.h, needs special # CFLAGS configuration to build properly SINGLE_TIMER_BOARDS = \ native \ nucleo-f031k6 \ nucleo-f042k6 \ # # These boards have too little RAM to support collecting detailed statistics # with the default settings of TEST_MIN and TEST_MAX, so DETAILED_STATS will be # disabled by default for these boards unless explicitly enabled SMALL_RAM_BOARDS = \ nucleo-f031k6 \ # FEATURES_REQUIRED = periph_timer # Use RTT as a wall clock reference, if available FEATURES_OPTIONAL = periph_rtt USEMODULE += random USEMODULE += fmt USEMODULE += matstat USEMODULE += xtimer ifeq (,$(findstring TIM_TEST_DEV,$(CFLAGS))) ifneq (,$(filter $(BOARD),$(SINGLE_TIMER_BOARDS))) CFLAGS += -DTIM_TEST_DEV=TIMER_DEV\(0\) -DTIM_REF_DEV=TIMER_DEV\(0\) endif endif ifeq (,$(findstring DETAILED_STATS,$(CFLAGS))) ifneq (,$(filter $(BOARD),$(SMALL_RAM_BOARDS))) CFLAGS += -DDETAILED_STATS=0 endif endif # Shortcut to configure the build for testing xtimer against a periph_timer reference .PHONY: test-xtimer test-xtimer: CFLAGS+=-DTEST_XTIMER -DTIM_TEST_FREQ=XTIMER_HZ -DTIM_TEST_DEV=XTIMER_DEV test-xtimer: all # Shortcut to configure the build for testing Kinetis LPTMR against a PIT reference # Usage: make BOARD=frdm-k22f test-kinetis-lptmr flash .PHONY: test-kinetis-lptmr test-kinetis-lptmr: CFLAGS+=-DTIM_TEST_DEV=TIMER_LPTMR_DEV\(0\) -DTIM_TEST_FREQ=32768 -DTIM_REF_DEV=TIMER_PIT_DEV\(0\) test-kinetis-lptmr: all # Reset the default goal. .DEFAULT_GOAL := include $(RIOTBASE)/Makefile.include
lazytech-org/RIOT
tests/bench_timers/Makefile
Makefile
lgpl-2.1
1,698
// IFC SDK : IFC2X3 C++ Early Classes // Copyright (C) 2009 CSTB // // 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. // The full license is in Licence.txt file included with this // distribution or is available at : // http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html // // 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. #ifndef IFC2X3_DEFINEDTYPES_H #define IFC2X3_DEFINEDTYPES_H #include <Step/Array.h> #include <Step/Set.h> #include <Step/List.h> #include <Step/Bag.h> #include <Step/SimpleTypes.h> #include <ifc2x3/fwDecl.h> namespace ifc2x3 { /** */ typedef Step::Real IfcAbsorbedDoseMeasure; /** */ typedef Step::Real IfcAccelerationMeasure; /** */ typedef Step::Real IfcAmountOfSubstanceMeasure; /** */ typedef Step::Real IfcAngularVelocityMeasure; /** */ typedef Step::Real IfcAreaMeasure; /** */ typedef Step::Boolean IfcBoolean; /** */ typedef Step::String IfcBoxAlignment; /** */ typedef Step::Real IfcContextDependentMeasure; /** */ typedef Step::Number IfcCountMeasure; /** */ typedef Step::Real IfcCurvatureMeasure; /** */ typedef Step::Integer IfcDayInMonthNumber; /** */ typedef Step::Integer IfcDaylightSavingHour; /** */ typedef Step::String IfcDescriptiveMeasure; /** */ typedef Step::Integer IfcDimensionCount; /** */ typedef Step::Real IfcDoseEquivalentMeasure; /** */ typedef Step::Real IfcDynamicViscosityMeasure; /** */ typedef Step::Real IfcElectricCapacitanceMeasure; /** */ typedef Step::Real IfcElectricChargeMeasure; /** */ typedef Step::Real IfcElectricConductanceMeasure; /** */ typedef Step::Real IfcElectricCurrentMeasure; /** */ typedef Step::Real IfcElectricResistanceMeasure; /** */ typedef Step::Real IfcElectricVoltageMeasure; /** */ typedef Step::Real IfcEnergyMeasure; /** */ typedef Step::String IfcFontStyle; /** */ typedef Step::String IfcFontVariant; /** */ typedef Step::String IfcFontWeight; /** */ typedef Step::Real IfcForceMeasure; /** */ typedef Step::Real IfcFrequencyMeasure; /** */ typedef Step::String IfcGloballyUniqueId; /** */ typedef Step::Real IfcHeatFluxDensityMeasure; /** */ typedef Step::Real IfcHeatingValueMeasure; /** */ typedef Step::Integer IfcHourInDay; /** */ typedef Step::String IfcIdentifier; /** */ typedef Step::Real IfcIlluminanceMeasure; /** */ typedef Step::Real IfcInductanceMeasure; /** */ typedef Step::Integer IfcInteger; /** */ typedef Step::Integer IfcIntegerCountRateMeasure; /** */ typedef Step::Real IfcIonConcentrationMeasure; /** */ typedef Step::Real IfcIsothermalMoistureCapacityMeasure; /** */ typedef Step::Real IfcKinematicViscosityMeasure; /** */ typedef Step::String IfcLabel; /** */ typedef Step::List< IfcLabel, 1 > List_IfcLabel_1_n; /** */ typedef Step::Real IfcLengthMeasure; /** */ typedef Step::List< IfcLengthMeasure, 1, 3 > List_IfcLengthMeasure_1_3; /** */ typedef Step::List< IfcLengthMeasure, 2, 3 > List_IfcLengthMeasure_2_3; /** */ typedef Step::Real IfcLinearForceMeasure; /** */ typedef Step::Real IfcLinearMomentMeasure; /** */ typedef Step::Real IfcLinearStiffnessMeasure; /** */ typedef Step::Real IfcLinearVelocityMeasure; /** */ typedef Step::Logical IfcLogical; /** */ typedef Step::Real IfcLuminousFluxMeasure; /** */ typedef Step::Real IfcLuminousIntensityDistributionMeasure; /** */ typedef Step::List< IfcLuminousIntensityDistributionMeasure, 1 > List_IfcLuminousIntensityDistributionMeasure_1_n; /** */ typedef Step::Real IfcLuminousIntensityMeasure; /** */ typedef Step::Real IfcMagneticFluxDensityMeasure; /** */ typedef Step::Real IfcMagneticFluxMeasure; /** */ typedef Step::Real IfcMassDensityMeasure; /** */ typedef Step::Real IfcMassFlowRateMeasure; /** */ typedef Step::Real IfcMassMeasure; /** */ typedef Step::Real IfcMassPerLengthMeasure; /** */ typedef Step::Integer IfcMinuteInHour; /** */ typedef Step::Real IfcModulusOfElasticityMeasure; /** */ typedef Step::Real IfcModulusOfLinearSubgradeReactionMeasure; /** */ typedef Step::Real IfcModulusOfRotationalSubgradeReactionMeasure; /** */ typedef Step::Real IfcModulusOfSubgradeReactionMeasure; /** */ typedef Step::Real IfcMoistureDiffusivityMeasure; /** */ typedef Step::Real IfcMolecularWeightMeasure; /** */ typedef Step::Real IfcMomentOfInertiaMeasure; /** */ typedef Step::Real IfcMonetaryMeasure; /** */ typedef Step::Integer IfcMonthInYearNumber; /** */ typedef Step::Real IfcNormalisedRatioMeasure; /** */ typedef Step::Number IfcNumericMeasure; /** */ typedef Step::Real IfcPHMeasure; /** */ typedef Step::Real IfcParameterValue; /** */ typedef Step::List< IfcParameterValue, 2, 2 > List_IfcParameterValue_2_2; /** */ typedef Step::Real IfcPlanarForceMeasure; /** */ typedef Step::Real IfcPlaneAngleMeasure; /** */ typedef Step::List< IfcPlaneAngleMeasure, 1 > List_IfcPlaneAngleMeasure_1_n; /** */ typedef Step::Real IfcPositiveLengthMeasure; /** */ typedef Step::List< IfcPositiveLengthMeasure, 3 > List_IfcPositiveLengthMeasure_3_n; /** */ typedef Step::List< IfcPositiveLengthMeasure, 2 > List_IfcPositiveLengthMeasure_2_n; /** */ typedef Step::Real IfcPositivePlaneAngleMeasure; /** */ typedef Step::Real IfcPositiveRatioMeasure; /** */ typedef Step::Real IfcPowerMeasure; /** */ typedef Step::String IfcPresentableText; /** */ typedef Step::Real IfcPressureMeasure; /** */ typedef Step::Real IfcRadioActivityMeasure; /** */ typedef Step::Real IfcRatioMeasure; /** */ typedef Step::Real IfcReal; /** */ typedef Step::Real IfcRotationalFrequencyMeasure; /** */ typedef Step::Real IfcRotationalMassMeasure; /** */ typedef Step::Real IfcRotationalStiffnessMeasure; /** */ typedef Step::Real IfcSecondInMinute; /** */ typedef Step::Real IfcSectionModulusMeasure; /** */ typedef Step::Real IfcSectionalAreaIntegralMeasure; /** */ typedef Step::Real IfcShearModulusMeasure; /** */ typedef Step::Real IfcSolidAngleMeasure; /** */ typedef Step::Real IfcSoundPowerMeasure; /** */ typedef Step::Real IfcSoundPressureMeasure; /** */ typedef Step::Real IfcSpecificHeatCapacityMeasure; /** */ typedef Step::Real IfcSpecularExponent; /** */ typedef Step::Real IfcSpecularRoughness; /** */ typedef Step::Real IfcTemperatureGradientMeasure; /** */ typedef Step::String IfcText; /** */ typedef Step::List< IfcText, 1 > List_IfcText_1_n; /** */ typedef Step::String IfcTextAlignment; /** */ typedef Step::String IfcTextDecoration; /** */ typedef Step::String IfcTextFontName; /** */ typedef Step::List< IfcTextFontName, 1 > List_IfcTextFontName_1_n; /** */ typedef Step::String IfcTextTransformation; /** */ typedef Step::Real IfcThermalAdmittanceMeasure; /** */ typedef Step::Real IfcThermalConductivityMeasure; /** */ typedef Step::Real IfcThermalExpansionCoefficientMeasure; /** */ typedef Step::Real IfcThermalResistanceMeasure; /** */ typedef Step::Real IfcThermalTransmittanceMeasure; /** */ typedef Step::Real IfcThermodynamicTemperatureMeasure; /** */ typedef Step::Real IfcTimeMeasure; /** */ typedef Step::Integer IfcTimeStamp; /** */ typedef Step::Real IfcTorqueMeasure; /** */ typedef Step::Real IfcVaporPermeabilityMeasure; /** */ typedef Step::Real IfcVolumeMeasure; /** */ typedef Step::Real IfcVolumetricFlowRateMeasure; /** */ typedef Step::Real IfcWarpingConstantMeasure; /** */ typedef Step::Real IfcWarpingMomentMeasure; /** */ typedef Step::Integer IfcYearNumber; /** */ enum IfcActionSourceTypeEnum { IfcActionSourceTypeEnum_UNSET, IfcActionSourceTypeEnum_DEAD_LOAD_G, IfcActionSourceTypeEnum_COMPLETION_G1, IfcActionSourceTypeEnum_LIVE_LOAD_Q, IfcActionSourceTypeEnum_SNOW_S, IfcActionSourceTypeEnum_WIND_W, IfcActionSourceTypeEnum_PRESTRESSING_P, IfcActionSourceTypeEnum_SETTLEMENT_U, IfcActionSourceTypeEnum_TEMPERATURE_T, IfcActionSourceTypeEnum_EARTHQUAKE_E, IfcActionSourceTypeEnum_FIRE, IfcActionSourceTypeEnum_IMPULSE, IfcActionSourceTypeEnum_IMPACT, IfcActionSourceTypeEnum_TRANSPORT, IfcActionSourceTypeEnum_ERECTION, IfcActionSourceTypeEnum_PROPPING, IfcActionSourceTypeEnum_SYSTEM_IMPERFECTION, IfcActionSourceTypeEnum_SHRINKAGE, IfcActionSourceTypeEnum_CREEP, IfcActionSourceTypeEnum_LACK_OF_FIT, IfcActionSourceTypeEnum_BUOYANCY, IfcActionSourceTypeEnum_ICE, IfcActionSourceTypeEnum_CURRENT, IfcActionSourceTypeEnum_WAVE, IfcActionSourceTypeEnum_RAIN, IfcActionSourceTypeEnum_BRAKES, IfcActionSourceTypeEnum_USERDEFINED, IfcActionSourceTypeEnum_NOTDEFINED, }; /** */ enum IfcActionTypeEnum { IfcActionTypeEnum_UNSET, IfcActionTypeEnum_PERMANENT_G, IfcActionTypeEnum_VARIABLE_Q, IfcActionTypeEnum_EXTRAORDINARY_A, IfcActionTypeEnum_USERDEFINED, IfcActionTypeEnum_NOTDEFINED, }; /** */ enum IfcActuatorTypeEnum { IfcActuatorTypeEnum_UNSET, IfcActuatorTypeEnum_ELECTRICACTUATOR, IfcActuatorTypeEnum_HANDOPERATEDACTUATOR, IfcActuatorTypeEnum_HYDRAULICACTUATOR, IfcActuatorTypeEnum_PNEUMATICACTUATOR, IfcActuatorTypeEnum_THERMOSTATICACTUATOR, IfcActuatorTypeEnum_USERDEFINED, IfcActuatorTypeEnum_NOTDEFINED, }; /** */ enum IfcAddressTypeEnum { IfcAddressTypeEnum_UNSET, IfcAddressTypeEnum_OFFICE, IfcAddressTypeEnum_SITE, IfcAddressTypeEnum_HOME, IfcAddressTypeEnum_DISTRIBUTIONPOINT, IfcAddressTypeEnum_USERDEFINED, }; /** */ enum IfcAheadOrBehind { IfcAheadOrBehind_UNSET, IfcAheadOrBehind_AHEAD, IfcAheadOrBehind_BEHIND, }; /** */ enum IfcAirTerminalBoxTypeEnum { IfcAirTerminalBoxTypeEnum_UNSET, IfcAirTerminalBoxTypeEnum_CONSTANTFLOW, IfcAirTerminalBoxTypeEnum_VARIABLEFLOWPRESSUREDEPENDANT, IfcAirTerminalBoxTypeEnum_VARIABLEFLOWPRESSUREINDEPENDANT, IfcAirTerminalBoxTypeEnum_USERDEFINED, IfcAirTerminalBoxTypeEnum_NOTDEFINED, }; /** */ enum IfcAirTerminalTypeEnum { IfcAirTerminalTypeEnum_UNSET, IfcAirTerminalTypeEnum_GRILLE, IfcAirTerminalTypeEnum_REGISTER, IfcAirTerminalTypeEnum_DIFFUSER, IfcAirTerminalTypeEnum_EYEBALL, IfcAirTerminalTypeEnum_IRIS, IfcAirTerminalTypeEnum_LINEARGRILLE, IfcAirTerminalTypeEnum_LINEARDIFFUSER, IfcAirTerminalTypeEnum_USERDEFINED, IfcAirTerminalTypeEnum_NOTDEFINED, }; /** */ enum IfcAirToAirHeatRecoveryTypeEnum { IfcAirToAirHeatRecoveryTypeEnum_UNSET, IfcAirToAirHeatRecoveryTypeEnum_FIXEDPLATECOUNTERFLOWEXCHANGER, IfcAirToAirHeatRecoveryTypeEnum_FIXEDPLATECROSSFLOWEXCHANGER, IfcAirToAirHeatRecoveryTypeEnum_FIXEDPLATEPARALLELFLOWEXCHANGER, IfcAirToAirHeatRecoveryTypeEnum_ROTARYWHEEL, IfcAirToAirHeatRecoveryTypeEnum_RUNAROUNDCOILLOOP, IfcAirToAirHeatRecoveryTypeEnum_HEATPIPE, IfcAirToAirHeatRecoveryTypeEnum_TWINTOWERENTHALPYRECOVERYLOOPS, IfcAirToAirHeatRecoveryTypeEnum_THERMOSIPHONSEALEDTUBEHEATEXCHANGERS, IfcAirToAirHeatRecoveryTypeEnum_THERMOSIPHONCOILTYPEHEATEXCHANGERS, IfcAirToAirHeatRecoveryTypeEnum_USERDEFINED, IfcAirToAirHeatRecoveryTypeEnum_NOTDEFINED, }; /** */ enum IfcAlarmTypeEnum { IfcAlarmTypeEnum_UNSET, IfcAlarmTypeEnum_BELL, IfcAlarmTypeEnum_BREAKGLASSBUTTON, IfcAlarmTypeEnum_LIGHT, IfcAlarmTypeEnum_MANUALPULLBOX, IfcAlarmTypeEnum_SIREN, IfcAlarmTypeEnum_WHISTLE, IfcAlarmTypeEnum_USERDEFINED, IfcAlarmTypeEnum_NOTDEFINED, }; /** */ enum IfcAnalysisModelTypeEnum { IfcAnalysisModelTypeEnum_UNSET, IfcAnalysisModelTypeEnum_IN_PLANE_LOADING_2D, IfcAnalysisModelTypeEnum_OUT_PLANE_LOADING_2D, IfcAnalysisModelTypeEnum_LOADING_3D, IfcAnalysisModelTypeEnum_USERDEFINED, IfcAnalysisModelTypeEnum_NOTDEFINED, }; /** */ enum IfcAnalysisTheoryTypeEnum { IfcAnalysisTheoryTypeEnum_UNSET, IfcAnalysisTheoryTypeEnum_FIRST_ORDER_THEORY, IfcAnalysisTheoryTypeEnum_SECOND_ORDER_THEORY, IfcAnalysisTheoryTypeEnum_THIRD_ORDER_THEORY, IfcAnalysisTheoryTypeEnum_FULL_NONLINEAR_THEORY, IfcAnalysisTheoryTypeEnum_USERDEFINED, IfcAnalysisTheoryTypeEnum_NOTDEFINED, }; /** */ enum IfcArithmeticOperatorEnum { IfcArithmeticOperatorEnum_UNSET, IfcArithmeticOperatorEnum_ADD, IfcArithmeticOperatorEnum_DIVIDE, IfcArithmeticOperatorEnum_MULTIPLY, IfcArithmeticOperatorEnum_SUBTRACT, }; /** */ enum IfcAssemblyPlaceEnum { IfcAssemblyPlaceEnum_UNSET, IfcAssemblyPlaceEnum_SITE, IfcAssemblyPlaceEnum_FACTORY, IfcAssemblyPlaceEnum_NOTDEFINED, }; /** */ enum IfcBSplineCurveForm { IfcBSplineCurveForm_UNSET, IfcBSplineCurveForm_POLYLINE_FORM, IfcBSplineCurveForm_CIRCULAR_ARC, IfcBSplineCurveForm_ELLIPTIC_ARC, IfcBSplineCurveForm_PARABOLIC_ARC, IfcBSplineCurveForm_HYPERBOLIC_ARC, IfcBSplineCurveForm_UNSPECIFIED, }; /** */ enum IfcBeamTypeEnum { IfcBeamTypeEnum_UNSET, IfcBeamTypeEnum_BEAM, IfcBeamTypeEnum_JOIST, IfcBeamTypeEnum_LINTEL, IfcBeamTypeEnum_T_BEAM, IfcBeamTypeEnum_USERDEFINED, IfcBeamTypeEnum_NOTDEFINED, }; /** */ enum IfcBenchmarkEnum { IfcBenchmarkEnum_UNSET, IfcBenchmarkEnum_GREATERTHAN, IfcBenchmarkEnum_GREATERTHANOREQUALTO, IfcBenchmarkEnum_LESSTHAN, IfcBenchmarkEnum_LESSTHANOREQUALTO, IfcBenchmarkEnum_EQUALTO, IfcBenchmarkEnum_NOTEQUALTO, }; /** */ enum IfcBoilerTypeEnum { IfcBoilerTypeEnum_UNSET, IfcBoilerTypeEnum_WATER, IfcBoilerTypeEnum_STEAM, IfcBoilerTypeEnum_USERDEFINED, IfcBoilerTypeEnum_NOTDEFINED, }; /** */ enum IfcBooleanOperator { IfcBooleanOperator_UNSET, IfcBooleanOperator_UNION, IfcBooleanOperator_INTERSECTION, IfcBooleanOperator_DIFFERENCE, }; /** */ enum IfcBuildingElementProxyTypeEnum { IfcBuildingElementProxyTypeEnum_UNSET, IfcBuildingElementProxyTypeEnum_USERDEFINED, IfcBuildingElementProxyTypeEnum_NOTDEFINED, }; /** */ enum IfcCableCarrierFittingTypeEnum { IfcCableCarrierFittingTypeEnum_UNSET, IfcCableCarrierFittingTypeEnum_BEND, IfcCableCarrierFittingTypeEnum_CROSS, IfcCableCarrierFittingTypeEnum_REDUCER, IfcCableCarrierFittingTypeEnum_TEE, IfcCableCarrierFittingTypeEnum_USERDEFINED, IfcCableCarrierFittingTypeEnum_NOTDEFINED, }; /** */ enum IfcCableCarrierSegmentTypeEnum { IfcCableCarrierSegmentTypeEnum_UNSET, IfcCableCarrierSegmentTypeEnum_CABLELADDERSEGMENT, IfcCableCarrierSegmentTypeEnum_CABLETRAYSEGMENT, IfcCableCarrierSegmentTypeEnum_CABLETRUNKINGSEGMENT, IfcCableCarrierSegmentTypeEnum_CONDUITSEGMENT, IfcCableCarrierSegmentTypeEnum_USERDEFINED, IfcCableCarrierSegmentTypeEnum_NOTDEFINED, }; /** */ enum IfcCableSegmentTypeEnum { IfcCableSegmentTypeEnum_UNSET, IfcCableSegmentTypeEnum_CABLESEGMENT, IfcCableSegmentTypeEnum_CONDUCTORSEGMENT, IfcCableSegmentTypeEnum_USERDEFINED, IfcCableSegmentTypeEnum_NOTDEFINED, }; /** */ enum IfcChangeActionEnum { IfcChangeActionEnum_UNSET, IfcChangeActionEnum_NOCHANGE, IfcChangeActionEnum_MODIFIED, IfcChangeActionEnum_ADDED, IfcChangeActionEnum_DELETED, IfcChangeActionEnum_MODIFIEDADDED, IfcChangeActionEnum_MODIFIEDDELETED, }; /** */ enum IfcChillerTypeEnum { IfcChillerTypeEnum_UNSET, IfcChillerTypeEnum_AIRCOOLED, IfcChillerTypeEnum_WATERCOOLED, IfcChillerTypeEnum_HEATRECOVERY, IfcChillerTypeEnum_USERDEFINED, IfcChillerTypeEnum_NOTDEFINED, }; /** */ enum IfcCoilTypeEnum { IfcCoilTypeEnum_UNSET, IfcCoilTypeEnum_DXCOOLINGCOIL, IfcCoilTypeEnum_WATERCOOLINGCOIL, IfcCoilTypeEnum_STEAMHEATINGCOIL, IfcCoilTypeEnum_WATERHEATINGCOIL, IfcCoilTypeEnum_ELECTRICHEATINGCOIL, IfcCoilTypeEnum_GASHEATINGCOIL, IfcCoilTypeEnum_USERDEFINED, IfcCoilTypeEnum_NOTDEFINED, }; /** */ enum IfcColumnTypeEnum { IfcColumnTypeEnum_UNSET, IfcColumnTypeEnum_COLUMN, IfcColumnTypeEnum_USERDEFINED, IfcColumnTypeEnum_NOTDEFINED, }; /** */ enum IfcCompressorTypeEnum { IfcCompressorTypeEnum_UNSET, IfcCompressorTypeEnum_DYNAMIC, IfcCompressorTypeEnum_RECIPROCATING, IfcCompressorTypeEnum_ROTARY, IfcCompressorTypeEnum_SCROLL, IfcCompressorTypeEnum_TROCHOIDAL, IfcCompressorTypeEnum_SINGLESTAGE, IfcCompressorTypeEnum_BOOSTER, IfcCompressorTypeEnum_OPENTYPE, IfcCompressorTypeEnum_HERMETIC, IfcCompressorTypeEnum_SEMIHERMETIC, IfcCompressorTypeEnum_WELDEDSHELLHERMETIC, IfcCompressorTypeEnum_ROLLINGPISTON, IfcCompressorTypeEnum_ROTARYVANE, IfcCompressorTypeEnum_SINGLESCREW, IfcCompressorTypeEnum_TWINSCREW, IfcCompressorTypeEnum_USERDEFINED, IfcCompressorTypeEnum_NOTDEFINED, }; /** */ enum IfcCondenserTypeEnum { IfcCondenserTypeEnum_UNSET, IfcCondenserTypeEnum_WATERCOOLEDSHELLTUBE, IfcCondenserTypeEnum_WATERCOOLEDSHELLCOIL, IfcCondenserTypeEnum_WATERCOOLEDTUBEINTUBE, IfcCondenserTypeEnum_WATERCOOLEDBRAZEDPLATE, IfcCondenserTypeEnum_AIRCOOLED, IfcCondenserTypeEnum_EVAPORATIVECOOLED, IfcCondenserTypeEnum_USERDEFINED, IfcCondenserTypeEnum_NOTDEFINED, }; /** */ enum IfcConnectionTypeEnum { IfcConnectionTypeEnum_UNSET, IfcConnectionTypeEnum_ATPATH, IfcConnectionTypeEnum_ATSTART, IfcConnectionTypeEnum_ATEND, IfcConnectionTypeEnum_NOTDEFINED, }; /** */ enum IfcConstraintEnum { IfcConstraintEnum_UNSET, IfcConstraintEnum_HARD, IfcConstraintEnum_SOFT, IfcConstraintEnum_ADVISORY, IfcConstraintEnum_USERDEFINED, IfcConstraintEnum_NOTDEFINED, }; /** */ enum IfcControllerTypeEnum { IfcControllerTypeEnum_UNSET, IfcControllerTypeEnum_FLOATING, IfcControllerTypeEnum_PROPORTIONAL, IfcControllerTypeEnum_PROPORTIONALINTEGRAL, IfcControllerTypeEnum_PROPORTIONALINTEGRALDERIVATIVE, IfcControllerTypeEnum_TIMEDTWOPOSITION, IfcControllerTypeEnum_TWOPOSITION, IfcControllerTypeEnum_USERDEFINED, IfcControllerTypeEnum_NOTDEFINED, }; /** */ enum IfcCooledBeamTypeEnum { IfcCooledBeamTypeEnum_UNSET, IfcCooledBeamTypeEnum_ACTIVE, IfcCooledBeamTypeEnum_PASSIVE, IfcCooledBeamTypeEnum_USERDEFINED, IfcCooledBeamTypeEnum_NOTDEFINED, }; /** */ enum IfcCoolingTowerTypeEnum { IfcCoolingTowerTypeEnum_UNSET, IfcCoolingTowerTypeEnum_NATURALDRAFT, IfcCoolingTowerTypeEnum_MECHANICALINDUCEDDRAFT, IfcCoolingTowerTypeEnum_MECHANICALFORCEDDRAFT, IfcCoolingTowerTypeEnum_USERDEFINED, IfcCoolingTowerTypeEnum_NOTDEFINED, }; /** */ enum IfcCostScheduleTypeEnum { IfcCostScheduleTypeEnum_UNSET, IfcCostScheduleTypeEnum_BUDGET, IfcCostScheduleTypeEnum_COSTPLAN, IfcCostScheduleTypeEnum_ESTIMATE, IfcCostScheduleTypeEnum_TENDER, IfcCostScheduleTypeEnum_PRICEDBILLOFQUANTITIES, IfcCostScheduleTypeEnum_UNPRICEDBILLOFQUANTITIES, IfcCostScheduleTypeEnum_SCHEDULEOFRATES, IfcCostScheduleTypeEnum_USERDEFINED, IfcCostScheduleTypeEnum_NOTDEFINED, }; /** */ enum IfcCoveringTypeEnum { IfcCoveringTypeEnum_UNSET, IfcCoveringTypeEnum_CEILING, IfcCoveringTypeEnum_FLOORING, IfcCoveringTypeEnum_CLADDING, IfcCoveringTypeEnum_ROOFING, IfcCoveringTypeEnum_INSULATION, IfcCoveringTypeEnum_MEMBRANE, IfcCoveringTypeEnum_SLEEVING, IfcCoveringTypeEnum_WRAPPING, IfcCoveringTypeEnum_USERDEFINED, IfcCoveringTypeEnum_NOTDEFINED, }; /** */ enum IfcCurrencyEnum { IfcCurrencyEnum_UNSET, IfcCurrencyEnum_AED, IfcCurrencyEnum_AES, IfcCurrencyEnum_ATS, IfcCurrencyEnum_AUD, IfcCurrencyEnum_BBD, IfcCurrencyEnum_BEG, IfcCurrencyEnum_BGL, IfcCurrencyEnum_BHD, IfcCurrencyEnum_BMD, IfcCurrencyEnum_BND, IfcCurrencyEnum_BRL, IfcCurrencyEnum_BSD, IfcCurrencyEnum_BWP, IfcCurrencyEnum_BZD, IfcCurrencyEnum_CAD, IfcCurrencyEnum_CBD, IfcCurrencyEnum_CHF, IfcCurrencyEnum_CLP, IfcCurrencyEnum_CNY, IfcCurrencyEnum_CYS, IfcCurrencyEnum_CZK, IfcCurrencyEnum_DDP, IfcCurrencyEnum_DEM, IfcCurrencyEnum_DKK, IfcCurrencyEnum_EGL, IfcCurrencyEnum_EST, IfcCurrencyEnum_EUR, IfcCurrencyEnum_FAK, IfcCurrencyEnum_FIM, IfcCurrencyEnum_FJD, IfcCurrencyEnum_FKP, IfcCurrencyEnum_FRF, IfcCurrencyEnum_GBP, IfcCurrencyEnum_GIP, IfcCurrencyEnum_GMD, IfcCurrencyEnum_GRX, IfcCurrencyEnum_HKD, IfcCurrencyEnum_HUF, IfcCurrencyEnum_ICK, IfcCurrencyEnum_IDR, IfcCurrencyEnum_ILS, IfcCurrencyEnum_INR, IfcCurrencyEnum_IRP, IfcCurrencyEnum_ITL, IfcCurrencyEnum_JMD, IfcCurrencyEnum_JOD, IfcCurrencyEnum_JPY, IfcCurrencyEnum_KES, IfcCurrencyEnum_KRW, IfcCurrencyEnum_KWD, IfcCurrencyEnum_KYD, IfcCurrencyEnum_LKR, IfcCurrencyEnum_LUF, IfcCurrencyEnum_MTL, IfcCurrencyEnum_MUR, IfcCurrencyEnum_MXN, IfcCurrencyEnum_MYR, IfcCurrencyEnum_NLG, IfcCurrencyEnum_NZD, IfcCurrencyEnum_OMR, IfcCurrencyEnum_PGK, IfcCurrencyEnum_PHP, IfcCurrencyEnum_PKR, IfcCurrencyEnum_PLN, IfcCurrencyEnum_PTN, IfcCurrencyEnum_QAR, IfcCurrencyEnum_RUR, IfcCurrencyEnum_SAR, IfcCurrencyEnum_SCR, IfcCurrencyEnum_SEK, IfcCurrencyEnum_SGD, IfcCurrencyEnum_SKP, IfcCurrencyEnum_THB, IfcCurrencyEnum_TRL, IfcCurrencyEnum_TTD, IfcCurrencyEnum_TWD, IfcCurrencyEnum_USD, IfcCurrencyEnum_VEB, IfcCurrencyEnum_VND, IfcCurrencyEnum_XEU, IfcCurrencyEnum_ZAR, IfcCurrencyEnum_ZWD, IfcCurrencyEnum_NOK, }; /** */ enum IfcCurtainWallTypeEnum { IfcCurtainWallTypeEnum_UNSET, IfcCurtainWallTypeEnum_USERDEFINED, IfcCurtainWallTypeEnum_NOTDEFINED, }; /** */ enum IfcDamperTypeEnum { IfcDamperTypeEnum_UNSET, IfcDamperTypeEnum_CONTROLDAMPER, IfcDamperTypeEnum_FIREDAMPER, IfcDamperTypeEnum_SMOKEDAMPER, IfcDamperTypeEnum_FIRESMOKEDAMPER, IfcDamperTypeEnum_BACKDRAFTDAMPER, IfcDamperTypeEnum_RELIEFDAMPER, IfcDamperTypeEnum_BLASTDAMPER, IfcDamperTypeEnum_GRAVITYDAMPER, IfcDamperTypeEnum_GRAVITYRELIEFDAMPER, IfcDamperTypeEnum_BALANCINGDAMPER, IfcDamperTypeEnum_FUMEHOODEXHAUST, IfcDamperTypeEnum_USERDEFINED, IfcDamperTypeEnum_NOTDEFINED, }; /** */ enum IfcDataOriginEnum { IfcDataOriginEnum_UNSET, IfcDataOriginEnum_MEASURED, IfcDataOriginEnum_PREDICTED, IfcDataOriginEnum_SIMULATED, IfcDataOriginEnum_USERDEFINED, IfcDataOriginEnum_NOTDEFINED, }; /** */ enum IfcDerivedUnitEnum { IfcDerivedUnitEnum_UNSET, IfcDerivedUnitEnum_ANGULARVELOCITYUNIT, IfcDerivedUnitEnum_COMPOUNDPLANEANGLEUNIT, IfcDerivedUnitEnum_DYNAMICVISCOSITYUNIT, IfcDerivedUnitEnum_HEATFLUXDENSITYUNIT, IfcDerivedUnitEnum_INTEGERCOUNTRATEUNIT, IfcDerivedUnitEnum_ISOTHERMALMOISTURECAPACITYUNIT, IfcDerivedUnitEnum_KINEMATICVISCOSITYUNIT, IfcDerivedUnitEnum_LINEARVELOCITYUNIT, IfcDerivedUnitEnum_MASSDENSITYUNIT, IfcDerivedUnitEnum_MASSFLOWRATEUNIT, IfcDerivedUnitEnum_MOISTUREDIFFUSIVITYUNIT, IfcDerivedUnitEnum_MOLECULARWEIGHTUNIT, IfcDerivedUnitEnum_SPECIFICHEATCAPACITYUNIT, IfcDerivedUnitEnum_THERMALADMITTANCEUNIT, IfcDerivedUnitEnum_THERMALCONDUCTANCEUNIT, IfcDerivedUnitEnum_THERMALRESISTANCEUNIT, IfcDerivedUnitEnum_THERMALTRANSMITTANCEUNIT, IfcDerivedUnitEnum_VAPORPERMEABILITYUNIT, IfcDerivedUnitEnum_VOLUMETRICFLOWRATEUNIT, IfcDerivedUnitEnum_ROTATIONALFREQUENCYUNIT, IfcDerivedUnitEnum_TORQUEUNIT, IfcDerivedUnitEnum_MOMENTOFINERTIAUNIT, IfcDerivedUnitEnum_LINEARMOMENTUNIT, IfcDerivedUnitEnum_LINEARFORCEUNIT, IfcDerivedUnitEnum_PLANARFORCEUNIT, IfcDerivedUnitEnum_MODULUSOFELASTICITYUNIT, IfcDerivedUnitEnum_SHEARMODULUSUNIT, IfcDerivedUnitEnum_LINEARSTIFFNESSUNIT, IfcDerivedUnitEnum_ROTATIONALSTIFFNESSUNIT, IfcDerivedUnitEnum_MODULUSOFSUBGRADEREACTIONUNIT, IfcDerivedUnitEnum_ACCELERATIONUNIT, IfcDerivedUnitEnum_CURVATUREUNIT, IfcDerivedUnitEnum_HEATINGVALUEUNIT, IfcDerivedUnitEnum_IONCONCENTRATIONUNIT, IfcDerivedUnitEnum_LUMINOUSINTENSITYDISTRIBUTIONUNIT, IfcDerivedUnitEnum_MASSPERLENGTHUNIT, IfcDerivedUnitEnum_MODULUSOFLINEARSUBGRADEREACTIONUNIT, IfcDerivedUnitEnum_MODULUSOFROTATIONALSUBGRADEREACTIONUNIT, IfcDerivedUnitEnum_PHUNIT, IfcDerivedUnitEnum_ROTATIONALMASSUNIT, IfcDerivedUnitEnum_SECTIONAREAINTEGRALUNIT, IfcDerivedUnitEnum_SECTIONMODULUSUNIT, IfcDerivedUnitEnum_SOUNDPOWERUNIT, IfcDerivedUnitEnum_SOUNDPRESSUREUNIT, IfcDerivedUnitEnum_TEMPERATUREGRADIENTUNIT, IfcDerivedUnitEnum_THERMALEXPANSIONCOEFFICIENTUNIT, IfcDerivedUnitEnum_WARPINGCONSTANTUNIT, IfcDerivedUnitEnum_WARPINGMOMENTUNIT, IfcDerivedUnitEnum_USERDEFINED, }; /** */ enum IfcDimensionExtentUsage { IfcDimensionExtentUsage_UNSET, IfcDimensionExtentUsage_ORIGIN, IfcDimensionExtentUsage_TARGET, }; /** */ enum IfcDirectionSenseEnum { IfcDirectionSenseEnum_UNSET, IfcDirectionSenseEnum_POSITIVE, IfcDirectionSenseEnum_NEGATIVE, }; /** */ enum IfcDistributionChamberElementTypeEnum { IfcDistributionChamberElementTypeEnum_UNSET, IfcDistributionChamberElementTypeEnum_FORMEDDUCT, IfcDistributionChamberElementTypeEnum_INSPECTIONCHAMBER, IfcDistributionChamberElementTypeEnum_INSPECTIONPIT, IfcDistributionChamberElementTypeEnum_MANHOLE, IfcDistributionChamberElementTypeEnum_METERCHAMBER, IfcDistributionChamberElementTypeEnum_SUMP, IfcDistributionChamberElementTypeEnum_TRENCH, IfcDistributionChamberElementTypeEnum_VALVECHAMBER, IfcDistributionChamberElementTypeEnum_USERDEFINED, IfcDistributionChamberElementTypeEnum_NOTDEFINED, }; /** */ enum IfcDocumentConfidentialityEnum { IfcDocumentConfidentialityEnum_UNSET, IfcDocumentConfidentialityEnum_PUBLIC, IfcDocumentConfidentialityEnum_RESTRICTED, IfcDocumentConfidentialityEnum_CONFIDENTIAL, IfcDocumentConfidentialityEnum_PERSONAL, IfcDocumentConfidentialityEnum_USERDEFINED, IfcDocumentConfidentialityEnum_NOTDEFINED, }; /** */ enum IfcDocumentStatusEnum { IfcDocumentStatusEnum_UNSET, IfcDocumentStatusEnum_DRAFT, IfcDocumentStatusEnum_FINALDRAFT, IfcDocumentStatusEnum_FINAL, IfcDocumentStatusEnum_REVISION, IfcDocumentStatusEnum_NOTDEFINED, }; /** */ enum IfcDoorPanelOperationEnum { IfcDoorPanelOperationEnum_UNSET, IfcDoorPanelOperationEnum_SWINGING, IfcDoorPanelOperationEnum_DOUBLE_ACTING, IfcDoorPanelOperationEnum_SLIDING, IfcDoorPanelOperationEnum_FOLDING, IfcDoorPanelOperationEnum_REVOLVING, IfcDoorPanelOperationEnum_ROLLINGUP, IfcDoorPanelOperationEnum_USERDEFINED, IfcDoorPanelOperationEnum_NOTDEFINED, }; /** */ enum IfcDoorPanelPositionEnum { IfcDoorPanelPositionEnum_UNSET, IfcDoorPanelPositionEnum_LEFT, IfcDoorPanelPositionEnum_MIDDLE, IfcDoorPanelPositionEnum_RIGHT, IfcDoorPanelPositionEnum_NOTDEFINED, }; /** */ enum IfcDoorStyleConstructionEnum { IfcDoorStyleConstructionEnum_UNSET, IfcDoorStyleConstructionEnum_ALUMINIUM, IfcDoorStyleConstructionEnum_HIGH_GRADE_STEEL, IfcDoorStyleConstructionEnum_STEEL, IfcDoorStyleConstructionEnum_WOOD, IfcDoorStyleConstructionEnum_ALUMINIUM_WOOD, IfcDoorStyleConstructionEnum_ALUMINIUM_PLASTIC, IfcDoorStyleConstructionEnum_PLASTIC, IfcDoorStyleConstructionEnum_USERDEFINED, IfcDoorStyleConstructionEnum_NOTDEFINED, }; /** */ enum IfcDoorStyleOperationEnum { IfcDoorStyleOperationEnum_UNSET, IfcDoorStyleOperationEnum_SINGLE_SWING_LEFT, IfcDoorStyleOperationEnum_SINGLE_SWING_RIGHT, IfcDoorStyleOperationEnum_DOUBLE_DOOR_SINGLE_SWING, IfcDoorStyleOperationEnum_DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_LEFT, IfcDoorStyleOperationEnum_DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_RIGHT, IfcDoorStyleOperationEnum_DOUBLE_SWING_LEFT, IfcDoorStyleOperationEnum_DOUBLE_SWING_RIGHT, IfcDoorStyleOperationEnum_DOUBLE_DOOR_DOUBLE_SWING, IfcDoorStyleOperationEnum_SLIDING_TO_LEFT, IfcDoorStyleOperationEnum_SLIDING_TO_RIGHT, IfcDoorStyleOperationEnum_DOUBLE_DOOR_SLIDING, IfcDoorStyleOperationEnum_FOLDING_TO_LEFT, IfcDoorStyleOperationEnum_FOLDING_TO_RIGHT, IfcDoorStyleOperationEnum_DOUBLE_DOOR_FOLDING, IfcDoorStyleOperationEnum_REVOLVING, IfcDoorStyleOperationEnum_ROLLINGUP, IfcDoorStyleOperationEnum_USERDEFINED, IfcDoorStyleOperationEnum_NOTDEFINED, }; /** */ enum IfcDuctFittingTypeEnum { IfcDuctFittingTypeEnum_UNSET, IfcDuctFittingTypeEnum_BEND, IfcDuctFittingTypeEnum_CONNECTOR, IfcDuctFittingTypeEnum_ENTRY, IfcDuctFittingTypeEnum_EXIT, IfcDuctFittingTypeEnum_JUNCTION, IfcDuctFittingTypeEnum_OBSTRUCTION, IfcDuctFittingTypeEnum_TRANSITION, IfcDuctFittingTypeEnum_USERDEFINED, IfcDuctFittingTypeEnum_NOTDEFINED, }; /** */ enum IfcDuctSegmentTypeEnum { IfcDuctSegmentTypeEnum_UNSET, IfcDuctSegmentTypeEnum_RIGIDSEGMENT, IfcDuctSegmentTypeEnum_FLEXIBLESEGMENT, IfcDuctSegmentTypeEnum_USERDEFINED, IfcDuctSegmentTypeEnum_NOTDEFINED, }; /** */ enum IfcDuctSilencerTypeEnum { IfcDuctSilencerTypeEnum_UNSET, IfcDuctSilencerTypeEnum_FLATOVAL, IfcDuctSilencerTypeEnum_RECTANGULAR, IfcDuctSilencerTypeEnum_ROUND, IfcDuctSilencerTypeEnum_USERDEFINED, IfcDuctSilencerTypeEnum_NOTDEFINED, }; /** */ enum IfcElectricApplianceTypeEnum { IfcElectricApplianceTypeEnum_UNSET, IfcElectricApplianceTypeEnum_COMPUTER, IfcElectricApplianceTypeEnum_DIRECTWATERHEATER, IfcElectricApplianceTypeEnum_DISHWASHER, IfcElectricApplianceTypeEnum_ELECTRICCOOKER, IfcElectricApplianceTypeEnum_ELECTRICHEATER, IfcElectricApplianceTypeEnum_FACSIMILE, IfcElectricApplianceTypeEnum_FREESTANDINGFAN, IfcElectricApplianceTypeEnum_FREEZER, IfcElectricApplianceTypeEnum_FRIDGE_FREEZER, IfcElectricApplianceTypeEnum_HANDDRYER, IfcElectricApplianceTypeEnum_INDIRECTWATERHEATER, IfcElectricApplianceTypeEnum_MICROWAVE, IfcElectricApplianceTypeEnum_PHOTOCOPIER, IfcElectricApplianceTypeEnum_PRINTER, IfcElectricApplianceTypeEnum_REFRIGERATOR, IfcElectricApplianceTypeEnum_RADIANTHEATER, IfcElectricApplianceTypeEnum_SCANNER, IfcElectricApplianceTypeEnum_TELEPHONE, IfcElectricApplianceTypeEnum_TUMBLEDRYER, IfcElectricApplianceTypeEnum_TV, IfcElectricApplianceTypeEnum_VENDINGMACHINE, IfcElectricApplianceTypeEnum_WASHINGMACHINE, IfcElectricApplianceTypeEnum_WATERHEATER, IfcElectricApplianceTypeEnum_WATERCOOLER, IfcElectricApplianceTypeEnum_USERDEFINED, IfcElectricApplianceTypeEnum_NOTDEFINED, }; /** */ enum IfcElectricCurrentEnum { IfcElectricCurrentEnum_UNSET, IfcElectricCurrentEnum_ALTERNATING, IfcElectricCurrentEnum_DIRECT, IfcElectricCurrentEnum_NOTDEFINED, }; /** */ enum IfcElectricDistributionPointFunctionEnum { IfcElectricDistributionPointFunctionEnum_UNSET, IfcElectricDistributionPointFunctionEnum_ALARMPANEL, IfcElectricDistributionPointFunctionEnum_CONSUMERUNIT, IfcElectricDistributionPointFunctionEnum_CONTROLPANEL, IfcElectricDistributionPointFunctionEnum_DISTRIBUTIONBOARD, IfcElectricDistributionPointFunctionEnum_GASDETECTORPANEL, IfcElectricDistributionPointFunctionEnum_INDICATORPANEL, IfcElectricDistributionPointFunctionEnum_MIMICPANEL, IfcElectricDistributionPointFunctionEnum_MOTORCONTROLCENTRE, IfcElectricDistributionPointFunctionEnum_SWITCHBOARD, IfcElectricDistributionPointFunctionEnum_USERDEFINED, IfcElectricDistributionPointFunctionEnum_NOTDEFINED, }; /** */ enum IfcElectricFlowStorageDeviceTypeEnum { IfcElectricFlowStorageDeviceTypeEnum_UNSET, IfcElectricFlowStorageDeviceTypeEnum_BATTERY, IfcElectricFlowStorageDeviceTypeEnum_CAPACITORBANK, IfcElectricFlowStorageDeviceTypeEnum_HARMONICFILTER, IfcElectricFlowStorageDeviceTypeEnum_INDUCTORBANK, IfcElectricFlowStorageDeviceTypeEnum_UPS, IfcElectricFlowStorageDeviceTypeEnum_USERDEFINED, IfcElectricFlowStorageDeviceTypeEnum_NOTDEFINED, }; /** */ enum IfcElectricGeneratorTypeEnum { IfcElectricGeneratorTypeEnum_UNSET, IfcElectricGeneratorTypeEnum_USERDEFINED, IfcElectricGeneratorTypeEnum_NOTDEFINED, }; /** */ enum IfcElectricHeaterTypeEnum { IfcElectricHeaterTypeEnum_UNSET, IfcElectricHeaterTypeEnum_ELECTRICPOINTHEATER, IfcElectricHeaterTypeEnum_ELECTRICCABLEHEATER, IfcElectricHeaterTypeEnum_ELECTRICMATHEATER, IfcElectricHeaterTypeEnum_USERDEFINED, IfcElectricHeaterTypeEnum_NOTDEFINED, }; /** */ enum IfcElectricMotorTypeEnum { IfcElectricMotorTypeEnum_UNSET, IfcElectricMotorTypeEnum_DC, IfcElectricMotorTypeEnum_INDUCTION, IfcElectricMotorTypeEnum_POLYPHASE, IfcElectricMotorTypeEnum_RELUCTANCESYNCHRONOUS, IfcElectricMotorTypeEnum_SYNCHRONOUS, IfcElectricMotorTypeEnum_USERDEFINED, IfcElectricMotorTypeEnum_NOTDEFINED, }; /** */ enum IfcElectricTimeControlTypeEnum { IfcElectricTimeControlTypeEnum_UNSET, IfcElectricTimeControlTypeEnum_TIMECLOCK, IfcElectricTimeControlTypeEnum_TIMEDELAY, IfcElectricTimeControlTypeEnum_RELAY, IfcElectricTimeControlTypeEnum_USERDEFINED, IfcElectricTimeControlTypeEnum_NOTDEFINED, }; /** */ enum IfcElementAssemblyTypeEnum { IfcElementAssemblyTypeEnum_UNSET, IfcElementAssemblyTypeEnum_ACCESSORY_ASSEMBLY, IfcElementAssemblyTypeEnum_ARCH, IfcElementAssemblyTypeEnum_BEAM_GRID, IfcElementAssemblyTypeEnum_BRACED_FRAME, IfcElementAssemblyTypeEnum_GIRDER, IfcElementAssemblyTypeEnum_REINFORCEMENT_UNIT, IfcElementAssemblyTypeEnum_RIGID_FRAME, IfcElementAssemblyTypeEnum_SLAB_FIELD, IfcElementAssemblyTypeEnum_TRUSS, IfcElementAssemblyTypeEnum_USERDEFINED, IfcElementAssemblyTypeEnum_NOTDEFINED, }; /** */ enum IfcElementCompositionEnum { IfcElementCompositionEnum_UNSET, IfcElementCompositionEnum_COMPLEX, IfcElementCompositionEnum_ELEMENT, IfcElementCompositionEnum_PARTIAL, }; /** */ enum IfcEnergySequenceEnum { IfcEnergySequenceEnum_UNSET, IfcEnergySequenceEnum_PRIMARY, IfcEnergySequenceEnum_SECONDARY, IfcEnergySequenceEnum_TERTIARY, IfcEnergySequenceEnum_AUXILIARY, IfcEnergySequenceEnum_USERDEFINED, IfcEnergySequenceEnum_NOTDEFINED, }; /** */ enum IfcEnvironmentalImpactCategoryEnum { IfcEnvironmentalImpactCategoryEnum_UNSET, IfcEnvironmentalImpactCategoryEnum_COMBINEDVALUE, IfcEnvironmentalImpactCategoryEnum_DISPOSAL, IfcEnvironmentalImpactCategoryEnum_EXTRACTION, IfcEnvironmentalImpactCategoryEnum_INSTALLATION, IfcEnvironmentalImpactCategoryEnum_MANUFACTURE, IfcEnvironmentalImpactCategoryEnum_TRANSPORTATION, IfcEnvironmentalImpactCategoryEnum_USERDEFINED, IfcEnvironmentalImpactCategoryEnum_NOTDEFINED, }; /** */ enum IfcEvaporativeCoolerTypeEnum { IfcEvaporativeCoolerTypeEnum_UNSET, IfcEvaporativeCoolerTypeEnum_DIRECTEVAPORATIVERANDOMMEDIAAIRCOOLER, IfcEvaporativeCoolerTypeEnum_DIRECTEVAPORATIVERIGIDMEDIAAIRCOOLER, IfcEvaporativeCoolerTypeEnum_DIRECTEVAPORATIVESLINGERSPACKAGEDAIRCOOLER, IfcEvaporativeCoolerTypeEnum_DIRECTEVAPORATIVEPACKAGEDROTARYAIRCOOLER, IfcEvaporativeCoolerTypeEnum_DIRECTEVAPORATIVEAIRWASHER, IfcEvaporativeCoolerTypeEnum_INDIRECTEVAPORATIVEPACKAGEAIRCOOLER, IfcEvaporativeCoolerTypeEnum_INDIRECTEVAPORATIVEWETCOIL, IfcEvaporativeCoolerTypeEnum_INDIRECTEVAPORATIVECOOLINGTOWERORCOILCOOLER, IfcEvaporativeCoolerTypeEnum_INDIRECTDIRECTCOMBINATION, IfcEvaporativeCoolerTypeEnum_USERDEFINED, IfcEvaporativeCoolerTypeEnum_NOTDEFINED, }; /** */ enum IfcEvaporatorTypeEnum { IfcEvaporatorTypeEnum_UNSET, IfcEvaporatorTypeEnum_DIRECTEXPANSIONSHELLANDTUBE, IfcEvaporatorTypeEnum_DIRECTEXPANSIONTUBEINTUBE, IfcEvaporatorTypeEnum_DIRECTEXPANSIONBRAZEDPLATE, IfcEvaporatorTypeEnum_FLOODEDSHELLANDTUBE, IfcEvaporatorTypeEnum_SHELLANDCOIL, IfcEvaporatorTypeEnum_USERDEFINED, IfcEvaporatorTypeEnum_NOTDEFINED, }; /** */ enum IfcFanTypeEnum { IfcFanTypeEnum_UNSET, IfcFanTypeEnum_CENTRIFUGALFORWARDCURVED, IfcFanTypeEnum_CENTRIFUGALRADIAL, IfcFanTypeEnum_CENTRIFUGALBACKWARDINCLINEDCURVED, IfcFanTypeEnum_CENTRIFUGALAIRFOIL, IfcFanTypeEnum_TUBEAXIAL, IfcFanTypeEnum_VANEAXIAL, IfcFanTypeEnum_PROPELLORAXIAL, IfcFanTypeEnum_USERDEFINED, IfcFanTypeEnum_NOTDEFINED, }; /** */ enum IfcFilterTypeEnum { IfcFilterTypeEnum_UNSET, IfcFilterTypeEnum_AIRPARTICLEFILTER, IfcFilterTypeEnum_ODORFILTER, IfcFilterTypeEnum_OILFILTER, IfcFilterTypeEnum_STRAINER, IfcFilterTypeEnum_WATERFILTER, IfcFilterTypeEnum_USERDEFINED, IfcFilterTypeEnum_NOTDEFINED, }; /** */ enum IfcFireSuppressionTerminalTypeEnum { IfcFireSuppressionTerminalTypeEnum_UNSET, IfcFireSuppressionTerminalTypeEnum_BREECHINGINLET, IfcFireSuppressionTerminalTypeEnum_FIREHYDRANT, IfcFireSuppressionTerminalTypeEnum_HOSEREEL, IfcFireSuppressionTerminalTypeEnum_SPRINKLER, IfcFireSuppressionTerminalTypeEnum_SPRINKLERDEFLECTOR, IfcFireSuppressionTerminalTypeEnum_USERDEFINED, IfcFireSuppressionTerminalTypeEnum_NOTDEFINED, }; /** */ enum IfcFlowDirectionEnum { IfcFlowDirectionEnum_UNSET, IfcFlowDirectionEnum_SOURCE, IfcFlowDirectionEnum_SINK, IfcFlowDirectionEnum_SOURCEANDSINK, IfcFlowDirectionEnum_NOTDEFINED, }; /** */ enum IfcFlowInstrumentTypeEnum { IfcFlowInstrumentTypeEnum_UNSET, IfcFlowInstrumentTypeEnum_PRESSUREGAUGE, IfcFlowInstrumentTypeEnum_THERMOMETER, IfcFlowInstrumentTypeEnum_AMMETER, IfcFlowInstrumentTypeEnum_FREQUENCYMETER, IfcFlowInstrumentTypeEnum_POWERFACTORMETER, IfcFlowInstrumentTypeEnum_PHASEANGLEMETER, IfcFlowInstrumentTypeEnum_VOLTMETER_PEAK, IfcFlowInstrumentTypeEnum_VOLTMETER_RMS, IfcFlowInstrumentTypeEnum_USERDEFINED, IfcFlowInstrumentTypeEnum_NOTDEFINED, }; /** */ enum IfcFlowMeterTypeEnum { IfcFlowMeterTypeEnum_UNSET, IfcFlowMeterTypeEnum_ELECTRICMETER, IfcFlowMeterTypeEnum_ENERGYMETER, IfcFlowMeterTypeEnum_FLOWMETER, IfcFlowMeterTypeEnum_GASMETER, IfcFlowMeterTypeEnum_OILMETER, IfcFlowMeterTypeEnum_WATERMETER, IfcFlowMeterTypeEnum_USERDEFINED, IfcFlowMeterTypeEnum_NOTDEFINED, }; /** */ enum IfcFootingTypeEnum { IfcFootingTypeEnum_UNSET, IfcFootingTypeEnum_FOOTING_BEAM, IfcFootingTypeEnum_PAD_FOOTING, IfcFootingTypeEnum_PILE_CAP, IfcFootingTypeEnum_STRIP_FOOTING, IfcFootingTypeEnum_USERDEFINED, IfcFootingTypeEnum_NOTDEFINED, }; /** */ enum IfcGasTerminalTypeEnum { IfcGasTerminalTypeEnum_UNSET, IfcGasTerminalTypeEnum_GASAPPLIANCE, IfcGasTerminalTypeEnum_GASBOOSTER, IfcGasTerminalTypeEnum_GASBURNER, IfcGasTerminalTypeEnum_USERDEFINED, IfcGasTerminalTypeEnum_NOTDEFINED, }; /** */ enum IfcGeometricProjectionEnum { IfcGeometricProjectionEnum_UNSET, IfcGeometricProjectionEnum_GRAPH_VIEW, IfcGeometricProjectionEnum_SKETCH_VIEW, IfcGeometricProjectionEnum_MODEL_VIEW, IfcGeometricProjectionEnum_PLAN_VIEW, IfcGeometricProjectionEnum_REFLECTED_PLAN_VIEW, IfcGeometricProjectionEnum_SECTION_VIEW, IfcGeometricProjectionEnum_ELEVATION_VIEW, IfcGeometricProjectionEnum_USERDEFINED, IfcGeometricProjectionEnum_NOTDEFINED, }; /** */ enum IfcGlobalOrLocalEnum { IfcGlobalOrLocalEnum_UNSET, IfcGlobalOrLocalEnum_GLOBAL_COORDS, IfcGlobalOrLocalEnum_LOCAL_COORDS, }; /** */ enum IfcHeatExchangerTypeEnum { IfcHeatExchangerTypeEnum_UNSET, IfcHeatExchangerTypeEnum_PLATE, IfcHeatExchangerTypeEnum_SHELLANDTUBE, IfcHeatExchangerTypeEnum_USERDEFINED, IfcHeatExchangerTypeEnum_NOTDEFINED, }; /** */ enum IfcHumidifierTypeEnum { IfcHumidifierTypeEnum_UNSET, IfcHumidifierTypeEnum_STEAMINJECTION, IfcHumidifierTypeEnum_ADIABATICAIRWASHER, IfcHumidifierTypeEnum_ADIABATICPAN, IfcHumidifierTypeEnum_ADIABATICWETTEDELEMENT, IfcHumidifierTypeEnum_ADIABATICATOMIZING, IfcHumidifierTypeEnum_ADIABATICULTRASONIC, IfcHumidifierTypeEnum_ADIABATICRIGIDMEDIA, IfcHumidifierTypeEnum_ADIABATICCOMPRESSEDAIRNOZZLE, IfcHumidifierTypeEnum_ASSISTEDELECTRIC, IfcHumidifierTypeEnum_ASSISTEDNATURALGAS, IfcHumidifierTypeEnum_ASSISTEDPROPANE, IfcHumidifierTypeEnum_ASSISTEDBUTANE, IfcHumidifierTypeEnum_ASSISTEDSTEAM, IfcHumidifierTypeEnum_USERDEFINED, IfcHumidifierTypeEnum_NOTDEFINED, }; /** */ enum IfcInternalOrExternalEnum { IfcInternalOrExternalEnum_UNSET, IfcInternalOrExternalEnum_INTERNAL, IfcInternalOrExternalEnum_EXTERNAL, IfcInternalOrExternalEnum_NOTDEFINED, }; /** */ enum IfcInventoryTypeEnum { IfcInventoryTypeEnum_UNSET, IfcInventoryTypeEnum_ASSETINVENTORY, IfcInventoryTypeEnum_SPACEINVENTORY, IfcInventoryTypeEnum_FURNITUREINVENTORY, IfcInventoryTypeEnum_USERDEFINED, IfcInventoryTypeEnum_NOTDEFINED, }; /** */ enum IfcJunctionBoxTypeEnum { IfcJunctionBoxTypeEnum_UNSET, IfcJunctionBoxTypeEnum_USERDEFINED, IfcJunctionBoxTypeEnum_NOTDEFINED, }; /** */ enum IfcLampTypeEnum { IfcLampTypeEnum_UNSET, IfcLampTypeEnum_COMPACTFLUORESCENT, IfcLampTypeEnum_FLUORESCENT, IfcLampTypeEnum_HIGHPRESSUREMERCURY, IfcLampTypeEnum_HIGHPRESSURESODIUM, IfcLampTypeEnum_METALHALIDE, IfcLampTypeEnum_TUNGSTENFILAMENT, IfcLampTypeEnum_USERDEFINED, IfcLampTypeEnum_NOTDEFINED, }; /** */ enum IfcLayerSetDirectionEnum { IfcLayerSetDirectionEnum_UNSET, IfcLayerSetDirectionEnum_AXIS1, IfcLayerSetDirectionEnum_AXIS2, IfcLayerSetDirectionEnum_AXIS3, }; /** */ enum IfcLightDistributionCurveEnum { IfcLightDistributionCurveEnum_UNSET, IfcLightDistributionCurveEnum_TYPE_A, IfcLightDistributionCurveEnum_TYPE_B, IfcLightDistributionCurveEnum_TYPE_C, IfcLightDistributionCurveEnum_NOTDEFINED, }; /** */ enum IfcLightEmissionSourceEnum { IfcLightEmissionSourceEnum_UNSET, IfcLightEmissionSourceEnum_COMPACTFLUORESCENT, IfcLightEmissionSourceEnum_FLUORESCENT, IfcLightEmissionSourceEnum_HIGHPRESSUREMERCURY, IfcLightEmissionSourceEnum_HIGHPRESSURESODIUM, IfcLightEmissionSourceEnum_LIGHTEMITTINGDIODE, IfcLightEmissionSourceEnum_LOWPRESSURESODIUM, IfcLightEmissionSourceEnum_LOWVOLTAGEHALOGEN, IfcLightEmissionSourceEnum_MAINVOLTAGEHALOGEN, IfcLightEmissionSourceEnum_METALHALIDE, IfcLightEmissionSourceEnum_TUNGSTENFILAMENT, IfcLightEmissionSourceEnum_NOTDEFINED, }; /** */ enum IfcLightFixtureTypeEnum { IfcLightFixtureTypeEnum_UNSET, IfcLightFixtureTypeEnum_POINTSOURCE, IfcLightFixtureTypeEnum_DIRECTIONSOURCE, IfcLightFixtureTypeEnum_USERDEFINED, IfcLightFixtureTypeEnum_NOTDEFINED, }; /** */ enum IfcLoadGroupTypeEnum { IfcLoadGroupTypeEnum_UNSET, IfcLoadGroupTypeEnum_LOAD_GROUP, IfcLoadGroupTypeEnum_LOAD_CASE, IfcLoadGroupTypeEnum_LOAD_COMBINATION_GROUP, IfcLoadGroupTypeEnum_LOAD_COMBINATION, IfcLoadGroupTypeEnum_USERDEFINED, IfcLoadGroupTypeEnum_NOTDEFINED, }; /** */ enum IfcLogicalOperatorEnum { IfcLogicalOperatorEnum_UNSET, IfcLogicalOperatorEnum_LOGICALAND, IfcLogicalOperatorEnum_LOGICALOR, }; /** */ enum IfcMemberTypeEnum { IfcMemberTypeEnum_UNSET, IfcMemberTypeEnum_BRACE, IfcMemberTypeEnum_CHORD, IfcMemberTypeEnum_COLLAR, IfcMemberTypeEnum_MEMBER, IfcMemberTypeEnum_MULLION, IfcMemberTypeEnum_PLATE, IfcMemberTypeEnum_POST, IfcMemberTypeEnum_PURLIN, IfcMemberTypeEnum_RAFTER, IfcMemberTypeEnum_STRINGER, IfcMemberTypeEnum_STRUT, IfcMemberTypeEnum_STUD, IfcMemberTypeEnum_USERDEFINED, IfcMemberTypeEnum_NOTDEFINED, }; /** */ enum IfcMotorConnectionTypeEnum { IfcMotorConnectionTypeEnum_UNSET, IfcMotorConnectionTypeEnum_BELTDRIVE, IfcMotorConnectionTypeEnum_COUPLING, IfcMotorConnectionTypeEnum_DIRECTDRIVE, IfcMotorConnectionTypeEnum_USERDEFINED, IfcMotorConnectionTypeEnum_NOTDEFINED, }; /** */ enum IfcNullStyle { IfcNullStyle_UNSET, IfcNullStyle_NULL, }; /** */ enum IfcObjectTypeEnum { IfcObjectTypeEnum_UNSET, IfcObjectTypeEnum_PRODUCT, IfcObjectTypeEnum_PROCESS, IfcObjectTypeEnum_CONTROL, IfcObjectTypeEnum_RESOURCE, IfcObjectTypeEnum_ACTOR, IfcObjectTypeEnum_GROUP, IfcObjectTypeEnum_PROJECT, IfcObjectTypeEnum_NOTDEFINED, }; /** */ enum IfcObjectiveEnum { IfcObjectiveEnum_UNSET, IfcObjectiveEnum_CODECOMPLIANCE, IfcObjectiveEnum_DESIGNINTENT, IfcObjectiveEnum_HEALTHANDSAFETY, IfcObjectiveEnum_REQUIREMENT, IfcObjectiveEnum_SPECIFICATION, IfcObjectiveEnum_TRIGGERCONDITION, IfcObjectiveEnum_USERDEFINED, IfcObjectiveEnum_NOTDEFINED, }; /** */ enum IfcOccupantTypeEnum { IfcOccupantTypeEnum_UNSET, IfcOccupantTypeEnum_ASSIGNEE, IfcOccupantTypeEnum_ASSIGNOR, IfcOccupantTypeEnum_LESSEE, IfcOccupantTypeEnum_LESSOR, IfcOccupantTypeEnum_LETTINGAGENT, IfcOccupantTypeEnum_OWNER, IfcOccupantTypeEnum_TENANT, IfcOccupantTypeEnum_USERDEFINED, IfcOccupantTypeEnum_NOTDEFINED, }; /** */ enum IfcOutletTypeEnum { IfcOutletTypeEnum_UNSET, IfcOutletTypeEnum_AUDIOVISUALOUTLET, IfcOutletTypeEnum_COMMUNICATIONSOUTLET, IfcOutletTypeEnum_POWEROUTLET, IfcOutletTypeEnum_USERDEFINED, IfcOutletTypeEnum_NOTDEFINED, }; /** */ enum IfcPermeableCoveringOperationEnum { IfcPermeableCoveringOperationEnum_UNSET, IfcPermeableCoveringOperationEnum_GRILL, IfcPermeableCoveringOperationEnum_LOUVER, IfcPermeableCoveringOperationEnum_SCREEN, IfcPermeableCoveringOperationEnum_USERDEFINED, IfcPermeableCoveringOperationEnum_NOTDEFINED, }; /** */ enum IfcPhysicalOrVirtualEnum { IfcPhysicalOrVirtualEnum_UNSET, IfcPhysicalOrVirtualEnum_PHYSICAL, IfcPhysicalOrVirtualEnum_VIRTUAL, IfcPhysicalOrVirtualEnum_NOTDEFINED, }; /** */ enum IfcPileConstructionEnum { IfcPileConstructionEnum_UNSET, IfcPileConstructionEnum_CAST_IN_PLACE, IfcPileConstructionEnum_COMPOSITE, IfcPileConstructionEnum_PRECAST_CONCRETE, IfcPileConstructionEnum_PREFAB_STEEL, IfcPileConstructionEnum_USERDEFINED, IfcPileConstructionEnum_NOTDEFINED, }; /** */ enum IfcPileTypeEnum { IfcPileTypeEnum_UNSET, IfcPileTypeEnum_COHESION, IfcPileTypeEnum_FRICTION, IfcPileTypeEnum_SUPPORT, IfcPileTypeEnum_USERDEFINED, IfcPileTypeEnum_NOTDEFINED, }; /** */ enum IfcPipeFittingTypeEnum { IfcPipeFittingTypeEnum_UNSET, IfcPipeFittingTypeEnum_BEND, IfcPipeFittingTypeEnum_CONNECTOR, IfcPipeFittingTypeEnum_ENTRY, IfcPipeFittingTypeEnum_EXIT, IfcPipeFittingTypeEnum_JUNCTION, IfcPipeFittingTypeEnum_OBSTRUCTION, IfcPipeFittingTypeEnum_TRANSITION, IfcPipeFittingTypeEnum_USERDEFINED, IfcPipeFittingTypeEnum_NOTDEFINED, }; /** */ enum IfcPipeSegmentTypeEnum { IfcPipeSegmentTypeEnum_UNSET, IfcPipeSegmentTypeEnum_FLEXIBLESEGMENT, IfcPipeSegmentTypeEnum_RIGIDSEGMENT, IfcPipeSegmentTypeEnum_GUTTER, IfcPipeSegmentTypeEnum_SPOOL, IfcPipeSegmentTypeEnum_USERDEFINED, IfcPipeSegmentTypeEnum_NOTDEFINED, }; /** */ enum IfcPlateTypeEnum { IfcPlateTypeEnum_UNSET, IfcPlateTypeEnum_CURTAIN_PANEL, IfcPlateTypeEnum_SHEET, IfcPlateTypeEnum_USERDEFINED, IfcPlateTypeEnum_NOTDEFINED, }; /** */ enum IfcProcedureTypeEnum { IfcProcedureTypeEnum_UNSET, IfcProcedureTypeEnum_ADVICE_CAUTION, IfcProcedureTypeEnum_ADVICE_NOTE, IfcProcedureTypeEnum_ADVICE_WARNING, IfcProcedureTypeEnum_CALIBRATION, IfcProcedureTypeEnum_DIAGNOSTIC, IfcProcedureTypeEnum_SHUTDOWN, IfcProcedureTypeEnum_STARTUP, IfcProcedureTypeEnum_USERDEFINED, IfcProcedureTypeEnum_NOTDEFINED, }; /** */ enum IfcProfileTypeEnum { IfcProfileTypeEnum_UNSET, IfcProfileTypeEnum_CURVE, IfcProfileTypeEnum_AREA, }; /** */ enum IfcProjectOrderRecordTypeEnum { IfcProjectOrderRecordTypeEnum_UNSET, IfcProjectOrderRecordTypeEnum_CHANGE, IfcProjectOrderRecordTypeEnum_MAINTENANCE, IfcProjectOrderRecordTypeEnum_MOVE, IfcProjectOrderRecordTypeEnum_PURCHASE, IfcProjectOrderRecordTypeEnum_WORK, IfcProjectOrderRecordTypeEnum_USERDEFINED, IfcProjectOrderRecordTypeEnum_NOTDEFINED, }; /** */ enum IfcProjectOrderTypeEnum { IfcProjectOrderTypeEnum_UNSET, IfcProjectOrderTypeEnum_CHANGEORDER, IfcProjectOrderTypeEnum_MAINTENANCEWORKORDER, IfcProjectOrderTypeEnum_MOVEORDER, IfcProjectOrderTypeEnum_PURCHASEORDER, IfcProjectOrderTypeEnum_WORKORDER, IfcProjectOrderTypeEnum_USERDEFINED, IfcProjectOrderTypeEnum_NOTDEFINED, }; /** */ enum IfcProjectedOrTrueLengthEnum { IfcProjectedOrTrueLengthEnum_UNSET, IfcProjectedOrTrueLengthEnum_PROJECTED_LENGTH, IfcProjectedOrTrueLengthEnum_TRUE_LENGTH, }; /** */ enum IfcPropertySourceEnum { IfcPropertySourceEnum_UNSET, IfcPropertySourceEnum_DESIGN, IfcPropertySourceEnum_DESIGNMAXIMUM, IfcPropertySourceEnum_DESIGNMINIMUM, IfcPropertySourceEnum_SIMULATED, IfcPropertySourceEnum_ASBUILT, IfcPropertySourceEnum_COMMISSIONING, IfcPropertySourceEnum_MEASURED, IfcPropertySourceEnum_USERDEFINED, IfcPropertySourceEnum_NOTKNOWN, }; /** */ enum IfcProtectiveDeviceTypeEnum { IfcProtectiveDeviceTypeEnum_UNSET, IfcProtectiveDeviceTypeEnum_FUSEDISCONNECTOR, IfcProtectiveDeviceTypeEnum_CIRCUITBREAKER, IfcProtectiveDeviceTypeEnum_EARTHFAILUREDEVICE, IfcProtectiveDeviceTypeEnum_RESIDUALCURRENTCIRCUITBREAKER, IfcProtectiveDeviceTypeEnum_RESIDUALCURRENTSWITCH, IfcProtectiveDeviceTypeEnum_VARISTOR, IfcProtectiveDeviceTypeEnum_USERDEFINED, IfcProtectiveDeviceTypeEnum_NOTDEFINED, }; /** */ enum IfcPumpTypeEnum { IfcPumpTypeEnum_UNSET, IfcPumpTypeEnum_CIRCULATOR, IfcPumpTypeEnum_ENDSUCTION, IfcPumpTypeEnum_SPLITCASE, IfcPumpTypeEnum_VERTICALINLINE, IfcPumpTypeEnum_VERTICALTURBINE, IfcPumpTypeEnum_USERDEFINED, IfcPumpTypeEnum_NOTDEFINED, }; /** */ enum IfcRailingTypeEnum { IfcRailingTypeEnum_UNSET, IfcRailingTypeEnum_HANDRAIL, IfcRailingTypeEnum_GUARDRAIL, IfcRailingTypeEnum_BALUSTRADE, IfcRailingTypeEnum_USERDEFINED, IfcRailingTypeEnum_NOTDEFINED, }; /** */ enum IfcRampFlightTypeEnum { IfcRampFlightTypeEnum_UNSET, IfcRampFlightTypeEnum_STRAIGHT, IfcRampFlightTypeEnum_SPIRAL, IfcRampFlightTypeEnum_USERDEFINED, IfcRampFlightTypeEnum_NOTDEFINED, }; /** */ enum IfcRampTypeEnum { IfcRampTypeEnum_UNSET, IfcRampTypeEnum_STRAIGHT_RUN_RAMP, IfcRampTypeEnum_TWO_STRAIGHT_RUN_RAMP, IfcRampTypeEnum_QUARTER_TURN_RAMP, IfcRampTypeEnum_TWO_QUARTER_TURN_RAMP, IfcRampTypeEnum_HALF_TURN_RAMP, IfcRampTypeEnum_SPIRAL_RAMP, IfcRampTypeEnum_USERDEFINED, IfcRampTypeEnum_NOTDEFINED, }; /** */ enum IfcReflectanceMethodEnum { IfcReflectanceMethodEnum_UNSET, IfcReflectanceMethodEnum_BLINN, IfcReflectanceMethodEnum_FLAT, IfcReflectanceMethodEnum_GLASS, IfcReflectanceMethodEnum_MATT, IfcReflectanceMethodEnum_METAL, IfcReflectanceMethodEnum_MIRROR, IfcReflectanceMethodEnum_PHONG, IfcReflectanceMethodEnum_PLASTIC, IfcReflectanceMethodEnum_STRAUSS, IfcReflectanceMethodEnum_NOTDEFINED, }; /** */ enum IfcReinforcingBarRoleEnum { IfcReinforcingBarRoleEnum_UNSET, IfcReinforcingBarRoleEnum_MAIN, IfcReinforcingBarRoleEnum_SHEAR, IfcReinforcingBarRoleEnum_LIGATURE, IfcReinforcingBarRoleEnum_STUD, IfcReinforcingBarRoleEnum_PUNCHING, IfcReinforcingBarRoleEnum_EDGE, IfcReinforcingBarRoleEnum_RING, IfcReinforcingBarRoleEnum_USERDEFINED, IfcReinforcingBarRoleEnum_NOTDEFINED, }; /** */ enum IfcReinforcingBarSurfaceEnum { IfcReinforcingBarSurfaceEnum_UNSET, IfcReinforcingBarSurfaceEnum_PLAIN, IfcReinforcingBarSurfaceEnum_TEXTURED, }; /** */ enum IfcResourceConsumptionEnum { IfcResourceConsumptionEnum_UNSET, IfcResourceConsumptionEnum_CONSUMED, IfcResourceConsumptionEnum_PARTIALLYCONSUMED, IfcResourceConsumptionEnum_NOTCONSUMED, IfcResourceConsumptionEnum_OCCUPIED, IfcResourceConsumptionEnum_PARTIALLYOCCUPIED, IfcResourceConsumptionEnum_NOTOCCUPIED, IfcResourceConsumptionEnum_USERDEFINED, IfcResourceConsumptionEnum_NOTDEFINED, }; /** */ enum IfcRibPlateDirectionEnum { IfcRibPlateDirectionEnum_UNSET, IfcRibPlateDirectionEnum_DIRECTION_X, IfcRibPlateDirectionEnum_DIRECTION_Y, }; /** */ enum IfcRoleEnum { IfcRoleEnum_UNSET, IfcRoleEnum_SUPPLIER, IfcRoleEnum_MANUFACTURER, IfcRoleEnum_CONTRACTOR, IfcRoleEnum_SUBCONTRACTOR, IfcRoleEnum_ARCHITECT, IfcRoleEnum_STRUCTURALENGINEER, IfcRoleEnum_COSTENGINEER, IfcRoleEnum_CLIENT, IfcRoleEnum_BUILDINGOWNER, IfcRoleEnum_BUILDINGOPERATOR, IfcRoleEnum_MECHANICALENGINEER, IfcRoleEnum_ELECTRICALENGINEER, IfcRoleEnum_PROJECTMANAGER, IfcRoleEnum_FACILITIESMANAGER, IfcRoleEnum_CIVILENGINEER, IfcRoleEnum_COMISSIONINGENGINEER, IfcRoleEnum_ENGINEER, IfcRoleEnum_OWNER, IfcRoleEnum_CONSULTANT, IfcRoleEnum_CONSTRUCTIONMANAGER, IfcRoleEnum_FIELDCONSTRUCTIONMANAGER, IfcRoleEnum_RESELLER, IfcRoleEnum_USERDEFINED, }; /** */ enum IfcRoofTypeEnum { IfcRoofTypeEnum_UNSET, IfcRoofTypeEnum_FLAT_ROOF, IfcRoofTypeEnum_SHED_ROOF, IfcRoofTypeEnum_GABLE_ROOF, IfcRoofTypeEnum_HIP_ROOF, IfcRoofTypeEnum_HIPPED_GABLE_ROOF, IfcRoofTypeEnum_GAMBREL_ROOF, IfcRoofTypeEnum_MANSARD_ROOF, IfcRoofTypeEnum_BARREL_ROOF, IfcRoofTypeEnum_RAINBOW_ROOF, IfcRoofTypeEnum_BUTTERFLY_ROOF, IfcRoofTypeEnum_PAVILION_ROOF, IfcRoofTypeEnum_DOME_ROOF, IfcRoofTypeEnum_FREEFORM, IfcRoofTypeEnum_NOTDEFINED, }; /** */ enum IfcSIPrefix { IfcSIPrefix_UNSET, IfcSIPrefix_EXA, IfcSIPrefix_PETA, IfcSIPrefix_TERA, IfcSIPrefix_GIGA, IfcSIPrefix_MEGA, IfcSIPrefix_KILO, IfcSIPrefix_HECTO, IfcSIPrefix_DECA, IfcSIPrefix_DECI, IfcSIPrefix_CENTI, IfcSIPrefix_MILLI, IfcSIPrefix_MICRO, IfcSIPrefix_NANO, IfcSIPrefix_PICO, IfcSIPrefix_FEMTO, IfcSIPrefix_ATTO, }; /** */ enum IfcSIUnitName { IfcSIUnitName_UNSET, IfcSIUnitName_AMPERE, IfcSIUnitName_BECQUEREL, IfcSIUnitName_CANDELA, IfcSIUnitName_COULOMB, IfcSIUnitName_CUBIC_METRE, IfcSIUnitName_DEGREE_CELSIUS, IfcSIUnitName_FARAD, IfcSIUnitName_GRAM, IfcSIUnitName_GRAY, IfcSIUnitName_HENRY, IfcSIUnitName_HERTZ, IfcSIUnitName_JOULE, IfcSIUnitName_KELVIN, IfcSIUnitName_LUMEN, IfcSIUnitName_LUX, IfcSIUnitName_METRE, IfcSIUnitName_MOLE, IfcSIUnitName_NEWTON, IfcSIUnitName_OHM, IfcSIUnitName_PASCAL, IfcSIUnitName_RADIAN, IfcSIUnitName_SECOND, IfcSIUnitName_SIEMENS, IfcSIUnitName_SIEVERT, IfcSIUnitName_SQUARE_METRE, IfcSIUnitName_STERADIAN, IfcSIUnitName_TESLA, IfcSIUnitName_VOLT, IfcSIUnitName_WATT, IfcSIUnitName_WEBER, }; /** */ enum IfcSanitaryTerminalTypeEnum { IfcSanitaryTerminalTypeEnum_UNSET, IfcSanitaryTerminalTypeEnum_BATH, IfcSanitaryTerminalTypeEnum_BIDET, IfcSanitaryTerminalTypeEnum_CISTERN, IfcSanitaryTerminalTypeEnum_SHOWER, IfcSanitaryTerminalTypeEnum_SINK, IfcSanitaryTerminalTypeEnum_SANITARYFOUNTAIN, IfcSanitaryTerminalTypeEnum_TOILETPAN, IfcSanitaryTerminalTypeEnum_URINAL, IfcSanitaryTerminalTypeEnum_WASHHANDBASIN, IfcSanitaryTerminalTypeEnum_WCSEAT, IfcSanitaryTerminalTypeEnum_USERDEFINED, IfcSanitaryTerminalTypeEnum_NOTDEFINED, }; /** */ enum IfcSectionTypeEnum { IfcSectionTypeEnum_UNSET, IfcSectionTypeEnum_UNIFORM, IfcSectionTypeEnum_TAPERED, }; /** */ enum IfcSensorTypeEnum { IfcSensorTypeEnum_UNSET, IfcSensorTypeEnum_CO2SENSOR, IfcSensorTypeEnum_FIRESENSOR, IfcSensorTypeEnum_FLOWSENSOR, IfcSensorTypeEnum_GASSENSOR, IfcSensorTypeEnum_HEATSENSOR, IfcSensorTypeEnum_HUMIDITYSENSOR, IfcSensorTypeEnum_LIGHTSENSOR, IfcSensorTypeEnum_MOISTURESENSOR, IfcSensorTypeEnum_MOVEMENTSENSOR, IfcSensorTypeEnum_PRESSURESENSOR, IfcSensorTypeEnum_SMOKESENSOR, IfcSensorTypeEnum_SOUNDSENSOR, IfcSensorTypeEnum_TEMPERATURESENSOR, IfcSensorTypeEnum_USERDEFINED, IfcSensorTypeEnum_NOTDEFINED, }; /** */ enum IfcSequenceEnum { IfcSequenceEnum_UNSET, IfcSequenceEnum_START_START, IfcSequenceEnum_START_FINISH, IfcSequenceEnum_FINISH_START, IfcSequenceEnum_FINISH_FINISH, IfcSequenceEnum_NOTDEFINED, }; /** */ enum IfcServiceLifeFactorTypeEnum { IfcServiceLifeFactorTypeEnum_UNSET, IfcServiceLifeFactorTypeEnum_A_QUALITYOFCOMPONENTS, IfcServiceLifeFactorTypeEnum_B_DESIGNLEVEL, IfcServiceLifeFactorTypeEnum_C_WORKEXECUTIONLEVEL, IfcServiceLifeFactorTypeEnum_D_INDOORENVIRONMENT, IfcServiceLifeFactorTypeEnum_E_OUTDOORENVIRONMENT, IfcServiceLifeFactorTypeEnum_F_INUSECONDITIONS, IfcServiceLifeFactorTypeEnum_G_MAINTENANCELEVEL, IfcServiceLifeFactorTypeEnum_USERDEFINED, IfcServiceLifeFactorTypeEnum_NOTDEFINED, }; /** */ enum IfcServiceLifeTypeEnum { IfcServiceLifeTypeEnum_UNSET, IfcServiceLifeTypeEnum_ACTUALSERVICELIFE, IfcServiceLifeTypeEnum_EXPECTEDSERVICELIFE, IfcServiceLifeTypeEnum_OPTIMISTICREFERENCESERVICELIFE, IfcServiceLifeTypeEnum_PESSIMISTICREFERENCESERVICELIFE, IfcServiceLifeTypeEnum_REFERENCESERVICELIFE, }; /** */ enum IfcSlabTypeEnum { IfcSlabTypeEnum_UNSET, IfcSlabTypeEnum_FLOOR, IfcSlabTypeEnum_ROOF, IfcSlabTypeEnum_LANDING, IfcSlabTypeEnum_BASESLAB, IfcSlabTypeEnum_USERDEFINED, IfcSlabTypeEnum_NOTDEFINED, }; /** */ enum IfcSoundScaleEnum { IfcSoundScaleEnum_UNSET, IfcSoundScaleEnum_DBA, IfcSoundScaleEnum_DBB, IfcSoundScaleEnum_DBC, IfcSoundScaleEnum_NC, IfcSoundScaleEnum_NR, IfcSoundScaleEnum_USERDEFINED, IfcSoundScaleEnum_NOTDEFINED, }; /** */ enum IfcSpaceHeaterTypeEnum { IfcSpaceHeaterTypeEnum_UNSET, IfcSpaceHeaterTypeEnum_SECTIONALRADIATOR, IfcSpaceHeaterTypeEnum_PANELRADIATOR, IfcSpaceHeaterTypeEnum_TUBULARRADIATOR, IfcSpaceHeaterTypeEnum_CONVECTOR, IfcSpaceHeaterTypeEnum_BASEBOARDHEATER, IfcSpaceHeaterTypeEnum_FINNEDTUBEUNIT, IfcSpaceHeaterTypeEnum_UNITHEATER, IfcSpaceHeaterTypeEnum_USERDEFINED, IfcSpaceHeaterTypeEnum_NOTDEFINED, }; /** */ enum IfcSpaceTypeEnum { IfcSpaceTypeEnum_UNSET, IfcSpaceTypeEnum_USERDEFINED, IfcSpaceTypeEnum_NOTDEFINED, }; /** */ enum IfcStackTerminalTypeEnum { IfcStackTerminalTypeEnum_UNSET, IfcStackTerminalTypeEnum_BIRDCAGE, IfcStackTerminalTypeEnum_COWL, IfcStackTerminalTypeEnum_RAINWATERHOPPER, IfcStackTerminalTypeEnum_USERDEFINED, IfcStackTerminalTypeEnum_NOTDEFINED, }; /** */ enum IfcStairFlightTypeEnum { IfcStairFlightTypeEnum_UNSET, IfcStairFlightTypeEnum_STRAIGHT, IfcStairFlightTypeEnum_WINDER, IfcStairFlightTypeEnum_SPIRAL, IfcStairFlightTypeEnum_CURVED, IfcStairFlightTypeEnum_FREEFORM, IfcStairFlightTypeEnum_USERDEFINED, IfcStairFlightTypeEnum_NOTDEFINED, }; /** */ enum IfcStairTypeEnum { IfcStairTypeEnum_UNSET, IfcStairTypeEnum_STRAIGHT_RUN_STAIR, IfcStairTypeEnum_TWO_STRAIGHT_RUN_STAIR, IfcStairTypeEnum_QUARTER_WINDING_STAIR, IfcStairTypeEnum_QUARTER_TURN_STAIR, IfcStairTypeEnum_HALF_WINDING_STAIR, IfcStairTypeEnum_HALF_TURN_STAIR, IfcStairTypeEnum_TWO_QUARTER_WINDING_STAIR, IfcStairTypeEnum_TWO_QUARTER_TURN_STAIR, IfcStairTypeEnum_THREE_QUARTER_WINDING_STAIR, IfcStairTypeEnum_THREE_QUARTER_TURN_STAIR, IfcStairTypeEnum_SPIRAL_STAIR, IfcStairTypeEnum_DOUBLE_RETURN_STAIR, IfcStairTypeEnum_CURVED_RUN_STAIR, IfcStairTypeEnum_TWO_CURVED_RUN_STAIR, IfcStairTypeEnum_USERDEFINED, IfcStairTypeEnum_NOTDEFINED, }; /** */ enum IfcStateEnum { IfcStateEnum_UNSET, IfcStateEnum_READWRITE, IfcStateEnum_READONLY, IfcStateEnum_LOCKED, IfcStateEnum_READWRITELOCKED, IfcStateEnum_READONLYLOCKED, }; /** */ enum IfcStructuralCurveTypeEnum { IfcStructuralCurveTypeEnum_UNSET, IfcStructuralCurveTypeEnum_RIGID_JOINED_MEMBER, IfcStructuralCurveTypeEnum_PIN_JOINED_MEMBER, IfcStructuralCurveTypeEnum_CABLE, IfcStructuralCurveTypeEnum_TENSION_MEMBER, IfcStructuralCurveTypeEnum_COMPRESSION_MEMBER, IfcStructuralCurveTypeEnum_USERDEFINED, IfcStructuralCurveTypeEnum_NOTDEFINED, }; /** */ enum IfcStructuralSurfaceTypeEnum { IfcStructuralSurfaceTypeEnum_UNSET, IfcStructuralSurfaceTypeEnum_BENDING_ELEMENT, IfcStructuralSurfaceTypeEnum_MEMBRANE_ELEMENT, IfcStructuralSurfaceTypeEnum_SHELL, IfcStructuralSurfaceTypeEnum_USERDEFINED, IfcStructuralSurfaceTypeEnum_NOTDEFINED, }; /** */ enum IfcSurfaceSide { IfcSurfaceSide_UNSET, IfcSurfaceSide_POSITIVE, IfcSurfaceSide_NEGATIVE, IfcSurfaceSide_BOTH, }; /** */ enum IfcSurfaceTextureEnum { IfcSurfaceTextureEnum_UNSET, IfcSurfaceTextureEnum_BUMP, IfcSurfaceTextureEnum_OPACITY, IfcSurfaceTextureEnum_REFLECTION, IfcSurfaceTextureEnum_SELFILLUMINATION, IfcSurfaceTextureEnum_SHININESS, IfcSurfaceTextureEnum_SPECULAR, IfcSurfaceTextureEnum_TEXTURE, IfcSurfaceTextureEnum_TRANSPARENCYMAP, IfcSurfaceTextureEnum_NOTDEFINED, }; /** */ enum IfcSwitchingDeviceTypeEnum { IfcSwitchingDeviceTypeEnum_UNSET, IfcSwitchingDeviceTypeEnum_CONTACTOR, IfcSwitchingDeviceTypeEnum_EMERGENCYSTOP, IfcSwitchingDeviceTypeEnum_STARTER, IfcSwitchingDeviceTypeEnum_SWITCHDISCONNECTOR, IfcSwitchingDeviceTypeEnum_TOGGLESWITCH, IfcSwitchingDeviceTypeEnum_USERDEFINED, IfcSwitchingDeviceTypeEnum_NOTDEFINED, }; /** */ enum IfcTankTypeEnum { IfcTankTypeEnum_UNSET, IfcTankTypeEnum_PREFORMED, IfcTankTypeEnum_SECTIONAL, IfcTankTypeEnum_EXPANSION, IfcTankTypeEnum_PRESSUREVESSEL, IfcTankTypeEnum_USERDEFINED, IfcTankTypeEnum_NOTDEFINED, }; /** */ enum IfcTendonTypeEnum { IfcTendonTypeEnum_UNSET, IfcTendonTypeEnum_STRAND, IfcTendonTypeEnum_WIRE, IfcTendonTypeEnum_BAR, IfcTendonTypeEnum_COATED, IfcTendonTypeEnum_USERDEFINED, IfcTendonTypeEnum_NOTDEFINED, }; /** */ enum IfcTextPath { IfcTextPath_UNSET, IfcTextPath_LEFT, IfcTextPath_RIGHT, IfcTextPath_UP, IfcTextPath_DOWN, }; /** */ enum IfcThermalLoadSourceEnum { IfcThermalLoadSourceEnum_UNSET, IfcThermalLoadSourceEnum_PEOPLE, IfcThermalLoadSourceEnum_LIGHTING, IfcThermalLoadSourceEnum_EQUIPMENT, IfcThermalLoadSourceEnum_VENTILATIONINDOORAIR, IfcThermalLoadSourceEnum_VENTILATIONOUTSIDEAIR, IfcThermalLoadSourceEnum_RECIRCULATEDAIR, IfcThermalLoadSourceEnum_EXHAUSTAIR, IfcThermalLoadSourceEnum_AIREXCHANGERATE, IfcThermalLoadSourceEnum_DRYBULBTEMPERATURE, IfcThermalLoadSourceEnum_RELATIVEHUMIDITY, IfcThermalLoadSourceEnum_INFILTRATION, IfcThermalLoadSourceEnum_USERDEFINED, IfcThermalLoadSourceEnum_NOTDEFINED, }; /** */ enum IfcThermalLoadTypeEnum { IfcThermalLoadTypeEnum_UNSET, IfcThermalLoadTypeEnum_SENSIBLE, IfcThermalLoadTypeEnum_LATENT, IfcThermalLoadTypeEnum_RADIANT, IfcThermalLoadTypeEnum_NOTDEFINED, }; /** */ enum IfcTimeSeriesDataTypeEnum { IfcTimeSeriesDataTypeEnum_UNSET, IfcTimeSeriesDataTypeEnum_CONTINUOUS, IfcTimeSeriesDataTypeEnum_DISCRETE, IfcTimeSeriesDataTypeEnum_DISCRETEBINARY, IfcTimeSeriesDataTypeEnum_PIECEWISEBINARY, IfcTimeSeriesDataTypeEnum_PIECEWISECONSTANT, IfcTimeSeriesDataTypeEnum_PIECEWISECONTINUOUS, IfcTimeSeriesDataTypeEnum_NOTDEFINED, }; /** */ enum IfcTimeSeriesScheduleTypeEnum { IfcTimeSeriesScheduleTypeEnum_UNSET, IfcTimeSeriesScheduleTypeEnum_ANNUAL, IfcTimeSeriesScheduleTypeEnum_MONTHLY, IfcTimeSeriesScheduleTypeEnum_WEEKLY, IfcTimeSeriesScheduleTypeEnum_DAILY, IfcTimeSeriesScheduleTypeEnum_USERDEFINED, IfcTimeSeriesScheduleTypeEnum_NOTDEFINED, }; /** */ enum IfcTransformerTypeEnum { IfcTransformerTypeEnum_UNSET, IfcTransformerTypeEnum_CURRENT, IfcTransformerTypeEnum_FREQUENCY, IfcTransformerTypeEnum_VOLTAGE, IfcTransformerTypeEnum_USERDEFINED, IfcTransformerTypeEnum_NOTDEFINED, }; /** */ enum IfcTransitionCode { IfcTransitionCode_UNSET, IfcTransitionCode_DISCONTINUOUS, IfcTransitionCode_CONTINUOUS, IfcTransitionCode_CONTSAMEGRADIENT, IfcTransitionCode_CONTSAMEGRADIENTSAMECURVATURE, }; /** */ enum IfcTransportElementTypeEnum { IfcTransportElementTypeEnum_UNSET, IfcTransportElementTypeEnum_ELEVATOR, IfcTransportElementTypeEnum_ESCALATOR, IfcTransportElementTypeEnum_MOVINGWALKWAY, IfcTransportElementTypeEnum_USERDEFINED, IfcTransportElementTypeEnum_NOTDEFINED, }; /** */ enum IfcTrimmingPreference { IfcTrimmingPreference_UNSET, IfcTrimmingPreference_CARTESIAN, IfcTrimmingPreference_PARAMETER, IfcTrimmingPreference_UNSPECIFIED, }; /** */ enum IfcTubeBundleTypeEnum { IfcTubeBundleTypeEnum_UNSET, IfcTubeBundleTypeEnum_FINNED, IfcTubeBundleTypeEnum_USERDEFINED, IfcTubeBundleTypeEnum_NOTDEFINED, }; /** */ enum IfcUnitEnum { IfcUnitEnum_UNSET, IfcUnitEnum_ABSORBEDDOSEUNIT, IfcUnitEnum_AMOUNTOFSUBSTANCEUNIT, IfcUnitEnum_AREAUNIT, IfcUnitEnum_DOSEEQUIVALENTUNIT, IfcUnitEnum_ELECTRICCAPACITANCEUNIT, IfcUnitEnum_ELECTRICCHARGEUNIT, IfcUnitEnum_ELECTRICCONDUCTANCEUNIT, IfcUnitEnum_ELECTRICCURRENTUNIT, IfcUnitEnum_ELECTRICRESISTANCEUNIT, IfcUnitEnum_ELECTRICVOLTAGEUNIT, IfcUnitEnum_ENERGYUNIT, IfcUnitEnum_FORCEUNIT, IfcUnitEnum_FREQUENCYUNIT, IfcUnitEnum_ILLUMINANCEUNIT, IfcUnitEnum_INDUCTANCEUNIT, IfcUnitEnum_LENGTHUNIT, IfcUnitEnum_LUMINOUSFLUXUNIT, IfcUnitEnum_LUMINOUSINTENSITYUNIT, IfcUnitEnum_MAGNETICFLUXDENSITYUNIT, IfcUnitEnum_MAGNETICFLUXUNIT, IfcUnitEnum_MASSUNIT, IfcUnitEnum_PLANEANGLEUNIT, IfcUnitEnum_POWERUNIT, IfcUnitEnum_PRESSUREUNIT, IfcUnitEnum_RADIOACTIVITYUNIT, IfcUnitEnum_SOLIDANGLEUNIT, IfcUnitEnum_THERMODYNAMICTEMPERATUREUNIT, IfcUnitEnum_TIMEUNIT, IfcUnitEnum_VOLUMEUNIT, IfcUnitEnum_USERDEFINED, }; /** */ enum IfcUnitaryEquipmentTypeEnum { IfcUnitaryEquipmentTypeEnum_UNSET, IfcUnitaryEquipmentTypeEnum_AIRHANDLER, IfcUnitaryEquipmentTypeEnum_AIRCONDITIONINGUNIT, IfcUnitaryEquipmentTypeEnum_SPLITSYSTEM, IfcUnitaryEquipmentTypeEnum_ROOFTOPUNIT, IfcUnitaryEquipmentTypeEnum_USERDEFINED, IfcUnitaryEquipmentTypeEnum_NOTDEFINED, }; /** */ enum IfcValveTypeEnum { IfcValveTypeEnum_UNSET, IfcValveTypeEnum_AIRRELEASE, IfcValveTypeEnum_ANTIVACUUM, IfcValveTypeEnum_CHANGEOVER, IfcValveTypeEnum_CHECK, IfcValveTypeEnum_COMMISSIONING, IfcValveTypeEnum_DIVERTING, IfcValveTypeEnum_DRAWOFFCOCK, IfcValveTypeEnum_DOUBLECHECK, IfcValveTypeEnum_DOUBLEREGULATING, IfcValveTypeEnum_FAUCET, IfcValveTypeEnum_FLUSHING, IfcValveTypeEnum_GASCOCK, IfcValveTypeEnum_GASTAP, IfcValveTypeEnum_ISOLATING, IfcValveTypeEnum_MIXING, IfcValveTypeEnum_PRESSUREREDUCING, IfcValveTypeEnum_PRESSURERELIEF, IfcValveTypeEnum_REGULATING, IfcValveTypeEnum_SAFETYCUTOFF, IfcValveTypeEnum_STEAMTRAP, IfcValveTypeEnum_STOPCOCK, IfcValveTypeEnum_USERDEFINED, IfcValveTypeEnum_NOTDEFINED, }; /** */ enum IfcVibrationIsolatorTypeEnum { IfcVibrationIsolatorTypeEnum_UNSET, IfcVibrationIsolatorTypeEnum_COMPRESSION, IfcVibrationIsolatorTypeEnum_SPRING, IfcVibrationIsolatorTypeEnum_USERDEFINED, IfcVibrationIsolatorTypeEnum_NOTDEFINED, }; /** */ enum IfcWallTypeEnum { IfcWallTypeEnum_UNSET, IfcWallTypeEnum_STANDARD, IfcWallTypeEnum_POLYGONAL, IfcWallTypeEnum_SHEAR, IfcWallTypeEnum_ELEMENTEDWALL, IfcWallTypeEnum_PLUMBINGWALL, IfcWallTypeEnum_USERDEFINED, IfcWallTypeEnum_NOTDEFINED, }; /** */ enum IfcWasteTerminalTypeEnum { IfcWasteTerminalTypeEnum_UNSET, IfcWasteTerminalTypeEnum_FLOORTRAP, IfcWasteTerminalTypeEnum_FLOORWASTE, IfcWasteTerminalTypeEnum_GULLYSUMP, IfcWasteTerminalTypeEnum_GULLYTRAP, IfcWasteTerminalTypeEnum_GREASEINTERCEPTOR, IfcWasteTerminalTypeEnum_OILINTERCEPTOR, IfcWasteTerminalTypeEnum_PETROLINTERCEPTOR, IfcWasteTerminalTypeEnum_ROOFDRAIN, IfcWasteTerminalTypeEnum_WASTEDISPOSALUNIT, IfcWasteTerminalTypeEnum_WASTETRAP, IfcWasteTerminalTypeEnum_USERDEFINED, IfcWasteTerminalTypeEnum_NOTDEFINED, }; /** */ enum IfcWindowPanelOperationEnum { IfcWindowPanelOperationEnum_UNSET, IfcWindowPanelOperationEnum_SIDEHUNGRIGHTHAND, IfcWindowPanelOperationEnum_SIDEHUNGLEFTHAND, IfcWindowPanelOperationEnum_TILTANDTURNRIGHTHAND, IfcWindowPanelOperationEnum_TILTANDTURNLEFTHAND, IfcWindowPanelOperationEnum_TOPHUNG, IfcWindowPanelOperationEnum_BOTTOMHUNG, IfcWindowPanelOperationEnum_PIVOTHORIZONTAL, IfcWindowPanelOperationEnum_PIVOTVERTICAL, IfcWindowPanelOperationEnum_SLIDINGHORIZONTAL, IfcWindowPanelOperationEnum_SLIDINGVERTICAL, IfcWindowPanelOperationEnum_REMOVABLECASEMENT, IfcWindowPanelOperationEnum_FIXEDCASEMENT, IfcWindowPanelOperationEnum_OTHEROPERATION, IfcWindowPanelOperationEnum_NOTDEFINED, }; /** */ enum IfcWindowPanelPositionEnum { IfcWindowPanelPositionEnum_UNSET, IfcWindowPanelPositionEnum_LEFT, IfcWindowPanelPositionEnum_MIDDLE, IfcWindowPanelPositionEnum_RIGHT, IfcWindowPanelPositionEnum_BOTTOM, IfcWindowPanelPositionEnum_TOP, IfcWindowPanelPositionEnum_NOTDEFINED, }; /** */ enum IfcWindowStyleConstructionEnum { IfcWindowStyleConstructionEnum_UNSET, IfcWindowStyleConstructionEnum_ALUMINIUM, IfcWindowStyleConstructionEnum_HIGH_GRADE_STEEL, IfcWindowStyleConstructionEnum_STEEL, IfcWindowStyleConstructionEnum_WOOD, IfcWindowStyleConstructionEnum_ALUMINIUM_WOOD, IfcWindowStyleConstructionEnum_PLASTIC, IfcWindowStyleConstructionEnum_OTHER_CONSTRUCTION, IfcWindowStyleConstructionEnum_NOTDEFINED, }; /** */ enum IfcWindowStyleOperationEnum { IfcWindowStyleOperationEnum_UNSET, IfcWindowStyleOperationEnum_SINGLE_PANEL, IfcWindowStyleOperationEnum_DOUBLE_PANEL_VERTICAL, IfcWindowStyleOperationEnum_DOUBLE_PANEL_HORIZONTAL, IfcWindowStyleOperationEnum_TRIPLE_PANEL_VERTICAL, IfcWindowStyleOperationEnum_TRIPLE_PANEL_BOTTOM, IfcWindowStyleOperationEnum_TRIPLE_PANEL_TOP, IfcWindowStyleOperationEnum_TRIPLE_PANEL_LEFT, IfcWindowStyleOperationEnum_TRIPLE_PANEL_RIGHT, IfcWindowStyleOperationEnum_TRIPLE_PANEL_HORIZONTAL, IfcWindowStyleOperationEnum_USERDEFINED, IfcWindowStyleOperationEnum_NOTDEFINED, }; /** */ enum IfcWorkControlTypeEnum { IfcWorkControlTypeEnum_UNSET, IfcWorkControlTypeEnum_ACTUAL, IfcWorkControlTypeEnum_BASELINE, IfcWorkControlTypeEnum_PLANNED, IfcWorkControlTypeEnum_USERDEFINED, IfcWorkControlTypeEnum_NOTDEFINED, }; /** */ typedef Step::Set< Step::RefPtr< IfcClassificationNotationFacet >, 1 > Set_IfcClassificationNotationFacet_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcPresentationStyleSelect >, 1 > Set_IfcPresentationStyleSelect_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcVirtualGridIntersection > > Inverse_Set_IfcVirtualGridIntersection_0_n; /** */ typedef Step::List< Step::RefPtr< IfcMaterial >, 1 > List_IfcMaterial_1_n; /** */ typedef Step::List< Step::RefPtr< IfcStructuralLoad >, 1 > List_IfcStructuralLoad_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcStyledItem >, 0, 1 > Inverse_Set_IfcStyledItem_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcPhysicalComplexQuantity >, 0, 1 > Inverse_Set_IfcPhysicalComplexQuantity_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcPresentationStyleSelect > > Set_IfcPresentationStyleSelect_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcElement >, 1 > Set_IfcElement_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcOrganization > > Inverse_Set_IfcOrganization_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsPortToElement > > Inverse_Set_IfcRelConnectsPortToElement_0_n; /** */ typedef Step::List< Step::RefPtr< IfcStructuralLoad >, 2 > List_IfcStructuralLoad_2_n; /** */ typedef Step::Set< Step::ObsPtr< IfcLocalPlacement > > Inverse_Set_IfcLocalPlacement_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsElements > > Inverse_Set_IfcRelConnectsElements_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcReinforcementBarProperties >, 1 > Set_IfcReinforcementBarProperties_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcRepresentationContext >, 1 > Set_IfcRepresentationContext_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcMaterialClassificationRelationship >, 0, 1 > Inverse_Set_IfcMaterialClassificationRelationship_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcTimeSeriesReferenceRelationship >, 0, 1 > Inverse_Set_IfcTimeSeriesReferenceRelationship_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcVertexBasedTextureMap >, 1 > Set_IfcVertexBasedTextureMap_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcDraughtingCalloutRelationship > > Inverse_Set_IfcDraughtingCalloutRelationship_0_n; /** */ typedef Step::List< Step::RefPtr< IfcCurveStyleFontPattern >, 1 > List_IfcCurveStyleFontPattern_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcProduct >, 1, 1 > Inverse_Set_IfcProduct_1_1; /** */ typedef Step::Set< Step::ObsPtr< IfcPropertySet > > Inverse_Set_IfcPropertySet_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcProduct >, 1 > Inverse_Set_IfcProduct_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcPropertySetDefinition >, 1 > Set_IfcPropertySetDefinition_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsStructuralMember >, 1 > Inverse_Set_IfcRelConnectsStructuralMember_1_n; /** */ typedef Step::List< Step::RefPtr< IfcStructuralLoad >, 3 > List_IfcStructuralLoad_3_n; /** */ typedef Step::Array< Step::Real, 1, 2 > Array_Real_1_2; /** */ typedef Array_Real_1_2 IfcComplexNumber; /** */ typedef Step::List< Step::RefPtr< IfcIrregularTimeSeriesValue >, 1 > List_IfcIrregularTimeSeriesValue_1_n; /** */ typedef Step::List< Step::Real, 2 > List_Real_2_n; /** */ typedef Step::Set< Step::ObsPtr< IfcStructuralAnalysisModel >, 0, 1 > Inverse_Set_IfcStructuralAnalysisModel_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcGrid >, 0, 1 > Inverse_Set_IfcGrid_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcDraughtingCalloutElement >, 1 > Set_IfcDraughtingCalloutElement_1_n; /** */ typedef Step::List< Step::RefPtr< IfcShapeModel >, 1 > List_IfcShapeModel_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssignsToActor > > Inverse_Set_IfcRelAssignsToActor_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcGeometricSetSelect >, 1 > Set_IfcGeometricSetSelect_1_n; /** */ typedef Step::List< Step::RefPtr< IfcTableRow >, 1 > List_IfcTableRow_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcDocumentSelect >, 1 > Set_IfcDocumentSelect_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcActorSelect >, 1 > Set_IfcActorSelect_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssignsToControl > > Inverse_Set_IfcRelAssignsToControl_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsStructuralMember > > Inverse_Set_IfcRelConnectsStructuralMember_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcConnectedFaceSet >, 1 > Set_IfcConnectedFaceSet_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcCovering >, 1 > Set_IfcCovering_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelDecomposes > > Inverse_Set_IfcRelDecomposes_0_n; /** */ typedef Step::List< Step::RefPtr< IfcProfileDef >, 2 > List_IfcProfileDef_2_n; /** */ typedef Step::Set< Step::ObsPtr< IfcReferencesValueDocument > > Inverse_Set_IfcReferencesValueDocument_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelInteractionRequirements > > Inverse_Set_IfcRelInteractionRequirements_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcMappedItem > > Inverse_Set_IfcMappedItem_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcProduct >, 1 > Set_IfcProduct_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcConstraintRelationship > > Inverse_Set_IfcConstraintRelationship_0_n; /** */ typedef Step::List< Step::RefPtr< IfcCartesianPoint >, 3 > List_IfcCartesianPoint_3_n; /** */ typedef Step::List< Step::Real, 2, 3 > List_Real_2_3; /** */ typedef Step::Set< Step::ObsPtr< IfcProductRepresentation >, 0, 1 > Inverse_Set_IfcProductRepresentation_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelServicesBuildings >, 0, 1 > Inverse_Set_IfcRelServicesBuildings_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsStructuralActivity > > Inverse_Set_IfcRelConnectsStructuralActivity_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssignsToProcess > > Inverse_Set_IfcRelAssignsToProcess_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcLibraryInformation >, 0, 1 > Inverse_Set_IfcLibraryInformation_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcDocumentReference >, 1 > Set_IfcDocumentReference_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcOrganizationRelationship > > Inverse_Set_IfcOrganizationRelationship_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcApprovalActorRelationship > > Inverse_Set_IfcApprovalActorRelationship_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcClassificationItem >, 1 > Set_IfcClassificationItem_1_n; /** */ typedef Step::List< Step::RefPtr< IfcRepresentation >, 1 > List_IfcRepresentation_1_n; /** */ typedef Step::List< Step::RefPtr< IfcGridAxis >, 1 > List_IfcGridAxis_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcOrganization >, 1 > Set_IfcOrganization_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcRelaxation >, 1 > Set_IfcRelaxation_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelFlowControlElements >, 0, 1 > Inverse_Set_IfcRelFlowControlElements_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcAnnotationSurface >, 1, 1 > Inverse_Set_IfcAnnotationSurface_1_1; /** */ typedef Step::Set< Step::ObsPtr< IfcClassificationItem > > Inverse_Set_IfcClassificationItem_0_n; /** */ typedef Step::List< Step::RefPtr< IfcSectionReinforcementProperties >, 1 > List_IfcSectionReinforcementProperties_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcProfileDef >, 2 > Set_IfcProfileDef_2_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelCoversBldgElements > > Inverse_Set_IfcRelCoversBldgElements_0_n; /** */ typedef Step::List< Step::RefPtr< IfcLightDistributionData >, 1 > List_IfcLightDistributionData_1_n; /** */ typedef Step::List< Step::RefPtr< IfcOrientedEdge >, 1 > List_IfcOrientedEdge_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcCurve > > Set_IfcCurve_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelContainedInSpatialStructure >, 0, 1 > Inverse_Set_IfcRelContainedInSpatialStructure_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcPresentationStyleAssignment >, 1 > Set_IfcPresentationStyleAssignment_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsPorts >, 0, 1 > Inverse_Set_IfcRelConnectsPorts_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelProjectsElement > > Inverse_Set_IfcRelProjectsElement_0_n; /** */ typedef Step::List< Step::Integer, 3, 4 > List_Integer_3_4; /** */ typedef List_Integer_3_4 IfcCompoundPlaneAngleMeasure; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssociates > > Inverse_Set_IfcRelAssociates_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcFillStyleSelect >, 1 > Set_IfcFillStyleSelect_1_n; /** */ typedef Step::Array< Step::RefPtr< IfcCartesianPoint >, 0, 255 > Array_IfcCartesianPoint_0_255; /** */ typedef Step::Set< Step::ObsPtr< IfcClassificationItemRelationship >, 0, 1 > Inverse_Set_IfcClassificationItemRelationship_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelVoidsElement > > Inverse_Set_IfcRelVoidsElement_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcMaterialDefinitionRepresentation >, 0, 1 > Inverse_Set_IfcMaterialDefinitionRepresentation_0_1; /** */ typedef Step::List< Step::RefPtr< IfcAxis2Placement3D >, 2 > List_IfcAxis2Placement3D_2_n; /** */ typedef Step::Set< Step::ObsPtr< IfcDocumentInformation >, 0, 1 > Inverse_Set_IfcDocumentInformation_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcPerson > > Inverse_Set_IfcPerson_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcPropertyConstraintRelationship > > Inverse_Set_IfcPropertyConstraintRelationship_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelDefinesByType >, 0, 1 > Inverse_Set_IfcRelDefinesByType_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelCoversBldgElements >, 0, 1 > Inverse_Set_IfcRelCoversBldgElements_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsWithRealizingElements > > Inverse_Set_IfcRelConnectsWithRealizingElements_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcStructuralResultGroup >, 1 > Set_IfcStructuralResultGroup_1_n; /** */ typedef Step::List< Step::RefPtr< IfcConstraint >, 1 > List_IfcConstraint_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelCoversSpaces > > Inverse_Set_IfcRelCoversSpaces_0_n; /** */ typedef Step::List< Step::RefPtr< IfcSurfaceTexture >, 1 > List_IfcSurfaceTexture_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcConstraintAggregationRelationship > > Inverse_Set_IfcConstraintAggregationRelationship_0_n; /** */ typedef Step::List< Step::Binary< 32 >, 1 > List_32_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRepresentationMap >, 0, 1 > Inverse_Set_IfcRepresentationMap_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcStructuralLoadGroup >, 1 > Set_IfcStructuralLoadGroup_1_n; /** */ typedef Step::List< Step::RefPtr< IfcValue >, 1 > List_IfcValue_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcAppliedValue >, 1 > Set_IfcAppliedValue_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcSpatialStructureElement >, 1 > Set_IfcSpatialStructureElement_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelDefinesByProperties >, 0, 1 > Inverse_Set_IfcRelDefinesByProperties_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcDocumentInformationRelationship > > Inverse_Set_IfcDocumentInformationRelationship_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelDecomposes >, 0, 1 > Inverse_Set_IfcRelDecomposes_0_1; /** */ typedef Step::List< Step::RefPtr< IfcSimpleValue >, 1 > List_IfcSimpleValue_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcUnit >, 1 > Set_IfcUnit_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelDefines > > Inverse_Set_IfcRelDefines_0_n; /** */ typedef Step::Array< Step::Real, 0, 255 > Array_Real_0_255; /** */ typedef Step::List< Step::RefPtr< IfcTextureVertex >, 3 > List_IfcTextureVertex_3_n; /** */ typedef Step::Set< Step::RefPtr< IfcFillAreaStyleTileShapeSelect >, 1 > Set_IfcFillAreaStyleTileShapeSelect_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcSurfaceStyleElementSelect >, 1, 5 > Set_IfcSurfaceStyleElementSelect_1_5; /** */ typedef Step::Set< Step::ObsPtr< IfcTypeObject >, 0, 1 > Inverse_Set_IfcTypeObject_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelSequence > > Inverse_Set_IfcRelSequence_0_n; /** */ typedef Step::List< Step::Integer > List_Integer_0_n; /** */ typedef Step::List< Step::RefPtr< IfcCartesianPoint >, 2 > List_IfcCartesianPoint_2_n; /** */ typedef Step::List< Step::RefPtr< IfcTimeSeriesValue >, 1 > List_IfcTimeSeriesValue_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelContainedInSpatialStructure > > Inverse_Set_IfcRelContainedInSpatialStructure_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcObject >, 1 > Set_IfcObject_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcPropertyDependencyRelationship > > Inverse_Set_IfcPropertyDependencyRelationship_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcClassificationNotationSelect >, 1 > Set_IfcClassificationNotationSelect_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcPhysicalQuantity >, 1 > Set_IfcPhysicalQuantity_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcConstraint >, 1 > Set_IfcConstraint_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcProperty >, 1 > Set_IfcProperty_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelCoversSpaces >, 0, 1 > Inverse_Set_IfcRelCoversSpaces_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcLibraryReference >, 1 > Set_IfcLibraryReference_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcPresentationLayerAssignment > > Inverse_Set_IfcPresentationLayerAssignment_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcStructuralResultGroup >, 0, 1 > Inverse_Set_IfcStructuralResultGroup_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcFaceBound >, 1 > Set_IfcFaceBound_1_n; /** */ typedef Step::List< Step::RefPtr< IfcRelAssignsToProjectOrder >, 1 > List_IfcRelAssignsToProjectOrder_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelReferencedInSpatialStructure > > Inverse_Set_IfcRelReferencedInSpatialStructure_0_n; /** */ typedef Step::List< Step::RefPtr< IfcMaterialLayer >, 1 > List_IfcMaterialLayer_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcPersonAndOrganization > > Inverse_Set_IfcPersonAndOrganization_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcAppliedValueRelationship > > Inverse_Set_IfcAppliedValueRelationship_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcClosedShell >, 1 > Set_IfcClosedShell_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcShapeAspect > > Inverse_Set_IfcShapeAspect_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcDistributionControlElement >, 1 > Set_IfcDistributionControlElement_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcDerivedUnitElement >, 1 > Set_IfcDerivedUnitElement_1_n; /** */ typedef Step::List< Step::RefPtr< IfcSoundValue >, 1, 8 > List_IfcSoundValue_1_8; /** */ typedef Step::Set< Step::ObsPtr< IfcRepresentation > > Inverse_Set_IfcRepresentation_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcObjectDefinition >, 1 > Set_IfcObjectDefinition_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcConstraintClassificationRelationship > > Inverse_Set_IfcConstraintClassificationRelationship_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelConnectsStructuralElement > > Inverse_Set_IfcRelConnectsStructuralElement_0_n; /** */ typedef Step::List< Step::RefPtr< IfcCompositeCurveSegment >, 1 > List_IfcCompositeCurveSegment_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelSpaceBoundary > > Inverse_Set_IfcRelSpaceBoundary_0_n; /** */ typedef Step::List< Step::RefPtr< IfcActorRole >, 1 > List_IfcActorRole_1_n; /** */ typedef Step::List< Step::RefPtr< IfcAddress >, 1 > List_IfcAddress_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcDocumentInformation >, 1 > Set_IfcDocumentInformation_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcCompositeCurve >, 1 > Inverse_Set_IfcCompositeCurve_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcFace >, 1 > Set_IfcFace_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcCurve >, 1 > Set_IfcCurve_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssignsToResource > > Inverse_Set_IfcRelAssignsToResource_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcApprovalRelationship > > Inverse_Set_IfcApprovalRelationship_0_n; /** */ typedef Step::List< Step::RefPtr< IfcRepresentationMap >, 1 > List_IfcRepresentationMap_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcTrimmingSelect >, 1, 2 > Set_IfcTrimmingSelect_1_2; /** */ typedef Step::Set< Step::ObsPtr< IfcRelFillsElement >, 0, 1 > Inverse_Set_IfcRelFillsElement_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcDocumentInformationRelationship >, 0, 1 > Inverse_Set_IfcDocumentInformationRelationship_0_1; /** */ typedef Step::Set< Step::RefPtr< IfcLayeredItem >, 1 > Set_IfcLayeredItem_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcStructuralAnalysisModel > > Inverse_Set_IfcStructuralAnalysisModel_0_n; /** */ typedef Step::List< Step::RefPtr< IfcDirection >, 2, 2 > List_IfcDirection_2_2; /** */ typedef Step::Set< Step::ObsPtr< IfcStructuralAction > > Inverse_Set_IfcStructuralAction_0_n; /** */ typedef Step::List< Step::RefPtr< IfcDirection >, 3, 3 > List_IfcDirection_3_3; /** */ typedef Step::List< Step::RefPtr< IfcGridAxis >, 2, 2 > List_IfcGridAxis_2_2; /** */ typedef Step::Set< Step::RefPtr< IfcRepresentationItem >, 1 > Set_IfcRepresentationItem_1_n; /** */ typedef Step::List< Step::RefPtr< IfcDateTimeSelect >, 1 > List_IfcDateTimeSelect_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcRoot >, 1 > Set_IfcRoot_1_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssignsToProduct > > Inverse_Set_IfcRelAssignsToProduct_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcRelAssigns > > Inverse_Set_IfcRelAssigns_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcTerminatorSymbol >, 0, 2 > Inverse_Set_IfcTerminatorSymbol_0_2; /** */ typedef Step::Set< Step::ObsPtr< IfcRelServicesBuildings > > Inverse_Set_IfcRelServicesBuildings_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcComplexProperty >, 0, 1 > Inverse_Set_IfcComplexProperty_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcGeometricRepresentationSubContext > > Inverse_Set_IfcGeometricRepresentationSubContext_0_n; /** */ typedef Step::Set< Step::ObsPtr< IfcShapeAspect >, 0, 1 > Inverse_Set_IfcShapeAspect_0_1; /** */ typedef Step::Set< Step::ObsPtr< IfcRelFillsElement > > Inverse_Set_IfcRelFillsElement_0_n; /** */ typedef Step::Set< Step::RefPtr< IfcShell >, 1 > Set_IfcShell_1_n; /** */ typedef Step::Set< Step::RefPtr< IfcPerson >, 1 > Set_IfcPerson_1_n; } #endif // IFC2X3_DEFINEDTYPES_H
cstb/ifc2x3-SDK
include/ifc2x3/DefinedTypes.h
C
lgpl-2.1
100,081
/* Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef QGraphicsWebView_h #define QGraphicsWebView_h #include "qwebkitglobal.h" #include "qwebpage.h" #include <QtCore/qurl.h> #include <QtGui/qevent.h> #include <QtGui/qgraphicswidget.h> #include <QtGui/qicon.h> #include <QtGui/qpainter.h> #include <QtNetwork/qnetworkaccessmanager.h> class QWebPage; class QWebHistory; class QWebSettings; class QGraphicsWebViewPrivate; class QWEBKIT_EXPORT QGraphicsWebView : public QGraphicsWidget { Q_OBJECT Q_PROPERTY(QString title READ title NOTIFY titleChanged) Q_PROPERTY(QIcon icon READ icon NOTIFY iconChanged) Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor) Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) Q_PROPERTY(bool modified READ isModified) public: explicit QGraphicsWebView(QGraphicsItem* parent = 0); ~QGraphicsWebView(); QWebPage* page() const; void setPage(QWebPage*); QUrl url() const; void setUrl(const QUrl&); QString title() const; QIcon icon() const; qreal zoomFactor() const; void setZoomFactor(qreal); bool isModified() const; void load(const QUrl &url); void load(const QNetworkRequest& request, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const QByteArray& body = QByteArray()); void setHtml(const QString& html, const QUrl& baseUrl = QUrl()); // FIXME: Consider rename to setHtml? void setContent(const QByteArray& data, const QString& mimeType = QString(), const QUrl& baseUrl = QUrl()); QWebHistory* history() const; QWebSettings* settings() const; QAction* pageAction(QWebPage::WebAction action) const; void triggerPageAction(QWebPage::WebAction action, bool checked = false); bool findText(const QString& subString, QWebPage::FindFlags options = 0); virtual void setGeometry(const QRectF& rect); virtual void updateGeometry(); virtual void paint(QPainter*, const QStyleOptionGraphicsItem* options, QWidget* widget = 0); virtual QVariant itemChange(GraphicsItemChange change, const QVariant& value); virtual bool event(QEvent*); virtual QSizeF sizeHint(Qt::SizeHint which, const QSizeF& constraint) const; virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const; public Q_SLOTS: void stop(); void back(); void forward(); void reload(); Q_SIGNALS: void loadStarted(); void loadFinished(bool); void loadProgress(int progress); void urlChanged(const QUrl&); void titleChanged(const QString&); void iconChanged(); void statusBarMessage(const QString& message); void linkClicked(const QUrl&); protected: virtual void mousePressEvent(QGraphicsSceneMouseEvent*); virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent*); virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent*); virtual void mouseMoveEvent(QGraphicsSceneMouseEvent*); virtual void hoverMoveEvent(QGraphicsSceneHoverEvent*); virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent*); #ifndef QT_NO_WHEELEVENT virtual void wheelEvent(QGraphicsSceneWheelEvent*); #endif virtual void keyPressEvent(QKeyEvent*); virtual void keyReleaseEvent(QKeyEvent*); #ifndef QT_NO_CONTEXTMENU virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent*); #endif virtual void dragEnterEvent(QGraphicsSceneDragDropEvent*); virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent*); virtual void dragMoveEvent(QGraphicsSceneDragDropEvent*); virtual void dropEvent(QGraphicsSceneDragDropEvent*); virtual void focusInEvent(QFocusEvent*); virtual void focusOutEvent(QFocusEvent*); virtual void inputMethodEvent(QInputMethodEvent*); virtual bool focusNextPrevChild(bool next); virtual bool sceneEvent(QEvent*); private: Q_PRIVATE_SLOT(d, void _q_doLoadFinished(bool success)) QGraphicsWebViewPrivate* const d; friend class QGraphicsWebViewPrivate; }; #endif // QGraphicsWebView_h
radekp/qt
src/3rdparty/webkit/WebKit/qt/Api/qgraphicswebview.h
C
lgpl-2.1
4,829
/* libinfinity - a GObject-based infinote implementation * Copyright (C) 2007-2015 Armin Burgmeier <armin@arbur.net> * * 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ /** * SECTION:infinoted-plugin-manager * @title: InfinotedPluginManager * @short_description: Loads and propagates events to infinoted plugins. * @include: infinoted/infinoted-plugin-manager.h * @stability: Unstable * * #InfinotedPluginManager handles the loading of plugins for the infinoted * server. It initializes and deinitializes plugins, and it makes callbacks * when connections or sessions are added or removed. Furthermore, it provides * an interface for plugins to obtain and interact with the server itself, * most notable its #InfdDirectory instance. */ #include <infinoted/infinoted-plugin-manager.h> #include <libinfinity/inf-signals.h> #include <libinfinity/inf-i18n.h> #include <gmodule.h> typedef struct _InfinotedPluginManagerPrivate InfinotedPluginManagerPrivate; struct _InfinotedPluginManagerPrivate { InfdDirectory* directory; InfinotedLog* log; InfCertificateCredentials* credentials; gchar* path; GSList* plugins; GHashTable* connections; /* plugin + connection -> PluginConnectionInfo */ GHashTable* sessions; /* plugin + session -> PluginSessionInfo */ }; typedef struct _InfinotedPluginInstance InfinotedPluginInstance; struct _InfinotedPluginInstance { GModule* module; const InfinotedPlugin* plugin; }; typedef struct _InfinotedPluginManagerForeachConnectionData InfinotedPluginManagerForeachConnectionData; struct _InfinotedPluginManagerForeachConnectionData { InfinotedPluginManager* manager; InfinotedPluginInstance* instance; }; typedef void(*InfinotedPluginManagerWalkDirectoryFunc)( InfinotedPluginManager*, InfinotedPluginInstance*, const InfBrowserIter*, InfSessionProxy*); enum { PROP_0, PROP_DIRECTORY, PROP_LOG, PROP_CREDENTIALS, PROP_PATH }; #define INFINOTED_PLUGIN_MANAGER_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), INFINOTED_TYPE_PLUGIN_MANAGER, InfinotedPluginManagerPrivate)) G_DEFINE_TYPE_WITH_CODE(InfinotedPluginManager, infinoted_plugin_manager, G_TYPE_OBJECT, G_ADD_PRIVATE(InfinotedPluginManager)) static gpointer infinoted_plugin_manager_hash(gpointer first, gpointer second) { /* This function creates a hash out of two pointer values */ /* TODO: Switch to guintptr with glib 2.18 */ gsize hash = 5381; hash = hash * 33 + (gsize)first; hash = hash * 33 + (gsize)second; return (gpointer)hash; } static void infinoted_plugin_manager_add_connection(InfinotedPluginManager* manager, InfinotedPluginInstance* instance, InfXmlConnection* connection) { InfinotedPluginManagerPrivate* priv; gpointer plugin_info; gpointer hash; gpointer connection_info; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); plugin_info = instance+1; hash = infinoted_plugin_manager_hash(plugin_info, connection); g_assert(g_hash_table_lookup(priv->connections, hash) == NULL); if(instance->plugin->connection_info_size > 0) { connection_info = g_slice_alloc(instance->plugin->connection_info_size); g_hash_table_insert(priv->connections, hash, connection_info); } if(instance->plugin->on_connection_added != NULL) { instance->plugin->on_connection_added( connection, plugin_info, connection_info ); } } static void infinoted_plugin_manager_remove_connection(InfinotedPluginManager* manager, InfinotedPluginInstance* instance, InfXmlConnection* connection) { InfinotedPluginManagerPrivate* priv; gpointer plugin_info; gpointer hash; gpointer connection_info; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); plugin_info = instance+1; hash = infinoted_plugin_manager_hash(plugin_info, connection); connection_info = g_hash_table_lookup(priv->connections, hash); g_assert( instance->plugin->connection_info_size == 0 || connection_info != NULL ); if(instance->plugin->on_connection_removed != NULL) { instance->plugin->on_connection_removed( connection, plugin_info, connection_info ); } if(instance->plugin->connection_info_size > 0) { g_hash_table_remove(priv->connections, hash); g_slice_free1(instance->plugin->connection_info_size, connection_info); } } static gboolean infinoted_plugin_manager_check_session_type(InfinotedPluginInstance* instance, InfSessionProxy* proxy) { GType session_type; InfSession* session; gboolean result; if(instance->plugin->session_type == NULL) return TRUE; /* If the type was not registered yet the passed session cannot have the * correct type. */ session_type = g_type_from_name(instance->plugin->session_type); if(session_type == 0) return FALSE; g_object_get(G_OBJECT(proxy), "session", &session, NULL); result = g_type_is_a(G_TYPE_FROM_INSTANCE(session), session_type); g_object_unref(session); return result; } static void infinoted_plugin_manager_add_session(InfinotedPluginManager* manager, InfinotedPluginInstance* instance, const InfBrowserIter* iter, InfSessionProxy* proxy) { InfinotedPluginManagerPrivate* priv; gpointer plugin_info; gpointer hash; gpointer session_info; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); if(infinoted_plugin_manager_check_session_type(instance, proxy)) { plugin_info = instance+1; hash = infinoted_plugin_manager_hash(plugin_info, proxy); g_assert(g_hash_table_lookup(priv->sessions, hash) == NULL); if(instance->plugin->session_info_size > 0) { session_info = g_slice_alloc(instance->plugin->session_info_size); g_hash_table_insert(priv->sessions, hash, session_info); } if(instance->plugin->on_session_added != NULL) { instance->plugin->on_session_added( iter, proxy, plugin_info, session_info ); } } } static void infinoted_plugin_manager_remove_session(InfinotedPluginManager* manager, InfinotedPluginInstance* instance, const InfBrowserIter* iter, InfSessionProxy* proxy) { InfinotedPluginManagerPrivate* priv; gpointer plugin_info; gpointer hash; gpointer session_info; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); if(infinoted_plugin_manager_check_session_type(instance, proxy)) { plugin_info = instance+1; hash = infinoted_plugin_manager_hash(plugin_info, proxy); session_info = g_hash_table_lookup(priv->sessions, hash); g_assert( instance->plugin->session_info_size == 0 || session_info != NULL ); if(instance->plugin->on_session_removed != NULL) { instance->plugin->on_session_removed( iter, proxy, plugin_info, session_info ); } if(instance->plugin->session_info_size > 0) { g_hash_table_remove(priv->sessions, hash); g_slice_free1(instance->plugin->session_info_size, session_info); } } } static void infinoted_plugin_manager_walk_directory( InfinotedPluginManager* manager, const InfBrowserIter* iter, InfinotedPluginInstance* instance, InfinotedPluginManagerWalkDirectoryFunc func) { /* This function walks the whole directory tree recursively and * registers running sessions with the given plugin instance. */ InfinotedPluginManagerPrivate* priv; InfBrowser* browser; InfBrowserIter child; InfSessionProxy* proxy; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); browser = INF_BROWSER(priv->directory); if(inf_browser_is_subdirectory(browser, iter) == TRUE) { if(inf_browser_get_explored(browser, iter) == TRUE) { child = *iter; if(inf_browser_get_child(browser, &child)) { do { infinoted_plugin_manager_walk_directory( manager, &child, instance, func ); } while(inf_browser_get_next(browser, &child)); } } } else { proxy = inf_browser_get_session(browser, iter); if(proxy != NULL) { func(manager, instance, iter, proxy); } } } static void infinoted_plugin_manager_load_plugin_foreach_connection_func( InfXmlConnection* connection, gpointer user_data) { InfinotedPluginManagerForeachConnectionData* data; data = (InfinotedPluginManagerForeachConnectionData*)user_data; infinoted_plugin_manager_add_connection( data->manager, data->instance, connection ); } static void infinoted_plugin_manager_unload_plugin_foreach_connection_func( InfXmlConnection* connection, gpointer user_data) { InfinotedPluginManagerForeachConnectionData* data; data = (InfinotedPluginManagerForeachConnectionData*)user_data; infinoted_plugin_manager_remove_connection( data->manager, data->instance, connection ); } static gboolean infinoted_plugin_manager_load_plugin(InfinotedPluginManager* manager, const gchar* plugin_path, const gchar* plugin_name, GKeyFile* key_file, GError** error) { InfinotedPluginManagerPrivate* priv; gchar* plugin_basename; gchar* plugin_filename; GModule* module; const InfinotedPlugin* plugin; InfinotedPluginInstance* instance; gboolean result; GError* local_error; InfBrowserIter root; InfinotedPluginManagerForeachConnectionData data; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); plugin_basename = g_strdup_printf( "libinfinoted-plugin-%s.%s", plugin_name, G_MODULE_SUFFIX ); plugin_filename = g_build_filename(plugin_path, plugin_basename, NULL); g_free(plugin_basename); module = g_module_open(plugin_filename, G_MODULE_BIND_LOCAL); g_free(plugin_filename); if(module == NULL) { g_set_error_literal( error, infinoted_plugin_manager_error_quark(), INFINOTED_PLUGIN_MANAGER_ERROR_OPEN_FAILED, g_module_error() ); return FALSE; } if(g_module_symbol(module, "INFINOTED_PLUGIN", (gpointer*)&plugin) == FALSE) { g_set_error_literal( error, infinoted_plugin_manager_error_quark(), INFINOTED_PLUGIN_MANAGER_ERROR_NO_ENTRY_POINT, g_module_error() ); g_module_close(module); return FALSE; } instance = g_malloc(sizeof(InfinotedPluginInstance) + plugin->info_size); instance->module = module; instance->plugin = plugin; /* Call on_info_initialize, allowing the plugin to set default values */ if(plugin->on_info_initialize != NULL) plugin->on_info_initialize(instance+1); /* Next, parse options from keyfile */ if(plugin->options != NULL) { local_error = NULL; result = infinoted_parameter_load_from_key_file( plugin->options, key_file, plugin->name, instance+1, &local_error ); if(result == FALSE) { g_free(instance); g_module_close(module); g_propagate_prefixed_error( error, local_error, "Failed to initialize plugin \"%s\": ", plugin_name ); return FALSE; } } /* Finally, call on_initialize, which allows the plugin to initialize * itself with the plugin options. */ if(plugin->on_initialize != NULL) { local_error = NULL; result = plugin->on_initialize(manager, instance+1, &local_error); if(local_error != NULL) { if(instance->plugin->on_deinitialize != NULL) instance->plugin->on_deinitialize(instance+1); g_free(instance); g_module_close(module); g_propagate_prefixed_error( error, local_error, "Failed to initialize plugin \"%s\": ", plugin_name ); return FALSE; } } /* Register initial connections with plugin */ data.manager = manager; data.instance = instance; infd_directory_foreach_connection( priv->directory, infinoted_plugin_manager_load_plugin_foreach_connection_func, &data ); /* Register initial sessions with plugin */ inf_browser_get_root(INF_BROWSER(priv->directory), &root); infinoted_plugin_manager_walk_directory( manager, &root, instance, infinoted_plugin_manager_add_session ); infinoted_log_info( priv->log, _("Loaded plugin \"%s\" from \"%s\""), plugin_name, g_module_name(module) ); priv->plugins = g_slist_prepend(priv->plugins, instance); return TRUE; } static void infinoted_plugin_manager_unload_plugin(InfinotedPluginManager* manager, InfinotedPluginInstance* instance) { InfinotedPluginManagerPrivate* priv; InfinotedPluginManagerForeachConnectionData data; InfBrowserIter root; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); priv->plugins = g_slist_remove(priv->plugins, instance); /* Unregister all sessions with the plugin */ inf_browser_get_root(INF_BROWSER(priv->directory), &root); infinoted_plugin_manager_walk_directory( manager, &root, instance, infinoted_plugin_manager_remove_session ); /* Unregister all connections with the plugin */ data.manager = manager; data.instance = instance; infd_directory_foreach_connection( priv->directory, infinoted_plugin_manager_unload_plugin_foreach_connection_func, &data ); if(instance->plugin->on_deinitialize != NULL) instance->plugin->on_deinitialize(instance+1); infinoted_log_info( priv->log, _("Unloaded plugin \"%s\" from \"%s\""), instance->plugin->name, g_module_name(instance->module) ); g_module_close(instance->module); g_free(instance); } static void infinoted_plugin_manager_connection_added_cb(InfdDirectory* directory, InfXmlConnection* connection, gpointer user_data) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; GSList* item; manager = (InfinotedPluginManager*)user_data; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); for(item = priv->plugins; item != NULL; item = item->next) { infinoted_plugin_manager_add_connection( manager, (InfinotedPluginInstance*)item->data, connection ); } } static void infinoted_plugin_manager_connection_removed_cb(InfdDirectory* directory, InfXmlConnection* connection, gpointer user_data) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; GSList* item; manager = (InfinotedPluginManager*)user_data; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); for(item = priv->plugins; item != NULL; item = item->next) { infinoted_plugin_manager_remove_connection( manager, (InfinotedPluginInstance*)item->data, connection ); } } static void infinoted_plugin_manager_subscribe_session_cb(InfBrowser* browser, const InfBrowserIter* iter, InfSessionProxy* proxy, InfRequest* request, gpointer user_data) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; GSList* item; manager = (InfinotedPluginManager*)user_data; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); for(item = priv->plugins; item != NULL; item = item->next) { infinoted_plugin_manager_add_session( manager, (InfinotedPluginInstance*)item->data, iter, proxy ); } } static void infinoted_plugin_manager_unsubscribe_session_cb(InfBrowser* browser, const InfBrowserIter* iter, InfSessionProxy* proxy, InfRequest* request, gpointer user_data) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; GSList* item; manager = (InfinotedPluginManager*)user_data; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); for(item = priv->plugins; item != NULL; item = item->next) { infinoted_plugin_manager_remove_session( manager, (InfinotedPluginInstance*)item->data, iter, proxy ); } } static void infinoted_plugin_manager_set_directory(InfinotedPluginManager* manager, InfdDirectory* directory) { InfinotedPluginManagerPrivate* priv; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); /* Directory can only be changed while no plugins are loaded. */ g_assert(priv->plugins == NULL); if(priv->directory != NULL) { inf_signal_handlers_disconnect_by_func( G_OBJECT(priv->directory), G_CALLBACK(infinoted_plugin_manager_connection_added_cb), manager ); inf_signal_handlers_disconnect_by_func( G_OBJECT(priv->directory), G_CALLBACK(infinoted_plugin_manager_connection_removed_cb), manager ); inf_signal_handlers_disconnect_by_func( G_OBJECT(priv->directory), G_CALLBACK(infinoted_plugin_manager_subscribe_session_cb), manager ); inf_signal_handlers_disconnect_by_func( G_OBJECT(priv->directory), G_CALLBACK(infinoted_plugin_manager_unsubscribe_session_cb), manager ); g_object_unref(priv->directory); } priv->directory = directory; if(directory != NULL) { g_object_ref(priv->directory); g_signal_connect_after( G_OBJECT(directory), "connection-added", G_CALLBACK(infinoted_plugin_manager_connection_added_cb), manager ); g_signal_connect_after( G_OBJECT(directory), "connection-removed", G_CALLBACK(infinoted_plugin_manager_connection_removed_cb), manager ); g_signal_connect_after( G_OBJECT(directory), "subscribe-session", G_CALLBACK(infinoted_plugin_manager_subscribe_session_cb), manager ); g_signal_connect_after( G_OBJECT(directory), "unsubscribe-session", G_CALLBACK(infinoted_plugin_manager_unsubscribe_session_cb), manager ); } g_object_notify(G_OBJECT(manager), "directory"); } static void infinoted_plugin_manager_init(InfinotedPluginManager* manager) { InfinotedPluginManagerPrivate* priv; priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); priv->directory = NULL; priv->log = NULL; priv->credentials = NULL; priv->path = NULL; priv->plugins = NULL; priv->connections = g_hash_table_new(NULL, NULL); priv->sessions = g_hash_table_new(NULL, NULL); } static void infinoted_plugin_manager_dispose(GObject* object) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; manager = INFINOTED_PLUGIN_MANAGER(object); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); while(priv->plugins != NULL) { infinoted_plugin_manager_unload_plugin( manager, (InfinotedPluginInstance*)priv->plugins->data ); } if(priv->directory != NULL) infinoted_plugin_manager_set_directory(manager, NULL); if(priv->log != NULL) { g_object_unref(priv->log); priv->log = NULL; } if(priv->credentials != NULL) { inf_certificate_credentials_unref(priv->credentials); priv->credentials = NULL; } G_OBJECT_CLASS(infinoted_plugin_manager_parent_class)->dispose(object); } static void infinoted_plugin_manager_finalize(GObject* object) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; manager = INFINOTED_PLUGIN_MANAGER(object); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); g_assert(g_hash_table_size(priv->connections) == 0); g_assert(g_hash_table_size(priv->sessions) == 0); g_hash_table_unref(priv->connections); g_hash_table_unref(priv->sessions); g_free(priv->path); G_OBJECT_CLASS(infinoted_plugin_manager_parent_class)->finalize(object); } static void infinoted_plugin_manager_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; manager = INFINOTED_PLUGIN_MANAGER(object); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); switch(prop_id) { case PROP_DIRECTORY: g_assert(priv->directory == NULL); /* construct only */ infinoted_plugin_manager_set_directory( manager, INFD_DIRECTORY(g_value_get_object(value)) ); break; case PROP_LOG: g_assert(priv->log == NULL); /* construct only */ priv->log = INFINOTED_LOG(g_value_dup_object(value)); break; case PROP_CREDENTIALS: g_assert(priv->credentials == NULL); /* construct only */ priv->credentials = (InfCertificateCredentials*)g_value_dup_boxed(value); break; case PROP_PATH: /* read only */ default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void infinoted_plugin_manager_get_property(GObject* object, guint prop_id, GValue* value, GParamSpec* pspec) { InfinotedPluginManager* manager; InfinotedPluginManagerPrivate* priv; manager = INFINOTED_PLUGIN_MANAGER(object); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); switch(prop_id) { case PROP_DIRECTORY: g_value_set_object(value, priv->directory); break; case PROP_LOG: g_value_set_object(value, priv->log); break; case PROP_CREDENTIALS: g_value_set_boxed(value, priv->credentials); break; case PROP_PATH: g_value_set_string(value, priv->path); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void infinoted_plugin_manager_class_init( InfinotedPluginManagerClass* manager_class) { GObjectClass* object_class; object_class = G_OBJECT_CLASS(manager_class); object_class->dispose = infinoted_plugin_manager_dispose; object_class->finalize = infinoted_plugin_manager_finalize; object_class->set_property = infinoted_plugin_manager_set_property; object_class->get_property = infinoted_plugin_manager_get_property; g_object_class_install_property( object_class, PROP_DIRECTORY, g_param_spec_object( "directory", "Directory", "The infinote directory served by the server", INFD_TYPE_DIRECTORY, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY ) ); g_object_class_install_property( object_class, PROP_LOG, g_param_spec_object( "log", "Log", "The log object into which to write log messages", INFINOTED_TYPE_LOG, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY ) ); g_object_class_install_property( object_class, PROP_CREDENTIALS, g_param_spec_boxed( "credentials", "Credentials", "The server's TLS credentials", INF_TYPE_CERTIFICATE_CREDENTIALS, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY ) ); g_object_class_install_property( object_class, PROP_PATH, g_param_spec_string( "path", "Path", "The path from which plugins are loaded", NULL, G_PARAM_READABLE ) ); } /** * infinoted_plugin_manager_new: (constructor) * @directory: The #InfdDirectory on which plugins should operate. * @log: The #InfinotedLog to write log messages to. * @creds: (allow-none): The #InfCertificateCredentials used to secure data * transfer with the clients, or %NULL. * * Creates a new #InfinotedPluginManager with the given directory, log * and credentials. These three objects will be available for plugins * to enhance the infinoted functionality. Plugins can be loaded * with infinoted_plugin_manager_load(). * * Returns: (transfer full): A new #InfinotedPluginManager. */ InfinotedPluginManager* infinoted_plugin_manager_new(InfdDirectory* directory, InfinotedLog* log, InfCertificateCredentials* creds) { GObject* object; g_return_val_if_fail(INFD_IS_DIRECTORY(directory), NULL); g_return_val_if_fail(INFINOTED_IS_LOG(log), NULL); object = g_object_new( INFINOTED_TYPE_PLUGIN_MANAGER, "directory", directory, "log", log, "credentials", creds, NULL ); return INFINOTED_PLUGIN_MANAGER(object); } /** * infinoted_plugin_manager_load: * @manager: A #InfinotedPluginManager. * @plugin_path: The path from which to load plugins. * @plugins: (array zero-terminated=1) (allow-none): A list of plugins to * load, or %NULL. * @options: A #GKeyFile with configuration options for the plugins. * @error: Location to store error information, if any, or %NULL. * * Loads all plugins specified in @plugins from the location at @plugin_path. * If loading one of the module fails the function sets @error and returns * %FALSE, and the object ends up with no plugins loaded. If @plugins is * %NULL, no plugins are loaded. * * If this function is called while there are already plugins loaded, all * existing plugins are unloaded first. * * Returns: %TRUE on success or %FALSE on error. */ gboolean infinoted_plugin_manager_load(InfinotedPluginManager* manager, const gchar* plugin_path, const gchar* const* plugins, GKeyFile* options, GError** error) { InfinotedPluginManagerPrivate* priv; const gchar* const* plugin; gboolean result; g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(manager), FALSE); g_return_val_if_fail(plugin_path != NULL, FALSE); g_return_val_if_fail(options != NULL, FALSE); g_return_val_if_fail(error == NULL || *error == NULL, FALSE); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); /* Unload existing plugins */ g_free(priv->path); while(priv->plugins != NULL) { infinoted_plugin_manager_unload_plugin( manager, (InfinotedPluginInstance*)priv->plugins->data ); } /* Load new plugins */ priv->path = g_strdup(plugin_path); if(plugins != NULL) { for(plugin = plugins; *plugin != NULL; ++plugin) { result = infinoted_plugin_manager_load_plugin( manager, plugin_path, *plugin, options, error ); if(result == FALSE) { while(priv->plugins != NULL) { infinoted_plugin_manager_unload_plugin( manager, (InfinotedPluginInstance*)priv->plugins->data ); } return FALSE; } } } return TRUE; } /** * infinoted_plugin_manager_get_directory: * @manager: A #InfinotedPluginManager. * * Returns the #InfdDirectory used by the plugin manager. * * Returns: (transfer none): A #InfdDirectory owned by the plugin manager. */ InfdDirectory* infinoted_plugin_manager_get_directory(InfinotedPluginManager* manager) { g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(manager), NULL); return INFINOTED_PLUGIN_MANAGER_PRIVATE(manager)->directory; } /** * infinoted_plugin_manager_get_io: * @manager: A #InfinotedPluginManager. * * Returns the #InfIo of the #InfdDirectory used by the plugin manager. * * Returns: (transfer none): A #InfIo owned by the plugin manager. */ InfIo* infinoted_plugin_manager_get_io(InfinotedPluginManager* manager) { InfinotedPluginManagerPrivate* priv; g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(manager), NULL); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(manager); return infd_directory_get_io(priv->directory); } /** * infinoted_plugin_manager_get_log: * @manager: A #InfinotedPluginManager. * * Returns the #InfinotedLog that the plugin manager and the plugins do * write log messages to. * * Returns: (transfer none): A #InfinotedLog owned by the plugin manager. */ InfinotedLog* infinoted_plugin_manager_get_log(InfinotedPluginManager* manager) { g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(manager), NULL); return INFINOTED_PLUGIN_MANAGER_PRIVATE(manager)->log; } /** * infinoted_plugin_manager_get_credentials: * @manager: A #InfinotedPluginManager. * * Returns the #InfCertificateCredentials used for securing the data transfer * with all clients. * * Returns: (transfer none): A #InfCertificateCredentials object owned by the * plugin manager. */ InfCertificateCredentials* infinoted_plugin_manager_get_credentials(InfinotedPluginManager* manager) { g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(manager), NULL); return INFINOTED_PLUGIN_MANAGER_PRIVATE(manager)->credentials; } /** * infinoted_plugin_manager_error_quark: * * Returns the #GQuark for errors from the InfinotedPluginManager module. * * Returns: The error domain for the InfinotedPluginManager module. */ GQuark infinoted_plugin_manager_error_quark(void) { return g_quark_from_static_string("INFINOTED_PLUGIN_MANAGER_ERROR"); } /** * infinoted_plugin_manager_get_connection_info: * @mgr: A #InfinotedPluginManager. * @plugin_info: The @plugin_info pointer of a plugin instance. * @connection: The #InfXmlConnection for which to retrieve plugin data. * * Queries the connection-specfic plugin data for the plugin instance * @plugin_info. Returns %NULL if no such object exists, i.e. when the * plugin's @connection_info_size is set to 0. * * Returns: (transfer none) (allow-none): A pointer to the connection-specific * plugin data, or %NULL. */ gpointer infinoted_plugin_manager_get_connection_info(InfinotedPluginManager* mgr, gpointer plugin_info, InfXmlConnection* connection) { InfinotedPluginManagerPrivate* priv; g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(mgr), NULL); g_return_val_if_fail(INF_IS_XML_CONNECTION(connection), NULL); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(mgr); return g_hash_table_lookup( priv->connections, infinoted_plugin_manager_hash(plugin_info, connection) ); } /** * infinoted_plugin_manager_get_session_info: * @mgr: A #InfinotedPluginManager. * @plugin_info: The @plugin_info pointer of a plugin instance. * @proxy: The #InfSessionProxy for which to retrieve plugin data. * * Queries the session-specfic plugin data for the plugin instance * @plugin_info. Returns %NULL if no such object exists, i.e. when the * plugin's @session_info_size is set to 0. * * Returns: (transfer none) (allow-none): A pointer to the session-specific * plugin data, or %NULL. */ gpointer infinoted_plugin_manager_get_session_info(InfinotedPluginManager* mgr, gpointer plugin_info, InfSessionProxy* proxy) { InfinotedPluginManagerPrivate* priv; g_return_val_if_fail(INFINOTED_IS_PLUGIN_MANAGER(mgr), NULL); g_return_val_if_fail(INF_IS_SESSION_PROXY(proxy), NULL); priv = INFINOTED_PLUGIN_MANAGER_PRIVATE(mgr); return g_hash_table_lookup( priv->sessions, infinoted_plugin_manager_hash(plugin_info, proxy) ); } /* vim:set et sw=2 ts=2: */
gobby/libinfinity
infinoted/infinoted-plugin-manager.c
C
lgpl-2.1
32,365
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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.16"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Ninject.Configuration.NinjectDependencyResolver.Start</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"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</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/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></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="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">4.2</span> </div> <div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></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"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('classCqrs_1_1Ninject_1_1Configuration_1_1NinjectDependencyResolver_adc6171ed45679dcbaa67782770ba5083.html','');}); /* @license-end */ </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="contents"> <a id="adc6171ed45679dcbaa67782770ba5083"></a> <h2 class="memtitle"><span class="permalink"><a href="#adc6171ed45679dcbaa67782770ba5083">&#9670;&nbsp;</a></span>Start()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">static void Cqrs.Ninject.Configuration.NinjectDependencyResolver.Start </td> <td>(</td> <td class="paramtype">IKernel&#160;</td> <td class="paramname"><em>kernel</em> = <code>null</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&#160;</td> <td class="paramname"><em>prepareProvidedKernel</em> = <code>false</code>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">static</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Starts the <a class="el" href="classCqrs_1_1Ninject_1_1Configuration_1_1NinjectDependencyResolver.html" title="Provides an ability to resolve instances of objects using Ninject">NinjectDependencyResolver</a> </p> <p>this exists to the static constructor can be triggered. </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="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Ninject.html">Ninject</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Ninject_1_1Configuration.html">Configuration</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Ninject_1_1Configuration_1_1NinjectDependencyResolver.html">NinjectDependencyResolver</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/4.2/html/classCqrs_1_1Ninject_1_1Configuration_1_1NinjectDependencyResolver_adc6171ed45679dcbaa67782770ba5083.html
HTML
lgpl-2.1
6,310
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "PostprocessorWarehouse.h" #include "Postprocessor.h" #include "ElementPostprocessor.h" #include "InternalSidePostprocessor.h" #include "SidePostprocessor.h" #include "NodalPostprocessor.h" #include "GeneralPostprocessor.h" #include "MooseMesh.h" #include "SubProblem.h" #include "Parser.h" PostprocessorWarehouse::PostprocessorWarehouse() { } PostprocessorWarehouse::~PostprocessorWarehouse() { // We don't need to free because that's taken care of by the UserObjectWarehouse // for (std::vector<Postprocessor *>::iterator i=_all_postprocessors.begin(); i!=_all_postprocessors.end(); ++i) // delete *i; } void PostprocessorWarehouse::initialSetup() { for(std::vector<ElementPostprocessor *>::const_iterator i=_all_element_postprocessors.begin(); i!=_all_element_postprocessors.end(); ++i) (*i)->initialSetup(); for(std::vector<NodalPostprocessor *>::const_iterator i=_all_nodal_postprocessors.begin(); i!=_all_nodal_postprocessors.end(); ++i) (*i)->initialSetup(); for(std::vector<SidePostprocessor *>::const_iterator i=_all_side_postprocessors.begin(); i!=_all_side_postprocessors.end(); ++i) (*i)->initialSetup(); for(std::vector<InternalSidePostprocessor *>::const_iterator i=_all_internal_side_postprocessors.begin(); i!=_all_internal_side_postprocessors.end(); ++i) (*i)->initialSetup(); for(std::vector<GeneralPostprocessor *>::const_iterator i=_all_generic_postprocessors.begin(); i!=_all_generic_postprocessors.end(); ++i) (*i)->initialSetup(); } void PostprocessorWarehouse::timestepSetup() { for(std::vector<ElementPostprocessor *>::const_iterator i=_all_element_postprocessors.begin(); i!=_all_element_postprocessors.end(); ++i) (*i)->timestepSetup(); for(std::vector<NodalPostprocessor *>::const_iterator i=_all_nodal_postprocessors.begin(); i!=_all_nodal_postprocessors.end(); ++i) (*i)->timestepSetup(); for(std::vector<SidePostprocessor *>::const_iterator i=_all_side_postprocessors.begin(); i!=_all_side_postprocessors.end(); ++i) (*i)->timestepSetup(); for(std::vector<InternalSidePostprocessor *>::const_iterator i=_all_internal_side_postprocessors.begin(); i!=_all_internal_side_postprocessors.end(); ++i) (*i)->timestepSetup(); for(std::vector<GeneralPostprocessor *>::const_iterator i=_all_generic_postprocessors.begin(); i!=_all_generic_postprocessors.end(); ++i) (*i)->timestepSetup(); } void PostprocessorWarehouse::residualSetup() { for(std::vector<ElementPostprocessor *>::const_iterator i=_all_element_postprocessors.begin(); i!=_all_element_postprocessors.end(); ++i) (*i)->residualSetup(); for(std::vector<NodalPostprocessor *>::const_iterator i=_all_nodal_postprocessors.begin(); i!=_all_nodal_postprocessors.end(); ++i) (*i)->residualSetup(); for(std::vector<SidePostprocessor *>::const_iterator i=_all_side_postprocessors.begin(); i!=_all_side_postprocessors.end(); ++i) (*i)->residualSetup(); for(std::vector<InternalSidePostprocessor *>::const_iterator i=_all_internal_side_postprocessors.begin(); i!=_all_internal_side_postprocessors.end(); ++i) (*i)->residualSetup(); for(std::vector<GeneralPostprocessor *>::const_iterator i=_all_generic_postprocessors.begin(); i!=_all_generic_postprocessors.end(); ++i) (*i)->residualSetup(); } void PostprocessorWarehouse::jacobianSetup() { for(std::vector<ElementPostprocessor *>::const_iterator i=_all_element_postprocessors.begin(); i!=_all_element_postprocessors.end(); ++i) (*i)->jacobianSetup(); for(std::vector<NodalPostprocessor *>::const_iterator i=_all_nodal_postprocessors.begin(); i!=_all_nodal_postprocessors.end(); ++i) (*i)->jacobianSetup(); for(std::vector<SidePostprocessor *>::const_iterator i=_all_side_postprocessors.begin(); i!=_all_side_postprocessors.end(); ++i) (*i)->jacobianSetup(); for(std::vector<InternalSidePostprocessor *>::const_iterator i=_all_internal_side_postprocessors.begin(); i!=_all_internal_side_postprocessors.end(); ++i) (*i)->jacobianSetup(); for(std::vector<GeneralPostprocessor *>::const_iterator i=_all_generic_postprocessors.begin(); i!=_all_generic_postprocessors.end(); ++i) (*i)->jacobianSetup(); } void PostprocessorWarehouse::addPostprocessor(Postprocessor *postprocessor) { _all_postprocessors.push_back(postprocessor); if (dynamic_cast<ElementPostprocessor*>(postprocessor)) { ElementPostprocessor * elem_pp = dynamic_cast<ElementPostprocessor*>(postprocessor); const std::set<SubdomainID> & block_ids = dynamic_cast<ElementPostprocessor*>(elem_pp)->blockIDs(); _all_element_postprocessors.push_back(elem_pp); for (std::set<SubdomainID>::const_iterator it = block_ids.begin(); it != block_ids.end(); ++it) { _element_postprocessors[*it].push_back(elem_pp); _block_ids_with_postprocessors.insert(*it); } } else if (dynamic_cast<SidePostprocessor*>(postprocessor)) { SidePostprocessor * side_pp = dynamic_cast<SidePostprocessor*>(postprocessor); _all_side_postprocessors.push_back(side_pp); const std::set<BoundaryID> & bnds = dynamic_cast<SidePostprocessor*>(side_pp)->boundaryIDs(); for (std::set<BoundaryID>::const_iterator it = bnds.begin(); it != bnds.end(); ++it) { _side_postprocessors[*it].push_back(side_pp); _boundary_ids_with_postprocessors.insert(*it); } } else if (dynamic_cast<InternalSidePostprocessor*>(postprocessor)) { InternalSidePostprocessor * internal_side_pp = dynamic_cast<InternalSidePostprocessor*>(postprocessor); _all_internal_side_postprocessors.push_back(internal_side_pp); const std::set<SubdomainID> & blks = dynamic_cast<InternalSidePostprocessor*>(internal_side_pp)->blockIDs(); for (std::set<SubdomainID>::const_iterator it = blks.begin(); it != blks.end(); ++it) { _internal_side_postprocessors[*it].push_back(internal_side_pp); _block_ids_with_postprocessors.insert(*it); } } else if (dynamic_cast<NodalPostprocessor*>(postprocessor)) { NodalPostprocessor * nodal_pp = dynamic_cast<NodalPostprocessor*>(postprocessor); // NodalPostprocessors can be "block" restricted and/or "boundary" restricted const std::set<BoundaryID> & bnds = nodal_pp->boundaryIDs(); const std::set<SubdomainID> & blks = nodal_pp->blockIDs(); // Add to the storage of all postprocessors _all_nodal_postprocessors.push_back(nodal_pp); // If the Block IDs are not empty, then the postprocessor is block restricted if (blks.find(Moose::ANY_BLOCK_ID) == blks.end()) for (std::set<SubdomainID>::const_iterator it = blks.begin(); it != blks.end(); ++it) { _block_nodal_postprocessors[*it].push_back(nodal_pp); _block_ids_with_nodal_postprocessors.insert(*it); } // Otherwise the postprocessor is a boundary postprocessor else for (std::set<BoundaryID>::const_iterator it = bnds.begin(); it != bnds.end(); ++it) { _nodal_postprocessors[*it].push_back(nodal_pp); _nodeset_ids_with_postprocessors.insert(*it); } } else { GeneralPostprocessor * general_pp = dynamic_cast<GeneralPostprocessor*>(postprocessor); // FIXME: generic pps multithreaded _generic_postprocessors.push_back(general_pp); _all_generic_postprocessors.push_back(general_pp); } } Postprocessor * PostprocessorWarehouse::getPostprocessor(std::string name) { // Loop through all the postprocessors, return the pointer if the names match for (std::vector<Postprocessor *>::iterator it=_all_postprocessors.begin(); it != _all_postprocessors.end(); ++it) { if (name.compare((*it)->PPName()) == 0) return *it; } // Return a null if nothing was found return NULL; }
amburan/moose
framework/src/postprocessors/PostprocessorWarehouse.C
C++
lgpl-2.1
8,830
/*! * \file grid_movement_structure.hpp * \brief Headers of the main subroutines for doing the numerical grid * movement (including volumetric movement, surface movement and Free From * technique definition). The subroutines and functions are in * the <i>grid_movement_structure.cpp</i> file. * \author Aerospace Design Laboratory (Stanford University) <http://su2.stanford.edu>. * \version 1.2.0 * * SU2, Copyright (C) 2012-2014 Aerospace Design Laboratory (ADL). * * SU2 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. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "geometry_structure.hpp" #include "config_structure.hpp" #include "matrix_structure.hpp" #include "vector_structure.hpp" #include "linear_solvers_structure.hpp" #include <iostream> #include <cstdlib> #include <fstream> #include <cmath> #include <ctime> using namespace std; /*! * \class CGridMovement * \brief Class for moving the surface and volumetric * numerical grid (2D and 3D problems). * \author F. Palacios. * \version 1.2.0 */ class CGridMovement { public: /*! * \brief Constructor of the class. */ CGridMovement(void); /*! * \brief Destructor of the class. */ ~CGridMovement(void); /*! * \brief A pure virtual member. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ virtual void SetSurface_Deformation(CGeometry *geometry, CConfig *config); }; /*! * \class CVolumetricMovement * \brief Class for moving the volumetric numerical grid. * \author F. Palacios, A. Bueno, T. Economon, S. Padron. * \version 1.2.0 */ class CVolumetricMovement : public CGridMovement { protected: unsigned short nDim; /*!< \brief Number of dimensions. */ unsigned short nVar; /*!< \brief Number of variables. */ unsigned long nPoint; /*!< \brief Number of points. */ unsigned long nPointDomain; /*!< \brief Number of points in the domain. */ CSysMatrix StiffMatrix; /*!< \brief Matrix to store the point-to-point stiffness. */ CSysVector LinSysSol; CSysVector LinSysRes; public: /*! * \brief Constructor of the class. */ CVolumetricMovement(CGeometry *geometry); /*! * \brief Destructor of the class. */ ~CVolumetricMovement(void); /*! * \brief Update the value of the coordinates after the grid movement. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ void UpdateGridCoord(CGeometry *geometry, CConfig *config); /*! * \brief Update the dual grid after the grid movement (edges and control volumes). * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ void UpdateDualGrid(CGeometry *geometry, CConfig *config); /*! * \brief Update the coarse multigrid levels after the grid movement. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ void UpdateMultiGrid(CGeometry **geometry, CConfig *config); /*! * \brief Compute the stiffness matrix for grid deformation using spring analogy. * \param[in] geometry - Geometrical definition of the problem. * \return Value of the length of the smallest edge of the grid. */ double SetFEAMethodContributions_Elem(CGeometry *geometry, CConfig *config); /*! * \brief Build the stiffness matrix for a 3-D hexahedron element. The result will be placed in StiffMatrix_Elem. * \param[in] geometry - Geometrical definition of the problem. * \param[in] StiffMatrix_Elem - Element stiffness matrix to be filled. * \param[in] CoordCorners[8][3] - Index value for Node 1 of the current hexahedron. */ void SetFEA_StiffMatrix3D(CGeometry *geometry, CConfig *config, double **StiffMatrix_Elem, unsigned long PointCorners[8], double CoordCorners[8][3], unsigned short nNodes, double scale); /*! * \brief Build the stiffness matrix for a 3-D hexahedron element. The result will be placed in StiffMatrix_Elem. * \param[in] geometry - Geometrical definition of the problem. * \param[in] StiffMatrix_Elem - Element stiffness matrix to be filled. * \param[in] CoordCorners[8][3] - Index value for Node 1 of the current hexahedron. */ void SetFEA_StiffMatrix2D(CGeometry *geometry, CConfig *config, double **StiffMatrix_Elem, unsigned long PointCorners[8], double CoordCorners[8][3], unsigned short nNodes, double scale); /*! * \brief Shape functions and derivative of the shape functions * \param[in] Xi - Local coordinates. * \param[in] Eta - Local coordinates. * \param[in] Mu - Local coordinates. * \param[in] CoordCorners[8][3] - Coordiantes of the corners. * \param[in] shp[8][4] - Shape function information */ double ShapeFunc_Hexa(double Xi, double Eta, double Mu, double CoordCorners[8][3], double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions * \param[in] Xi - Local coordinates. * \param[in] Eta - Local coordinates. * \param[in] Mu - Local coordinates. * \param[in] CoordCorners[8][3] - Coordiantes of the corners. * \param[in] shp[8][4] - Shape function information */ double ShapeFunc_Tetra(double Xi, double Eta, double Mu, double CoordCorners[8][3], double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions * \param[in] Xi - Local coordinates. * \param[in] Eta - Local coordinates. * \param[in] Mu - Local coordinates. * \param[in] CoordCorners[8][3] - Coordiantes of the corners. * \param[in] shp[8][4] - Shape function information */ double ShapeFunc_Pyram(double Xi, double Eta, double Mu, double CoordCorners[8][3], double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions * \param[in] Xi - Local coordinates. * \param[in] Eta - Local coordinates. * \param[in] Mu - Local coordinates. * \param[in] CoordCorners[8][3] - Coordiantes of the corners. * \param[in] shp[8][4] - Shape function information */ double ShapeFunc_Wedge(double Xi, double Eta, double Mu, double CoordCorners[8][3], double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions * \param[in] Xi - Local coordinates. * \param[in] Eta - Local coordinates. * \param[in] Mu - Local coordinates. * \param[in] CoordCorners[8][3] - Coordiantes of the corners. * \param[in] shp[8][4] - Shape function information */ double ShapeFunc_Triangle(double Xi, double Eta, double CoordCorners[8][3], double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions * \param[in] Xi - Local coordinates. * \param[in] Eta - Local coordinates. * \param[in] Mu - Local coordinates. * \param[in] CoordCorners[8][3] - Coordiantes of the corners. * \param[in] shp[8][4] - Shape function information */ double ShapeFunc_Rectangle(double Xi, double Eta, double CoordCorners[8][3], double DShapeFunction[8][4]); /*! * \brief Compute the shape functions for hexahedron * \param[in] HexaCorners[8][3] - coordinates of the cornes of the hexahedron. */ double GetHexa_Volume(double CoordCorners[8][3]); /*! * \brief Compute the shape functions for hexahedron * \param[in] TetCorners[4][3] - coordinates of the cornes of the hexahedron. */ double GetTetra_Volume(double CoordCorners[8][3]); /*! * \brief Compute the shape functions for hexahedron * \param[in] TetCorners[4][3] - coordinates of the cornes of the hexahedron. */ double GetWedge_Volume(double CoordCorners[8][3]); /*! * \brief Compute the shape functions for hexahedron * \param[in] TetCorners[4][3] - coordinates of the cornes of the hexahedron. */ double GetPyram_Volume(double CoordCorners[8][3]); /*! * \brief Compute the shape functions for hexahedron * \param[in] TetCorners[4][3] - coordinates of the cornes of the hexahedron. */ double GetTriangle_Area(double CoordCorners[8][3]); /*! * \brief Compute the shape functions for hexahedron * \param[in] TetCorners[4][3] - coordinates of the cornes of the hexahedron. */ double GetRectangle_Area(double CoordCorners[8][3]); /*! * \brief Add the stiffness matrix for a 2-D triangular element to the global stiffness matrix for the entire mesh (node-based). * \param[in] geometry - Geometrical definition of the problem. * \param[in] StiffMatrix_Elem - Element stiffness matrix to be filled. * \param[in] val_Point_0 - Index value for Node 0 of the current tetrahedron. * \param[in] val_Point_1 - Index value for Node 1 of the current tetrahedron. * \param[in] val_Point_2 - Index value for Node 2 of the current tetrahedron. * \param[in] val_Point_3 - Index value for Node 3 of the current tetrahedron. */ void AddFEA_StiffMatrix(CGeometry *geometry, double **StiffMatrix_Elem, unsigned long PointCorners[8], unsigned short nNodes); /*! * \brief Check for negative volumes (all elements) after performing grid deformation. * \param[in] geometry - Geometrical definition of the problem. */ double Check_Grid(CGeometry *geometry); /*! * \brief Check the boundary vertex that are going to be moved. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ void SetBoundaryDisplacements(CGeometry *geometry, CConfig *config); /*! * \brief Grid deformation using the spring analogy method. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] UpdateGeo - Update geometry. */ void SetVolume_Deformation(CGeometry *geometry, CConfig *config, bool UpdateGeo); /*! * \brief Compute the determinant of a 3 by 3 matrix. * \param[in] val_matrix 3 by 3 matrix. * \result Determinant of the matrix */ double Determinant_3x3(double A00, double A01, double A02, double A10, double A11, double A12, double A20, double A21, double A22); }; /*! * \class CSurfaceMovement * \brief Class for moving the surface numerical grid. * \author F. Palacios, T. Economon. * \version 1.2.0 */ class CSurfaceMovement : public CGridMovement { protected: public: /*! * \brief Constructor of the class. */ CSurfaceMovement(void); /*! * \brief Destructor of the class. */ ~CSurfaceMovement(void); /*! * \brief Set a obstacle in a channel. * \param[in] boundary - Geometry of the boundary. * \param[in] config - Definition of the particular problem. */ void SetAirfoil(CGeometry *boundary, CConfig *config); /*! * \brief Copy the boundary coordinates to each vertex. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ void CopyBoundary(CGeometry *geometry, CConfig *config); /*! * \brief Set the surface/boundary deformation. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ void SetSurface_Deformation(CGeometry *geometry, CConfig *config); }; #include "grid_movement_structure.inl"
shivajimedida/SU2_EDU
include/grid_movement_structure.hpp
C++
lgpl-2.1
12,197
// --------------------------------------------------------------------- // // Copyright (C) 2005 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // compare the FE_RaviartThomasNodal and FE_RaviartThomas elements // compare the shape funcions and shape values after converting to the // same basis. // Summary: the different Raviart-Thomas implementations use the same // polynomial spaces, but different basis functions. Here, we convert // between the bases and test if the resulting functions are the same // point-wise. #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/fe/fe_raviart_thomas.h> #include <deal.II/fe/mapping_cartesian.h> #include <deal.II/fe/fe_values.h> #include <fstream> // This function copied from FERaviartThomasNodal. nodes is the // element having the support points and the value of other in these // points is computed. template <int dim> void initialize_node_matrix (const FiniteElement<dim> &other, const FiniteElement<dim> &nodes, FullMatrix<double> &N) { const unsigned int n_dofs = other.dofs_per_cell; Assert (n_dofs == nodes.dofs_per_cell, ExcDimensionMismatch(n_dofs, nodes.dofs_per_cell)); N.reinit(n_dofs, n_dofs); const std::vector<Point<dim> > &unit_support_points = nodes.get_generalized_support_points(); // The curent node functional index unsigned int current = 0; // For each face and all quadrature // points on it, the node value is // the normal component of the // shape function, possibly // pointing in negative direction. for (unsigned int face = 0; face<GeometryInfo<dim>::faces_per_cell; ++face) for (unsigned int k=0; k<other.dofs_per_face; ++k) { for (unsigned int i=0; i<n_dofs; ++i) N(current,i) = other.shape_value_component( i, unit_support_points[current], GeometryInfo< dim >::unit_normal_direction[face]); ++current; } // Interior degrees of freedom in each direction const unsigned int n_cell = (n_dofs - current) / dim; for (unsigned int d=0; d<dim; ++d) for (unsigned int k=0; k<n_cell; ++k) { for (unsigned int i=0; i<n_dofs; ++i) N(current,i) = other.shape_value_component(i, unit_support_points[current], d); ++current; } Assert (current == n_dofs, ExcInternalError()); } template <int dim> void compare_shapes (const FiniteElement<dim> &other, const FiniteElement<dim> &nodes, FullMatrix<double> &M) { QGauss<dim> quadrature(other.degree+1); Table<3,double> other_values(quadrature.size(), other.dofs_per_cell, dim); Table<3,double> nodes_values(quadrature.size(), other.dofs_per_cell, dim); Table<3,Tensor<1,dim> > other_grads(quadrature.size(), other.dofs_per_cell, dim); Table<3,Tensor<1,dim> > nodes_grads(quadrature.size(), other.dofs_per_cell, dim); for (unsigned int k=0; k<quadrature.size(); ++k) for (unsigned int i=0; i<other.dofs_per_cell; ++i) for (unsigned int d=0; d<dim; ++d) { other_values[k][i][d] = other.shape_value_component(i,quadrature.point(k),d); nodes_values[k][i][d] = nodes.shape_value_component(i,quadrature.point(k),d); other_grads[k][i][d] = other.shape_grad_component(i,quadrature.point(k),d); nodes_grads[k][i][d] = nodes.shape_grad_component(i,quadrature.point(k),d); } for (unsigned int k=0; k<quadrature.size(); ++k) { for (unsigned int i=0; i<other.dofs_per_cell; ++i) for (unsigned int d=0; d<dim; ++d) { double value = other_values[k][i][d]; Tensor<1,dim> grad = other_grads[k][i][d]; for (unsigned int j=0; j<other.dofs_per_cell; ++j) { value -= M(j,i) * nodes_values[k][j][d]; grad -= M(j,i) * nodes_grads[k][j][d]; } deallog << '.'; if (std::fabs(value) > 1.e-12) deallog << "Error value\t" << k << '\t' << i << '\t' << d << '\t' << value << std::endl; if (grad.norm() > 1.e-12) deallog << "Error grad\t" << k << '\t' << i << '\t' << d << '\t' << grad << '\t' << other_grads[k][i][d] << std::endl; } deallog << std::endl; } } template<int dim> void test (unsigned int degree) { FE_RaviartThomas<dim> rt1(degree); FE_RaviartThomasNodal<dim> rtn1(degree); FullMatrix<double> N; initialize_node_matrix(rt1, rtn1, N); compare_shapes(rt1, rtn1, N); } int main() { std::ofstream logfile ("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); test<2>(0); test<2>(1); test<2>(2); }
flow123d/dealii
tests/fe/rtdiff.cc
C++
lgpl-2.1
5,393
/* $Id$ * * OpenMAMA: The open middleware agnostic messaging API * Copyright (C) 2011 NYSE Technologies, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ using System; namespace Wombat { public class MamdaConcreteSecurityStatusRecap : MamdaSecurityStatusRecap { /// <summary> /// Clear the recap data /// </summary> public void clear() { mSecurityStatus = 0; mSecurityStatusEnum = MamdaSecurityStatus.mamdaSecurityStatus.SECURITY_STATUS_NONE; mSecurityStatusQualifier = 0; mSecurityStatusQualifierEnum = MamdaSecurityStatusQual.mamdaSecurityStatusQual.SECURITY_STATUS_QUAL_NONE; mSecurityStatusStr = null; mShortSaleCircuitBreaker = ' '; mSecurityStatusQualifierStr = null; mActTime = DateTime.MinValue; mSrcTime = DateTime.MinValue; mReason = null; } /// <summary> /// Returns the security status /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatus()"/> /// </summary> /// <returns></returns> public long getSecurityStatus() { return mSecurityStatus; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// Set the security status /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatus()"/> /// </summary> /// <param name="securityStatus"></param> public void setSecurityStatus(long securityStatus) { mSecurityStatus = securityStatus; } /// <summary> /// Returns the security /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatus()"/> /// </summary> /// <returns></returns> public long getSecurityStatusQualifier() { return mSecurityStatusQualifier; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusQualifierFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatus()"/> /// </summary> /// <param name="secQualifier"></param> public void setSecurityStatusQualifier(long secQualifier) { mSecurityStatusQualifier = secQualifier; } /// <summary> /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusEnum()"/> /// </summary> /// <returns></returns> public MamdaSecurityStatus.mamdaSecurityStatus getSecurityStatusEnum() { return mSecurityStatusEnum; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusEnumFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusEnum()"/> /// </summary> /// <returns</returns> public void setSecurityStatusEnum(MamdaSecurityStatus.mamdaSecurityStatus secStatus) { mSecurityStatusEnum = secStatus; } /// <summary> /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusQualifierEnum()"/> /// </summary> /// <returns></returns> public MamdaSecurityStatusQual.mamdaSecurityStatusQual getSecurityStatusQualifierEnum() { return mSecurityStatusQualifierEnum; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusQualifierEnumFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusQualifierEnum()"/> /// </summary> /// <param name="secStatusQual"></param> public void setSecurityStatusQualifierEnum(MamdaSecurityStatusQual.mamdaSecurityStatusQual secStatusQual) { mSecurityStatusQualifierEnum = secStatusQual; } /// <summary> /// Returns the security status string /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusQualifier()"/> /// </summary> /// <returns></returns> public string getSecurityStatusStr() { return mSecurityStatusStr; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusStrFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// Returns the short sale CircuitBreaker /// <see cref="MamdaSecurityStatusUpdate.getShortSaleCircuitBreaker()"/> /// </summary> /// <returns></returns> public char getShortSaleCircuitBreaker() { return mShortSaleCircuitBreaker; } /// <summary> /// Set the short sale Circuit Breaker. /// <see cref="MamdaSecurityStatusUpdate.getShortSaleCircuitBreakerFieldState()"/> /// </summary> /// <param name="shortSaleCircuitBreaker"></param> public void setShortSaleCircuitBreaker(char shortSaleCircuitBreaker) { mShortSaleCircuitBreaker = shortSaleCircuitBreaker; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getShortSaleCircuitBreakerFieldState() { return MamdaFieldState.MODIFIED; } public string getSecurityStatusOrigStr() { return mSecurityStatusOrigStr; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusOrigStrFieldState() { return MamdaFieldState.MODIFIED; } public void setSecurityStatusOrigStr(string securityStatusOrigStr) { if (securityStatusOrigStr != null) mSecurityStatusOrigStr = securityStatusOrigStr; } /// <summary> /// Set the security status string /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusQualifier()"/> /// </summary> /// <param name="securityStatusStr"></param> public void setSecurityStatusStr(string securityStatusStr) { if (securityStatusStr != null) mSecurityStatusStr = securityStatusStr; } /// <summary> /// Returns the security status qualifier string /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusQualifier()"/> /// </summary> /// <returns></returns> public string getSecurityStatusQualifierStr() { return mSecurityStatusQualifierStr; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSecurityStatusQualifierStrFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// Set the security status qualifier string /// <see cref="MamdaSecurityStatusUpdate.getSecurityStatusQualifier()"/> /// </summary> /// <param name="securityStatusQualifierStr"></param> public void setSecurityStatusQualifierStr ( String securityStatusQualifierStr) { if (securityStatusQualifierStr != null) mSecurityStatusQualifierStr = securityStatusQualifierStr; } ///< summary> /// Returns the security status reason /// <see cref="MamdaSecurityStatusRecap.getReason()"/> /// </summary> /// <returns></returns> public string getReason() { return mReason; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getReasonFieldState() { return MamdaFieldState.MODIFIED; } ///<summary> /// Set the security status reason /// <see cref="MamdaSecurityStatusRecap.getReason()"/> /// </summary> /// <param name="reason"></param> public void setReason ( string reason) { if (reason != null) mReason = reason; } /// <summary> /// <see cref="MamdaBasicRecap.getActivityTime"/> /// </summary> /// <returns></returns> public DateTime getActivityTime() { return mActTime; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getActivityTimeFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// /// </summary> /// <param name="actTime"></param> public void setActivityTime(DateTime actTime) { if (actTime != DateTime.MinValue) mActTime = actTime; } public void setSrcTime(DateTime srcTime) { if (srcTime != DateTime.MinValue) mSrcTime = srcTime; } public DateTime getSrcTime() { return mSrcTime ; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getSrcTimeFieldState() { return MamdaFieldState.MODIFIED; } ///< summary> /// Returns the security status Luld Time /// </summary> /// <returns></returns> public DateTime getLuldTime() { return mLuldTime; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getLuldTimeFieldState() { return MamdaFieldState.MODIFIED; } ///< summary> /// Returns the security status Luld Indicator /// </summary> /// <returns></returns> public char getLuldIndicator() { return mLuldIndicator; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getLuldIndicatorFieldState() { return MamdaFieldState.MODIFIED; } ///< summary> /// Returns the security status Luld High Limit /// </summary> /// <returns></returns> public MamaPrice getLuldHighLimit() { return mLuldHighLimit; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getLuldHighLimitFieldState() { return MamdaFieldState.MODIFIED; } ///< summary> /// Returns the security status Luld LowLimit /// </summary> /// <returns></returns> public MamaPrice getLuldLowLimit() { return mLuldLowLimit; } /// <summary>Returns Field State, always MODIFIED /// </summary> /// <returns>Field State MODIFIED</returns> public MamdaFieldState getLuldLowLimitFieldState() { return MamdaFieldState.MODIFIED; } /// <summary> /// Set the Limit Up Limit Down Time /// </summary> /// <param name="LuldTime"></param> public void setLuldTime(DateTime luldTime) { if (luldTime != DateTime.MinValue) mLuldTime = luldTime; } /// <summary> /// Set the Limit Up Limit Down Indicator /// </summary> /// <param name="LuldIndicator"></param> public void setLuldIndicator(char luldIndicator) { mLuldIndicator = luldIndicator; } /// <summary> /// Set the Limit Up Limit Down High Limit /// </summary> /// <param name="LuldHighLimit"></param> public void setLuldHighLimit(MamaPrice luldHighLimit) { mLuldHighLimit.copy(luldHighLimit); } /// <summary> /// Set the Limit Up Limit Down Low Limit /// </summary> /// <param name="LuldHighLimit"></param> public void setLuldLowLimit(MamaPrice luldLowLimit) { mLuldLowLimit.copy(luldLowLimit); } private long mSecurityStatus; private long mSecurityStatusQualifier; private MamdaSecurityStatus.mamdaSecurityStatus mSecurityStatusEnum; private MamdaSecurityStatusQual.mamdaSecurityStatusQual mSecurityStatusQualifierEnum; private string mSecurityStatusStr; private char mShortSaleCircuitBreaker; private string mSecurityStatusOrigStr; private string mSecurityStatusQualifierStr; private DateTime mActTime = DateTime.MinValue; private DateTime mSrcTime = DateTime.MinValue; private string mReason = null; private DateTime mLuldTime = DateTime.MinValue; private char mLuldIndicator = ' '; private MamaPrice mLuldHighLimit = new MamaPrice(); private MamaPrice mLuldLowLimit = new MamaPrice(); } }
philippreston/OpenMAMA
mamda/dotnet/src/cs/MamdaConcreteSecurityStatusRecap.cs
C#
lgpl-2.1
13,898
import unittest import re from lxml import etree from zope.testing import doctest, cleanup import zope.component.eventtesting from imagestore.xml import XMLValidationError, local_file class ValidationTests(unittest.TestCase): relaxng = etree.RelaxNG(file=local_file('rng', 'imagestore.rng')) def validate(self, el): if not self.relaxng.validate(etree.ElementTree(el)): raise XMLValidationError("%s failed to validate" % el.tag) def test_basic(self): xml = ''' <imagestore xmlns="http://studiolab.io.tudelft.nl/ns/imagestore"> <sessions> </sessions> </imagestore> ''' self.validate(etree.XML(xml)) def test_attributes(self): xml = ''' <imagestore xmlns="http://studiolab.io.tudelft.nl/ns/imagestore"> <sessions href="sessions"> </sessions> </imagestore> ''' self.validate(etree.XML(xml)) def test_attributes_illegal(self): xml = ''' <imagestore xmlns="http://studiolab.io.tudelft.nl/ns/imagestore"> <sessions name="sessions"> </sessions> </imagestore> ''' self.assertRaises(XMLValidationError, self.validate, etree.XML(xml)) def test_extended(self): xml = ''' <imagestore xmlns="http://studiolab.io.tudelft.nl/ns/imagestore"> <sessions> <session href="sessions/foo" name="foo"> <group xmlns="http://studiolab.io.tudelft.nl/ns/imagestore" href="." name="collection"> <source src="APP/sessions/foo/images/UNKNOWN" name="UNKNOWN"/> <metadata href="metadata"> <depth href="metadata/depth">0.0</depth> <rotation href="metadata/rotation">0.0</rotation> <x href="metadata/x">0.0</x> <y href="metadata/y">0.0</y> </metadata> <objects href="objects"> <image href="objects/alpha" name="alpha"> <source src="APP/sessions/foo/images/a.png" name="a.png"/> <metadata href="objects/alpha/metadata"> <depth href="objects/alpha/metadata/depth">0.0</depth> <rotation href="objects/alpha/metadata/rotation">0.0</rotation> <x href="objects/alpha/metadata/x">0.0</x> <y href="objects/alpha/metadata/y">0.0</y> </metadata> </image> <group href="objects/beta" name="beta"> <source src="APP/sessions/foo/images/a.png" name="a.png"/> <metadata href="objects/beta/metadata"> <depth href="objects/beta/metadata/depth">0.0</depth> <rotation href="objects/beta/metadata/rotation">0.0</rotation> <x href="objects/beta/metadata/x">0.0</x> <y href="objects/beta/metadata/y">0.0</y> </metadata> <objects href="objects/beta/objects"/> </group> </objects> </group> <images> </images> </session> </sessions> </imagestore> ''' self.validate(etree.XML(xml)) def setUpZope(test): zope.component.eventtesting.setUp(test) def cleanUpZope(test): cleanup.cleanUp() r_created = re.compile('<created>[^/]*</created>') r_modified = re.compile('<modified>[^/]*</modified>') def datetime_normalize(xml): result = r_created.sub('<created></created>', xml) result = r_modified.sub('<modified></modified', result) return result def test_suite(): optionflags = ( doctest.ELLIPSIS | doctest.REPORT_NDIFF | doctest.NORMALIZE_WHITESPACE ) return unittest.TestSuite([ doctest.DocFileSuite( 'model.txt', optionflags=optionflags, setUp=setUpZope, tearDown=cleanUpZope, globs={'datetime_normalize': datetime_normalize}), unittest.makeSuite(ValidationTests)])
idstudiolab/imagestore
src/imagestore/tests.py
Python
lgpl-2.1
4,153
// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _PtGatewayInterface_h_ #define _PtGatewayInterface_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class PtMediaCapabilities; class PtAudioCodec; //: Abstract gateway interface used to obtain call setup information from //: a media gateway. // To implement a media gateway using PTAPI one implements this class by // deriving from it, creating an instance and registering it on the // PtTerminal which represents the gateway via the // PtTerminal::setGatewayInterface method. All of the methods on this // class must be implemented. // <BR> // A call setup with the the gateway (incoming or out going) starts with // the call to the <I>reserveLine</I> method. The gateway uses this method to // indicate that whether it has resources to accept or initiate a call. // Regardless of whether the gateway has resources for a line, the gateway // must return a line handle which the gateway may use to correlate // subsequent calls to methods on this class related to the same // line/terminalConnection. If <I>reserveLine</I> returned with an availability // other than LINE_AVAILABLE, the provider server will call the releaseLine // method and the other side of the call will get appropriate indication. // <BR> // If <I>reserveLine</I> returned with an availability of LINE_AVAILABLE, // the provider service will call the <I>getLineCapabilities</I> // method to get the encoding capabilities for both sending and receiving // of RTP packets. If a codec is found which is compatible with the other // end of the call the provider will subsequently call the <I>startLineRtpSend</I> // and <I>startLineRtpReceive</I> methods. However the order and timing in which // these two methods are called will vary depending upon which side // initiated the call and the implementation of the phone at the other end. // <BR> // When either side disconnects the call, the provider server will then // invoke the stopLineRtpSend and stopLineRtpReceive methods. Again the // order in which these are invoked may vary. Finally the releaseLine // method will be invoked to indicate that the line is no longer needed. // <BR> // <H3>Other PTAPI Interfaces Relevent to Gateways</H3> // For incoming calls (from other phones controlled by the PTAPI provider) // to the gateway, methods on this interface will be called starting // with <I>reserveLine</I>. However the gateway may want to implement a // PtTerminalConnectionListener to register on the associated PtTerminal // as well, to get call state information on calls to and from the gateway. // <BR> // For outgoing calls (to other phones controlled by the PTAPI provider) // from the gateway, the gateway creates a call via PtProvider::createCall // then sets up a call via the PtCall::connect method. The provider service // will make subsequent calls to the methods in this class starting with // <I>reserveLine</I>. // <BR> // Calls may be terminated by the gateway via the PtConnection::disconnect // method, regardless of which side initiated the call. class PtGatewayInterface { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum PtGatewayAvailability { UNKNOWN, LINE_AVAILABLE, ADDRESS_BUSY, GATEWAY_BUSY } //: Availability states for the gateway //! enumcode: UNKNOWN - error state //! enumcode: LINE_AVAILABLE - a line is available on this gateway on which to setup a call. //! enumcode: ADDRESS_BUSY - a line is available on this gateway, but the destination address to be called via this gateway is busy. //! enumcode: GATEWAY_BUSY - all lines are currently busy on this gateway. /* ============================ CREATORS ================================== */ PtGatewayInterface(); //:Default constructor virtual ~PtGatewayInterface(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual PtStatus reserveLine(PtTerminalConnection& rGatewayTerminalConnection, const char* destinationAddress, PtGatewayAvailability& rAvailablity, void*& rReservationHandle) = 0; //: Request to reserve a line on the gateway to the given PBX or PSTN //: phone // The OpenPhone SDK calls this method to reserve a line // on this gateway. The gateway checks that a line is available and // that the identified destination phone is not busy. // Note: releaseLine is called even when a call to <I>reserveLine</I> indicates // that a line is not available. <I>reserveLine</I> should therefore always // return a reservationHandle which is meaningful to releaseLine. // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. //!param: (in) rGatewayTerminalConnection - the terminal connection on this gateway for the call. //!param: (in) destinationAddress - (presently not used) //!param: (out) rAvailablity - GATEWAY_BUSY|ADDRESS_BUSY|AVAILABLE //!param: (out) rReservationHandle - reservation handle generated by the gateway. This is used in subsequent method invocations on the gateway to identify which reservation/terminalConnection/line the operation pertains to. For example the gateway may use the line number if there are a fixed number of lines that the gateway supports. This value is merely passed back to the gateway. It is not used outside the methods defined in this class. virtual PtStatus getLineCapabilities(void* reservationHandle, PtMediaCapabilities& rCapabilities, char rtpReceiveIpAddress[], int maxAddressLength, int& rRtpReceivePort) = 0; //: Get the codec capabilities for the reserved line // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. // Note: This method may be called more than once // during a single call on the same line to re-negotiate codecs. //!param: (in) reservationHandle - handle indicating the line on which to obtain capabilities //!param: (out) rCapabilities - reference to capabilities object defining the send and receive encodings allowed on this line //!param: (out) rtpReceiveIpAddress - null terminated ip address or DNS name string of the host that the gateway wishes to receive RTP packets for this line. //!param: (in) maxAddressLength - the maximum length that <I>rtpReceiveIpAddress</I> may be. //!param: (out) rRtpReceivePort - the port that the gateway wishes to receive RTP packets on the host specified in <I>rtpReceiveIpAddress</I>. virtual PtStatus startLineRtpSend(void* reservationHandle, const PtAudioCodec& rSendCodec, const char* sendAddress, int sendPort) = 0; //: Start sending audio via RTP and RTCP for the line indicated // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. // Note: This method may be called more than once // during a single call on the same line to change codecs. //! param: (in) reservationHandle - handle indicating the line on which to start sending RTP and RTCP //! param: (in) rSendCodec - RTP encoding method to be used when sending RTP //! param: (in) sendAddress - the IP address or DNS name of the destination host for the RTP and RTCP packets //! param: (in) sendPort - the port on which the destination host expects to receive RTP packets. The host expects to receive RTCP packets on the port: sendPort + 1. virtual PtStatus startLineRtpReceive(void* reservationHandle, const PtAudioCodec& rReceiveCodec) = 0; //: Start receiving audio via RTP and RTCP for the line indicated // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. // Note: that although it is specified what encoding method the gateway should // expect in received RTP packets, it is recommended for robustness that // the gateway handle any of the encodings specified in the capabilities // of the getLineCapabilities method. // Note: This method may be called more than once // during a single call on the same line to change codecs. //! param: (in) reservationHandle - handle indicating the line on which to start receiving RTP and RTCP //! param: (in) rReceiveCodec - RTP encoding method to be used when receiving RTP virtual PtStatus stopLineRtpSend(void* reservationHandle) = 0; //: Stop sending RTP and RTCP for the line indicated // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. //! param: (in) reservationHandle - handle indicating the line on which to stop sending RTP and RTCP virtual PtStatus stopLineRtpReceive(void* reservationHandle) = 0; //: Stop receiving RTP and RTCP for the line indicated // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. //! param: (in) reservationHandle - handle indicating the line on which to stop receiving RTP and RTCP virtual PtStatus releaseLine(void* reservationHandle) = 0; //: Notify the gateway that line is no longer needed. // Note: this method is called even when a call to <I>reserveLine</I> indicates // that a line is not available. <I>reserveLine</I> should therefore always // return a reservationHandle which is meaningful to releaseLine. // This method must be implemented by the // gateway or PBX if call setup is to be performed via the API. //! param: (in) reservationHandle - handle indicating the line which is no longer used. /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: PtGatewayInterface(const PtGatewayInterface& rPtGatewayInterface); //:Copy constructor (disabled) PtGatewayInterface& operator=(const PtGatewayInterface& rhs); //:Assignment operator (disabled) }; /* ============================ INLINE METHODS ============================ */ #endif // _PtGatewayInterface_h_
sipXtapi/sipXtapi
sipXcallLib/include/ptapi/PtGatewayInterface.h
C
lgpl-2.1
11,064
/* Copyright (C) 2010 William Hart This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */ #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpz_vec.h" void _fmpz_vec_add(fmpz * res, const fmpz * vec1, const fmpz * vec2, slong len2) { slong i; for (i = 0; i < len2; i++) fmpz_add(res + i, vec1 + i, vec2 + i); }
jpflori/flint2
fmpz_vec/add.c
C
lgpl-2.1
632
#include <QtCore/QObject> namespace Foo2 { class MyObj : public QObject { Q_OBJECT public: public Q_SLOTS: void slot1() {} void slot2() {} Q_SIGNALS: void signal1(); }; } using namespace Foo2; void foo1() { Foo2::MyObj *o1 = new Foo2::MyObj(); QObject::connect(o1, SIGNAL(signal1()), o1, SLOT(slot1())); // Warning } int main() { return 0; } #include "usingnamespace.moc"
nyalldawson/clazy
tests/old-style-connect/usingnamespace.cpp
C++
lgpl-2.1
403