repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
lerages/anarchy-source
src/main/java/org/rs2server/rs2/action/impl/HarvestingAction.java
package org.rs2server.rs2.action.impl; import org.rs2server.rs2.action.Action; import org.rs2server.rs2.model.Animation; import org.rs2server.rs2.model.GameObject; import org.rs2server.rs2.model.Item; import org.rs2server.rs2.model.Mob; import org.rs2server.rs2.model.World; import org.rs2server.rs2.net.ActionSender.DialogueType; /** * <p>A harvesting action is a resource-gathering action, which includes, but * is not limited to, woodcutting and mining.</p> * * <p>This class implements code related to all harvesting-type skills, such as * dealing with the action itself, looping, expiring the object (i.e. changing * rocks to the gray rock and trees to the stump), checking requirements and * giving out the harvested resources.</p> * * <p>The individual woodcutting and mining classes implement things specific * to these individual skills such as random events.</p> * @author <NAME> * */ public abstract class HarvestingAction extends Action { /** * Creates the harvesting action for the specified mob. * @param mob The mob to create the action for. */ public HarvestingAction(Mob mob) { super(mob, 0); } /** * Optoinally overrideable method which is called whenever an item has been harvested. * @param item The item. */ public void onSuccessfulHarvest(final Item item) { } /** * Gets the amount of cycles before the object is interacted with. * @return The amount of cycles before the object is interacted with. */ public abstract int getCycleCount(); /** * Gets the game object we are harvesting. * @return The game object we are harvesting. */ public abstract GameObject getGameObject(); /** * Gets the game object that replaces the object we harvest. * @return The game object that replaces the object we harvest. */ public abstract GameObject getReplacementObject(); /** * Gets the game objects maximum health. * @return The game objects maximum health. */ public abstract int getGameObjectMaxHealth(); /** * Gets the amount of cycles it takes for the object to respawn. * @return The amount of cycles it takes for the object to respawn. */ public abstract int getObjectRespawnTimer(); /** * Gets the reward from harvesting the object. * @return The reward from harvesting the object. */ public abstract Item getReward(); /** * Gets the skill we are using to harvest. * @return The skill we are using to harvest. */ public abstract int getSkill(); /** * Gets the required level to harvest this object. * @return The required level to harvest this object. */ public abstract int getRequiredLevel(); /** * Gets the experience granted for each item that is successfully harvested. * @return The experience granted for each item that is successfully harvested. */ public abstract double getExperience(); /** * Gets the message sent when the mob's level is too low to harvest this object. * @return The message sent when the mob's level is too low to harvest this object. */ public abstract String getLevelTooLowMessage(); /** * Gets the message sent when the harvest successfully begins. * @return The message sent when the harvest successfully begins. */ public abstract String getHarvestStartedMessage(); /** * Gets the message sent when the mob successfully harvests from the object. * @return The message sent when the mob successfully harvests from the object. */ public abstract String getSuccessfulHarvestMessage(); /** * Gets the message sent when the mob has a full inventory. * @return The message sent when the mob has a full inventory. */ public abstract String getInventoryFullMessage(); /** * Gets the animation played whilst harvesting the object. * @return The animation played whilst harvesting the object. */ public abstract Animation getAnimation(); /** * Performs extra checks that a specific harvest event independently uses, e.g. checking for a pickaxe in mining. */ public abstract boolean canHarvest(); /** * This starts the actions animation and requirement checks, but prevents the harvest from immediately executing. */ private boolean started = false; /** * The current cycle time. */ private int currentCycles = 0; /** * The amount of cycles before an animation. */ private int lastAnimation = 0; @Override public CancelPolicy getCancelPolicy() { return CancelPolicy.ALWAYS; } @Override public StackPolicy getStackPolicy() { return StackPolicy.NEVER; } @Override public AnimationPolicy getAnimationPolicy() { return AnimationPolicy.RESET_ALL; } @Override public void execute() { final Item reward = getReward(); if(reward != null && !getMob().getInventory().hasRoomFor(reward)) { getMob().getActionSender().removeAllInterfaces().removeInterface2(); getMob().getActionSender().sendDialogue("", DialogueType.MESSAGE, -1, null, "You don't have enough inventory space for this."); getMob().playAnimation(Animation.create(-1)); this.stop(); return; } if(getMob().getSkills().getLevelForExperience(getSkill()) < getRequiredLevel()) { getMob().getActionSender().removeAllInterfaces().removeInterface2(); getMob().getActionSender().sendDialogue("", DialogueType.MESSAGE, -1, null, getLevelTooLowMessage()); getMob().playAnimation(Animation.create(-1)); this.stop(); return; } if(!canHarvest()) { this.stop(); return; } if(!started) { started = true; getMob().playAnimation(getAnimation()); getMob().getActionSender().sendMessage(getHarvestStartedMessage()); if(getGameObject().getMaxHealth() == 0) { getGameObject().setMaxHealth(getGameObjectMaxHealth()); } currentCycles = getCycleCount(); return; } if(lastAnimation > 3) { getMob().playAnimation(getAnimation()); //keeps the emote playing lastAnimation = 0; } lastAnimation++; if(currentCycles > 0) { currentCycles--; return; } //execute currentCycles = getCycleCount(); getGameObject().decreaseCurrentHealth(1); //decreases the health by one, e.g. lost a logging getMob().getActionSender().sendMessage(getSuccessfulHarvestMessage()); if (reward != null) { getMob().getInventory().add(reward); onSuccessfulHarvest(reward); } getMob().getSkills().addExperience(getSkill(), getExperience()); if(getGameObject().getCurrentHealth() < 1) { getGameObject().setCurrentHealth(getGameObjectMaxHealth()); //sets its health back to max for when it respawns World.getWorld().replaceObject(getGameObject(), getReplacementObject(), getObjectRespawnTimer()); getMob().playAnimation(Animation.create(-1)); this.stop(); //stops the action as the object is completely harvested. return; } if(reward != null && !getMob().getInventory().hasRoomFor(reward)) { //getMob().getActionSender().sendString(210, 0, getInventoryFullMessage()); //getMob().getActionSender().sendChatboxInterface(210); getMob().getActionSender().sendDialogue("", DialogueType.MESSAGE, -1, null, getInventoryFullMessage()); getMob().playAnimation(Animation.create(-1)); this.stop(); return; } if(getGameObject().getCurrentHealth() < 1) { this.stop(); return; } } }
zincware/ZnTrack
tests/unit_tests/utlis/test_helpers.py
<reponame>zincware/ZnTrack import pytest from zntrack import Node from zntrack.utils import helpers class MyNode(Node): def run(self): pass @pytest.mark.parametrize( ("node", "true_val"), [ (MyNode(), True), (MyNode, True), ([MyNode, MyNode], True), ([MyNode(), MyNode()], True), ("Node", False), (["Node", MyNode()], True), ], ) def test_isnode(node, true_val): assert helpers.isnode(node) == true_val
alekseiliachko/memium_react
src/pages/404.js
import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import { Typography } from "@material-ui/core"; import { useHistory } from "react-router-dom"; const useStyles = makeStyles(() => ({ circleWrap: { width: "100%", height: "100%", display: "flex", alignItems: "center", flexDirection: "column", justifyContent: "center", }, goHome: { color: "blue", cursor: "pointer", }, })); export const NotFound = () => { const history = useHistory(); const classes = useStyles(); return ( <div className={classes.circleWrap}> <Typography variant="h4">404</Typography> <Typography variant="h5">Страница не найдена</Typography> <Typography onClick={() => history.push("/home")} className={classes.goHome} variant="h5" > Домой </Typography> </div> ); };
qsw1214/spring-notes
spring-ioc/src/main/java/org/zp/notes/spring/ioc/annotation/life/Auditorium.java
<reponame>qsw1214/spring-notes<filename>spring-ioc/src/main/java/org/zp/notes/spring/ioc/annotation/life/Auditorium.java package org.zp.notes.spring.ioc.annotation.life; public class Auditorium { public void work() { System.out.println("工作"); } public void turnOnLight() { System.out.println("开灯"); } public void turnOffLight() { System.out.println("关灯"); } }
ckamtsikis/cmssw
L1Trigger/TrackFindingTracklet/interface/Sector.h
<reponame>ckamtsikis/cmssw //This class holds functional blocks of a sector #ifndef L1Trigger_TrackFindingTracklet_interface_Sector_h #define L1Trigger_TrackFindingTracklet_interface_Sector_h #include "L1Trigger/TrackFindingTracklet/interface/L1TStub.h" #include "L1Trigger/TrackFindingTracklet/interface/SLHCEvent.h" #include <string> #include <map> #include <memory> #include <vector> #include <unordered_set> #include <fstream> namespace trklet { class Settings; class Globals; class ProcessBase; class MemoryBase; class Tracklet; class Track; class Stub; //Memory modules class InputLinkMemory; class AllStubsMemory; class VMStubsTEMemory; class VMStubsMEMemory; class StubPairsMemory; class StubTripletsMemory; class TrackletParametersMemory; class TrackletProjectionsMemory; class AllProjectionsMemory; class VMProjectionsMemory; class CandidateMatchMemory; class FullMatchMemory; class TrackFitMemory; class CleanTrackMemory; //Processing modules class VMRouter; class VMRouterCM; class TrackletEngine; class TrackletEngineDisplaced; class TripletEngine; class TrackletCalculator; class TrackletProcessor; class TrackletCalculatorDisplaced; class ProjectionRouter; class MatchEngine; class MatchCalculator; class MatchProcessor; class FitTrack; class PurgeDuplicate; class Sector { public: Sector(unsigned int i, Settings const& settings, Globals* globals); ~Sector(); bool addStub(L1TStub stub, std::string dtc); //TODO - should be pointer or string // Creates all required memory modules based on wiring map (args: module type, module instance) void addMem(std::string memType, std::string memName); // Creates all required processing modules based on wiring map (args: module type, module instance) void addProc(std::string procType, std::string procName); //--- Create all required proc -> mem module connections, based on wiring map //--- (args: memory instance & input/output proc modules it connects to in format procName.pinName) void addWire(std::string mem, std::string procinfull, std::string procoutfull); ProcessBase* getProc(std::string procName); MemoryBase* getMem(std::string memName); void writeInputStubs(bool first); void writeVMSTE(bool first); void writeVMSME(bool first); void writeAS(bool first); void writeSP(bool first); void writeST(bool first); void writeTPAR(bool first); void writeTPROJ(bool first); void writeAP(bool first); void writeVMPROJ(bool first); void writeCM(bool first); void writeMC(bool first); void writeTF(bool first); void writeCT(bool first); void clean(); // execute the different tracklet processing modules void executeVMR(); void executeTE(); void executeTED(); void executeTRE(); void executeTP(); void executeTC(); void executeTCD(); void executePR(); void executeME(); void executeMC(); void executeMP(); void executeFT(); void executePD(std::vector<Track*>& tracks); std::vector<Tracklet*> getAllTracklets() const; std::vector<const Stub*> getStubs() const; std::unordered_set<int> seedMatch(int itp) const; double phimin() const { return phimin_; } double phimax() const { return phimax_; } template <typename TV, typename... Args> void addMemToVec(std::vector<std::unique_ptr<TV> >& memvec, const std::string& memName, Args&... args) { memvec.push_back(std::make_unique<TV>(memName, std::forward<Args>(args)...)); Memories_[memName] = memvec.back().get(); MemoriesV_.push_back(memvec.back().get()); } template <typename TV, typename... Args> void addProcToVec(std::vector<std::unique_ptr<TV> >& procvec, const std::string& procName, Args&... args) { procvec.push_back(std::make_unique<TV>(procName, std::forward<Args>(args)...)); Processes_[procName] = procvec.back().get(); } private: int isector_; Settings const& settings_; Globals* globals_; double phimin_; double phimax_; std::map<std::string, MemoryBase*> Memories_; std::vector<MemoryBase*> MemoriesV_; std::vector<std::unique_ptr<InputLinkMemory> > IL_; std::vector<std::unique_ptr<AllStubsMemory> > AS_; std::vector<std::unique_ptr<VMStubsTEMemory> > VMSTE_; std::vector<std::unique_ptr<VMStubsMEMemory> > VMSME_; std::vector<std::unique_ptr<StubPairsMemory> > SP_; std::vector<std::unique_ptr<StubTripletsMemory> > ST_; std::vector<std::unique_ptr<TrackletParametersMemory> > TPAR_; std::vector<std::unique_ptr<TrackletProjectionsMemory> > TPROJ_; std::vector<std::unique_ptr<AllProjectionsMemory> > AP_; std::vector<std::unique_ptr<VMProjectionsMemory> > VMPROJ_; std::vector<std::unique_ptr<CandidateMatchMemory> > CM_; std::vector<std::unique_ptr<FullMatchMemory> > FM_; std::vector<std::unique_ptr<TrackFitMemory> > TF_; std::vector<std::unique_ptr<CleanTrackMemory> > CT_; std::map<std::string, ProcessBase*> Processes_; std::vector<std::unique_ptr<VMRouter> > VMR_; std::vector<std::unique_ptr<VMRouterCM> > VMRCM_; std::vector<std::unique_ptr<TrackletEngine> > TE_; std::vector<std::unique_ptr<TrackletEngineDisplaced> > TED_; std::vector<std::unique_ptr<TripletEngine> > TRE_; std::vector<std::unique_ptr<TrackletProcessor> > TP_; std::vector<std::unique_ptr<TrackletCalculator> > TC_; std::vector<std::unique_ptr<TrackletCalculatorDisplaced> > TCD_; std::vector<std::unique_ptr<ProjectionRouter> > PR_; std::vector<std::unique_ptr<MatchEngine> > ME_; std::vector<std::unique_ptr<MatchCalculator> > MC_; std::vector<std::unique_ptr<MatchProcessor> > MP_; std::vector<std::unique_ptr<FitTrack> > FT_; std::vector<std::unique_ptr<PurgeDuplicate> > PD_; }; }; // namespace trklet #endif
Jeonghum/hfdpcpp11
factory/simple_factory/lib/cheese_pizza.cpp
<gh_stars>1-10 //===--- cheese_pizza.cpp - -------------------------------------*- C++ -*-===// // // Head First Design Patterns // // //===----------------------------------------------------------------------===// /// /// \file /// \brief /// //===----------------------------------------------------------------------===// //https://google.github.io/styleguide/cppguide.html#Names_and_Order_of_Includes //dir2 / foo2.h. #include "cheese_pizza.hpp" //C system files. //C++ system files. #include <iostream> //Other libraries' .h files. //Your project's .h files. namespace headfirst { CheesePizza::CheesePizza() { std::cout << "CheesePizza::CheesePizza" << std::endl; name_ = "Cheese Pizza"; dough_ = "Regular Crust"; sauce_ = "Marinara Pizza Sauce"; toppings_.push_back( "Shredded Mozzarella" ); toppings_.push_back( "Parmesan" ); } } //namespace headfirst
kvadro1/filedossier
filedossier-document-validation/src/main/java/ru/ilb/filedossier/filedossier/document/validation/SignatureDetector.java
/* * Copyright 2019 kuznetsov_me. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.ilb.filedossier.filedossier.document.validation; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.naming.InitialContext; import javax.naming.NamingException; import ru.ilb.filedossier.functions.MapRuntimeFunction; /** * SignatureDetector checks for signatures each page of PDF document by comparing original PDF page with image scan. This class is a wrapper over python script, call it by * MapRuntimeFunction with request arguments and receives is exist value for each signature in JSON format. * <p> * SignatureDetector request is a JSON structure in the form of {@code Map<String, Object>}. It's contains path of original page, path of scan page and set of areas, where * signatures should be detected. * * @see ru.ilb.filedossier.functions.MapRuntimeFunction * @author kuznetsov_me */ public class SignatureDetector { /** * URI of the signature detector script. */ private URI signatureDetectorUri; /** * Request data for the script in the form of {@code Map<String, Object>}. Such a structure is easy to convert to/from JSON. */ private Map<String, Object> requestMap; private SignatureDetector() throws NamingException { InitialContext context = new InitialContext(); signatureDetectorUri = URI.create((String) context.lookup( "java:comp/env/ru.bystrobank.apps.documentsignaturedetector.uri")); } /** * @return List of "is detected" boolean values of each signature areas. */ public List<Boolean> detectSignatures() { if (signatureDetectorUri == null) { throw new IllegalStateException("Command URI not specified"); } List<Map<String, Object>> signatures = (LinkedList) new MapRuntimeFunction( signatureDetectorUri) .apply(requestMap) .get("signatures"); return signatures.stream() .map(signature -> (boolean) signature.get("detected")) .collect(Collectors.toList()); } public static RequestBuilder newRequestBuilder() { try { return new SignatureDetector().new RequestBuilder(); } catch (NamingException e) { throw new RuntimeException("Bad document signature detector URI: " + e); } } /** * Builds SignatureDetector with request arguments map. */ public class RequestBuilder { /** * Original PDF page path */ private String pdfPath; private String scanPath; private List<DocumentArea> signatureAreas; private RequestBuilder() { signatureAreas = new ArrayList<>(); } public RequestBuilder withPDFPage(byte[] pdfPage) throws IOException { Path tempFile = Files.createTempFile("pdfpage", "jpg"); Files.write(tempFile, pdfPage); this.pdfPath = tempFile.toString(); return this; } public RequestBuilder withScanPage(byte[] scanPage) throws IOException { Path tempFile = Files.createTempFile("scanpage", "jpg"); Files.write(tempFile, scanPage); this.scanPath = tempFile.toString(); return this; } public RequestBuilder withSignatureAreas(List<DocumentArea> signatureAreas) { this.signatureAreas = signatureAreas; return this; } /** * Converts specified values into Map structure. */ private Map<String, Object> createRequestMap() { try { Map<String, Object> requestMap = new HashMap<>(); requestMap.put("signatures", signatureAreas.stream() .map(signatureArea -> signatureArea.asMap()) .collect(Collectors.toList())); requestMap.put("pdf_page", Optional.of(pdfPath) .orElseThrow(NullPointerException::new)); requestMap.put("scan_page", Optional.of(scanPath) .orElseThrow(NullPointerException::new)); return requestMap; } catch (NullPointerException e) { throw new IllegalArgumentException("One of the arguments isn't set: " + e); } } public SignatureDetector build() { SignatureDetector.this.requestMap = createRequestMap(); return SignatureDetector.this; } } }
tschuls/ETH-SegReg-DLL
source/SimultaneousRegistrationSegmentation/Legacy/SRS3D-Bone.cxx
<reponame>tschuls/ETH-SegReg-DLL #include <stdio.h> #include <iostream> #include "ArgumentParser.h" #include "SRSConfig.h" #include "HierarchicalSRSImageToImageFilter.h" #include "Graph.h" #include "SubsamplingGraph.h" #include "FastRegistrationGraph.h" #include "BaseLabel.h" #include "Potential-Registration-Unary.h" #include "Potential-Registration-Pairwise.h" #include "Potential-Segmentation-Unary.h" #include "Potential-Coherence-Pairwise.h" #include "Potential-Segmentation-Pairwise.h" #include "MRF-TRW-S.h" #include "Log.h" #include "Preprocessing.h" #include "TransformationUtils.h" using namespace std; using namespace itk; int main(int argc, char ** argv) { feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW); SRSConfig filterConfig; filterConfig.parseParams(argc,argv); //define types. typedef short int PixelType; const unsigned int D=3; typedef Image<PixelType,D> ImageType; typedef ImageType::Pointer ImagePointerType; typedef ImageType::ConstPointer ImageConstPointerType; typedef TransfUtils<ImageType>::DisplacementType DisplacementType; typedef SparseRegistrationLabelMapper<ImageType,DisplacementType> LabelMapperType; //typedef DenseRegistrationLabelMapper<ImageType,DisplacementType> LabelMapperType; typedef TransfUtils<ImageType>::DeformationFieldType DeformationFieldType; typedef DeformationFieldType::Pointer DeformationFieldPointerType; typedef ImageUtils<ImageType>::FloatImageType FloatImageType; typedef ImageUtils<ImageType>::FloatImagePointerType FloatImagePointerType; //unary seg //typedef SegmentationClassifierGradient<ImageType> ClassifierType; //typedef SegmentationGenerativeClassifierGradient<ImageType> ClassifierType; //typedef SegmentationClassifier<ImageType> ClassifierType; //typedef UnaryPotentialSegmentationClassifier< ImageType, ClassifierType > SegmentationUnaryPotentialType; typedef UnaryPotentialSegmentationBoneMarcel< ImageType > SegmentationUnaryPotentialType; //typedef UnaryPotentialSegmentation< ImageType > SegmentationUnaryPotentialType; //pairwise seg // typedef UnaryPotentialSegmentation< ImageType > SegmentationUnaryPotentialType; typedef SmoothnessClassifierGradient<ImageType> SegmentationSmoothnessClassifierType; //typedef SmoothnessClassifierGradientContrast<ImageType> SegmentationSmoothnessClassifierType; //typedef SmoothnessClassifierFullMultilabelPosterior<ImageType> SegmentationSmoothnessClassifierType; typedef PairwisePotentialSegmentationClassifier<ImageType,SegmentationSmoothnessClassifierType> SegmentationPairwisePotentialType; //typedef PairwisePotentialSegmentationMarcel<ImageType> SegmentationPairwisePotentialType; //reg //typedef UnaryPotentialRegistrationSAD< LabelMapperType, ImageType > RegistrationUnaryPotentialType; //typedef FastUnaryPotentialRegistrationNCC< LabelMapperType, ImageType > RegistrationUnaryPotentialType; typedef UnaryPotentialRegistrationNCC< LabelMapperType, ImageType > RegistrationUnaryPotentialType; //typedef UnaryPotentialRegistrationNCCWithBonePrior< LabelMapperType, ImageType > RegistrationUnaryPotentialType; //typedef UnaryPotentialRegistrationNCCWithDistanceBonePrior< LabelMapperType, ImageType > RegistrationUnaryPotentialType; typedef PairwisePotentialRegistration< LabelMapperType, ImageType > RegistrationPairwisePotentialType; typedef PairwisePotentialCoherence< ImageType > CoherencePairwisePotentialType; //typedef PairwisePotentialCoherenceBinary< ImageType > CoherencePairwisePotentialType; //typedef PairwisePotentialBoneCoherence< ImageType > CoherencePairwisePotentialType; //typedef FastRegistrationGraphModel< // typedef SortedSubsamplingGraphModel< typedef GraphModel< ImageType, RegistrationUnaryPotentialType, RegistrationPairwisePotentialType, SegmentationUnaryPotentialType, SegmentationPairwisePotentialType, CoherencePairwisePotentialType, LabelMapperType> GraphType; typedef HierarchicalSRSImageToImageFilter<GraphType> FilterType; //create filter FilterType::Pointer filter=FilterType::New(); filter->setConfig(filterConfig); logSetStage("IO"); logSetVerbosity(filterConfig.verbose); LOG<<"Loading target image :"<<filterConfig.targetFilename<<std::endl; ImagePointerType targetImage=ImageUtils<ImageType>::readImage(filterConfig.targetFilename); if (!targetImage) {LOG<<"failed!"<<endl; exit(0);} LOG<<"Loading atlas image :"<<filterConfig.atlasFilename<<std::endl; ImagePointerType atlasImage=ImageUtils<ImageType>::readImage(filterConfig.atlasFilename); if (!atlasImage) {LOG<<"failed!"<<endl; exit(0); LOG<<"Loading atlas segmentation image :"<<filterConfig.atlasSegmentationFilename<<std::endl;} ImagePointerType atlasSegmentation=ImageUtils<ImageType>::readImage(filterConfig.atlasSegmentationFilename); if (!atlasSegmentation) {LOG<<"failed!"<<endl; exit(0);} logSetStage("Preprocessing"); //preprocessing 1: gradients ImagePointerType targetGradient, atlasGradient; ImagePointerType tissuePrior; if (filterConfig.segment){ if (filterConfig.targetGradientFilename!=""){ targetGradient=(ImageUtils<ImageType>::readImage(filterConfig.targetGradientFilename)); }else{ targetGradient=Preprocessing<ImageType>::computeSheetness(targetImage); ImageUtils<ImageType>::writeImage("targetsheetness.nii",targetGradient); } if (filterConfig.atlasGradientFilename!=""){ atlasGradient=(ImageUtils<ImageType>::readImage(filterConfig.atlasGradientFilename)); }else{ atlasGradient=Preprocessing<ImageType>::computeSheetness(atlasImage); ImageUtils<ImageType>::writeImage("atlassheetness.nii",atlasGradient); } if (filterConfig.useTissuePrior){ tissuePrior=Preprocessing<ImageType>::computeSoftTissueEstimate(targetImage); } //preprocessing 2: multilabel if (filterConfig.computeMultilabelAtlasSegmentation){ atlasSegmentation=FilterUtils<ImageType>::computeMultilabelSegmentation(atlasSegmentation); filterConfig.nSegmentations=5;//TODO!!!! } } ImagePointerType originalTargetImage=targetImage,originalAtlasImage=atlasImage,originalAtlasSegmentation=atlasSegmentation; //preprocessing 3: downscaling if (filterConfig.downScale<1){ double sigma=0.5; double scale=filterConfig.downScale; LOG<<"Resampling images from "<< targetImage->GetLargestPossibleRegion().GetSize()<<" by a factor of"<<scale<<endl; targetImage=FilterUtils<ImageType>::LinearResample(FilterUtils<ImageType>::gaussian((ImageConstPointerType)targetImage,sigma),scale); atlasImage=FilterUtils<ImageType>::LinearResample(FilterUtils<ImageType>::gaussian((ImageConstPointerType)atlasImage,sigma),scale); atlasSegmentation=FilterUtils<ImageType>::NNResample((atlasSegmentation),scale); if (filterConfig.segment){ targetGradient=FilterUtils<ImageType>::LinearResample(FilterUtils<ImageType>::gaussian((ImageConstPointerType)targetGradient,sigma),scale); atlasGradient=FilterUtils<ImageType>::LinearResample(FilterUtils<ImageType>::gaussian((ImageConstPointerType)atlasGradient,sigma),scale); if (filterConfig.useTissuePrior){ tissuePrior=FilterUtils<ImageType>::LinearResample(FilterUtils<ImageType>::gaussian((ImageConstPointerType)(targetImage),sigma),scale); } } } logResetStage; filter->setTargetImage(targetImage); filter->setTargetGradient(targetGradient); filter->setAtlasImage(atlasImage); filter->setAtlasGradient(atlasGradient); filter->setAtlasSegmentation(atlasSegmentation); if (filterConfig.useTissuePrior){ filter->setTissuePrior(tissuePrior); } if (filterConfig.affineBulkTransform!=""){ TransfUtils<ImageType>::AffineTransformPointerType affine=TransfUtils<ImageType>::readAffine(filterConfig.affineBulkTransform); ImageUtils<ImageType>::writeImage("def.nii",TransfUtils<ImageType>::affineDeformImage(originalAtlasImage,affine,originalTargetImage)); DeformationFieldPointerType transf=TransfUtils<ImageType>::affineToDisplacementField(affine,originalTargetImage); ImageUtils<ImageType>::writeImage("def2.nii",TransfUtils<ImageType>::warpImage((ImageType::ConstPointer)originalAtlasImage,transf)); filter->setBulkTransform(transf); } else if (filterConfig.bulkTransformationField!=""){ filter->setBulkTransform(ImageUtils<DeformationFieldType>::readImage(filterConfig.bulkTransformationField)); }else{ LOG<<"Computing transform to move image centers on top of each other.."<<std::endl; DeformationFieldPointerType transf=TransfUtils<ImageType>::computeCenteringTransform(originalTargetImage,originalAtlasImage); filter->setBulkTransform(transf); } // compute SRS clock_t FULLstart = clock(); filter->Update(); logSetStage("Finalizing"); clock_t FULLend = clock(); float t = (float) ((double)(FULLend - FULLstart) / CLOCKS_PER_SEC); LOG<<"Finished computation after "<<t<<" seconds"<<std::endl; LOG<<"RegUnaries: "<<tUnary<<" Optimization: "<<tOpt<<std::endl; LOG<<"RegPairwise: "<<tPairwise<<std::endl; //process outputs ImagePointerType targetSegmentationEstimate=filter->getTargetSegmentationEstimate(); DeformationFieldPointerType finalDeformation=filter->getFinalDeformation(); //upsample? if (filterConfig.downScale<1){ LOG<<"Upsampling Images.."<<endl; finalDeformation=TransfUtils<ImageType>::bSplineInterpolateDeformationField(finalDeformation,(ImageConstPointerType)originalTargetImage); //this is more or less f***** up //it would probably be far better to create a surface for each label, 'upsample' that surface, and then create a binary volume for each surface which are merged in a last step if (targetSegmentationEstimate){ FloatImagePointerType distanceMap=FilterUtils<ImageType,FloatImageType>::distanceMapByFastMarcher(FilterUtils<ImageType>::binaryThresholdingLow(targetSegmentationEstimate,1),1); targetSegmentationEstimate=FilterUtils<FloatImageType,ImageType>::binaryThresholdingHigh(FilterUtils<FloatImageType>::LinearResample(distanceMap,FilterUtils<ImageType,FloatImageType>::cast(originalTargetImage)),0); //targetSegmentationEstimate=FilterUtils<ImageType>::round(FilterUtils<ImageType>::NNResample((targetSegmentationEstimate),scale)); } } LOG<<"Deforming Images.."<<endl; if (filterConfig.defFilename!=""){ ImageUtils<DeformationFieldType>::writeImage(filterConfig.defFilename,finalDeformation); } ImagePointerType deformedAtlasSegmentation=TransfUtils<ImageType>::warpImage((ImageConstPointerType)originalAtlasSegmentation,finalDeformation,true); ImagePointerType deformedAtlasImage=TransfUtils<ImageType>::warpImage((ImageConstPointerType)originalAtlasImage,finalDeformation); ImageUtils<ImageType>::writeImage(filterConfig.outputDeformedFilename,deformedAtlasImage); if (ImageType::ImageDimension==2){ if (targetSegmentationEstimate) ImageUtils<ImageType>::writeImage(filterConfig.segmentationOutputFilename,filter->makePngFromDeformationField((ImageConstPointerType)targetSegmentationEstimate,LabelMapperType::nSegmentations)); ImageUtils<ImageType>::writeImage(filterConfig.outputDeformedSegmentationFilename,filter->makePngFromDeformationField((ImageConstPointerType)deformedAtlasSegmentation,LabelMapperType::nSegmentations)); } if (ImageType::ImageDimension==3){ if (targetSegmentationEstimate) ImageUtils<ImageType>::writeImage(filterConfig.segmentationOutputFilename,targetSegmentationEstimate); ImageUtils<ImageType>::writeImage(filterConfig.outputDeformedSegmentationFilename,deformedAtlasSegmentation); } LOG<<"Final SAD: "<<ImageUtils<ImageType>::sumAbsDist((ImageConstPointerType)deformedAtlasImage,(ImageConstPointerType)targetImage)<<endl; return 1; }
githubwua/cdap
cdap-ui/app/cdap/components/Cloud/Profiles/DetailView/Content/index.js
/* * Copyright © 2018 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import React from 'react'; import ProfileDetailViewBasicInfo from 'components/Cloud/Profiles/DetailView/Content/BasicInfo'; import ProfileDetailViewDetailsInfo from 'components/Cloud/Profiles/DetailView/Content/DetailsInfo'; import ProfileAssociations from 'components/Cloud/Profiles/DetailView/Content/ProfileAssociations'; require('./Content.scss'); export default function ProfileDetailViewContent({ ...props }) { return ( <div className="detail-view-content"> <ProfileDetailViewBasicInfo {...props} /> <hr /> <ProfileDetailViewDetailsInfo {...props} /> <br /> <ProfileAssociations {...props} /> </div> ); }
mohammedsuhail85/CSSE-Group19-SprigAPI
SpringBackendAPI/src/main/java/lk/sliit/csse/group19/springApi/SpringBackendAPI/Model/Invoice.java
/** * Invoice Table Model */ package lk.sliit.csse.group19.springApi.SpringBackendAPI.Model; import java.sql.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * @author Dev * */ @Entity public class Invoice { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private int purchaseOrderId; private int supplierId; private double totalPrice; private String invoiceComment; private Date issueDate; public int getId() { return id; } public int getPurchaseOrderId() { return purchaseOrderId; } public int getSupplierId() { return supplierId; } public double getTotalPrice() { return totalPrice; } public String getInvoiceComment() { return invoiceComment; } public Date getIssueDate() { return issueDate; } public void setId(int id) { this.id = id; } public void setPurchaseOrderId(int purchaseOrderId) { this.purchaseOrderId = purchaseOrderId; } public void setSupplierId(int supplierId) { this.supplierId = supplierId; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public void setInvoiceComment(String invoiceComment) { this.invoiceComment = invoiceComment; } public void setIssueDate(Date issueDate) { this.issueDate = issueDate; } }
gitofolio/gitofolio
gitofolio-api-server/src/main/java/com/gitofolio/api/service/factory/mapper/PortfolioCardMapper.java
package com.gitofolio.api.service.factory.mapper; import com.gitofolio.api.domain.user.UserInfo; import com.gitofolio.api.service.user.dtos.UserDTO; import com.gitofolio.api.service.user.dtos.PortfolioCardDTO; import com.gitofolio.api.domain.user.PortfolioCard; import com.gitofolio.api.service.common.secure.XssProtector; import org.springframework.transaction.annotation.Transactional; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import java.util.ArrayList; @Service public class PortfolioCardMapper implements UserMapper<List<PortfolioCard>>{ private final XssProtector xssProtector; @Override public UserDTO doMap(List<PortfolioCard> portfolioCards){ List<PortfolioCardDTO> cards = new ArrayList<PortfolioCardDTO>(portfolioCards.size()); for(PortfolioCard card : portfolioCards){ cards.add(new PortfolioCardDTO.Builder() .portfolioCard(card) .build()); } return new UserDTO.Builder() .userInfo(portfolioCards.get(0).getUserInfo()) .portfolioCardDTOs(cards) .build(); } @Override public List<PortfolioCard> resolveMap(UserDTO userDTO){ UserInfo mockUserInfo = getMockUserInfo(userDTO); List<PortfolioCard> portfolioCards = new ArrayList<PortfolioCard>(); List<PortfolioCardDTO> portfolioCardDTOs = userDTO.getPortfolioCards(); for(PortfolioCardDTO cardDTO : portfolioCardDTOs){ PortfolioCard portfolioCard = new PortfolioCard(); try{ portfolioCard.setId(cardDTO.getId()); }catch(NullPointerException NPE){ portfolioCard.setId(-1L); } portfolioCard.setPortfolioCardArticle(cardDTO.getPortfolioCardArticle()); portfolioCard.setPortfolioCardWatched(0); portfolioCard.setPortfolioUrl(cardDTO.getPortfolioUrl()); portfolioCard.setUserInfo(mockUserInfo); portfolioCards.add(portfolioCard); } return portfolioCards; } private UserInfo getMockUserInfo(UserDTO userDTO){ UserInfo mockUserInfo = new UserInfo(); mockUserInfo.setName(userDTO.getName()); try{ mockUserInfo.setId(userDTO.getId()); }catch(NullPointerException NPE){ mockUserInfo.setId(-1L); } return mockUserInfo; } @Autowired public PortfolioCardMapper(XssProtector xssProtector){ this.xssProtector = xssProtector; } }
brian-kelley/seacas
packages/seacas/libraries/exodus/src/ex_put_reduction_variable_param.c
<reponame>brian-kelley/seacas /* * Copyright (c) 2019 National Technology & Engineering Solutions * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with * NTESS, the U.S. Government retains certain rights in this software. * * 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 NTESS nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "exodusII.h" // for ex_err, etc #include "exodusII_int.h" // for ex__compress_variable, etc /*! \cond INTERNAL */ static int ex__prepare_result_var(int exoid, int num_vars, char *type_name, char *dim_name, char *variable_name) { int status; int dimid; int varid; int dims[2]; int dim_str_name; #if NC_HAS_HDF5 int fill = NC_FILL_CHAR; #endif char errmsg[MAX_ERR_LENGTH]; if ((status = nc_def_dim(exoid, dim_name, num_vars, &dimid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: %s variable name parameters are already defined " "in file id %d", type_name, exoid); ex_err_fn(exoid, __func__, errmsg, status); } else { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define number of %s variables in file id %d", type_name, exoid); ex_err_fn(exoid, __func__, errmsg, status); } return (EX_FATAL); /* exit define mode and return */ } /* Now define type_name variable name variable */ if ((status = nc_inq_dimid(exoid, DIM_STR_NAME, &dim_str_name)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get string length in file id %d", exoid); ex_err_fn(exoid, __func__, errmsg, status); return (EX_FATAL); } dims[0] = dimid; dims[1] = dim_str_name; if ((status = nc_def_var(exoid, variable_name, NC_CHAR, 2, dims, &varid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: %s variable names are already defined in file id %d", type_name, exoid); ex_err_fn(exoid, __func__, errmsg, status); } else { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define %s variable names in file id %d", type_name, exoid); ex_err_fn(exoid, __func__, errmsg, status); } return (EX_FATAL); /* exit define mode and return */ } #if NC_HAS_HDF5 nc_def_var_fill(exoid, varid, 0, &fill); #endif return (EX_NOERR); } /*! \endcond */ /*! \ingroup ResultsData The function ex_put_variable_param() writes the number of global, nodal, nodeset, sideset, edge, face, or element variables that will be written to the database. \return In case of an error, ex_put_variable_param() returns a negative number; a warning will return a positive number. Possible causes of errors include: - data file not properly opened with call to ex_create() or ex_open() - data file opened for read only. - invalid variable type specified. - data file not initialized properly with call to ex_put_init(). - this routine has already been called with the same variable type; redefining the number of variables is not allowed. - a warning value is returned if the number of variables is specified as zero. \param[in] exoid exodus file ID returned from a previous call to ex_create() or ex_open(). \param[in] obj_type Variable indicating the type of variable which is described. Use one of the #ex_entity_type types specified in the table below. \param[in] num_vars The number of var_type variables that will be written to the database. | ex_entity_type| description | |---------------|---------------------------| | #EX_GLOBAL | Global entity type | | #EX_NODE_SET | Node Set entity type | | #EX_EDGE_BLOCK | Edge Block entity type | | #EX_EDGE_SET | Edge Set entity type | | #EX_FACE_BLOCK | Face Block entity type | | #EX_FACE_SET | Face Set entity type | | #EX_ELEM_BLOCK | Element Block entity type| | #EX_ELEM_SET | Element Set entity type | | #EX_SIDE_SET | Side Set entity type | For example, the following code segment initializes the data file to store global variables: ~~~{.c} int num_glo_vars, error, exoid; \comment{write results variables parameters} num_glo_vars = 3; error = ex_put_variable_param (exoid, EX_GLOBAL, num_glo_vars); ~~~ */ int ex_put_reduction_variable_param(int exoid, ex_entity_type obj_type, int num_vars) { int time_dim, dimid, dim_str_name, varid; int dims[3]; char errmsg[MAX_ERR_LENGTH]; int status; EX_FUNC_ENTER(); ex__check_valid_file_id(exoid, __func__); /* if no variables are to be stored, return with warning */ if (num_vars == 0) { snprintf(errmsg, MAX_ERR_LENGTH, "Warning: zero %s variables specified for file id %d", ex_name_of_object(obj_type), exoid); ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM); EX_FUNC_LEAVE(EX_WARN); } if (obj_type != EX_NODE_SET && obj_type != EX_EDGE_BLOCK && obj_type != EX_EDGE_SET && obj_type != EX_FACE_BLOCK && obj_type != EX_FACE_SET && obj_type != EX_ELEM_BLOCK && obj_type != EX_ELEM_SET && obj_type != EX_SIDE_SET && obj_type != EX_GLOBAL && obj_type != EX_ASSEMBLY && obj_type != EX_BLOB) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: Invalid variable type %d specified in file id %d", obj_type, exoid); ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM); EX_FUNC_LEAVE(EX_WARN); } /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_TIME, &time_dim)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate time dimension in file id %d", exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } if ((status = nc_inq_dimid(exoid, DIM_STR_NAME, &dim_str_name)) < 0) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get name string length in file id %d", exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } /* put file into define mode */ if ((status = nc_redef(exoid)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to put file id %d into define mode", exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } /* define dimensions and variables */ if (obj_type == EX_GLOBAL) { if ((status = ex__prepare_result_var(exoid, num_vars, "global", DIM_NUM_GLO_VAR, VAR_NAME_GLO_VAR)) != EX_NOERR) { goto error_ret; } if ((status = nc_inq_dimid(exoid, DIM_NUM_GLO_VAR, &dimid)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get global variable count in file id %d", exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } dims[0] = time_dim; dims[1] = dimid; if ((status = nc_def_var(exoid, VAR_GLO_VAR, nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define global variables in file id %d", exoid); ex_err_fn(exoid, __func__, errmsg, status); goto error_ret; /* exit define mode and return */ } ex__compress_variable(exoid, varid, 2); } /* netCDF variables in which to store the EXODUS obj_type variable values will * be defined in ex_put_*_var_tab or ex_put_*_var; at this point, we * don't know what obj_type variables are valid for which obj_type blocks * (the info that is stored in the obj_type variable truth table) */ else if (obj_type == EX_ELEM_BLOCK) { if ((status = ex__prepare_result_var(exoid, num_vars, "element", DIM_NUM_ELE_RED_VAR, VAR_NAME_ELE_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_NODE_SET) { if ((status = ex__prepare_result_var(exoid, num_vars, "nodeset", DIM_NUM_NSET_RED_VAR, VAR_NAME_NSET_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_SIDE_SET) { if ((status = ex__prepare_result_var(exoid, num_vars, "sideset", DIM_NUM_SSET_RED_VAR, VAR_NAME_SSET_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_ASSEMBLY) { if ((status = ex__prepare_result_var(exoid, num_vars, "assembly", DIM_NUM_ASSEMBLY_RED_VAR, VAR_NAME_ASSEMBLY_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_BLOB) { if ((status = ex__prepare_result_var(exoid, num_vars, "blob", DIM_NUM_BLOB_RED_VAR, VAR_NAME_BLOB_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_EDGE_BLOCK) { if ((status = ex__prepare_result_var(exoid, num_vars, "edge", DIM_NUM_EDG_RED_VAR, VAR_NAME_EDG_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_FACE_BLOCK) { if ((status = ex__prepare_result_var(exoid, num_vars, "face", DIM_NUM_FAC_RED_VAR, VAR_NAME_FAC_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_EDGE_SET) { if ((status = ex__prepare_result_var(exoid, num_vars, "edgeset", DIM_NUM_ESET_RED_VAR, VAR_NAME_ESET_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_FACE_SET) { if ((status = ex__prepare_result_var(exoid, num_vars, "faceset", DIM_NUM_FSET_RED_VAR, VAR_NAME_FSET_RED_VAR)) != EX_NOERR) { goto error_ret; } } else if (obj_type == EX_ELEM_SET) { if ((status = ex__prepare_result_var(exoid, num_vars, "elementset", DIM_NUM_ELSET_RED_VAR, VAR_NAME_ELSET_RED_VAR)) != EX_NOERR) { goto error_ret; } } /* leave define mode */ if ((status = ex__leavedef(exoid, __func__)) != NC_NOERR) { EX_FUNC_LEAVE(EX_FATAL); } EX_FUNC_LEAVE(EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: ex__leavedef(exoid, __func__); EX_FUNC_LEAVE(EX_FATAL); }
Lutefisk3D/lutefisk3d
Source/ThirdParty/Box2D/Collision/Shapes/b2CircleShape.h
/* * Copyright (c) 2006-2009 <NAME> http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_CIRCLE_SHAPE_H #define B2_CIRCLE_SHAPE_H #include "Box2D/Collision/Shapes/b2Shape.h" /// A circle shape. class b2CircleShape : public b2Shape { public: b2CircleShape(); /// Implement b2Shape. b2Shape* Clone(b2BlockAllocator* allocator) const; /// @see b2Shape::GetChildCount int32 GetChildCount() const override; /// Implement b2Shape. bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override; /// Implement b2Shape. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform, int32 childIndex) const override; /// @see b2Shape::ComputeAABB void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override; /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const override; /// Get the supporting vertex index in the given direction. int32 GetSupport(const b2Vec2& d) const; /// Get the supporting vertex in the given direction. const b2Vec2& GetSupportVertex(const b2Vec2& d) const; /// Get the vertex count. int32 GetVertexCount() const { return 1; } /// Get a vertex by index. Used by b2Distance. const b2Vec2& GetVertex(int32 index) const; /// Position b2Vec2 m_p; }; inline b2CircleShape::b2CircleShape() { m_type = e_circle; m_radius = 0.0f; m_p.SetZero(); } inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const { B2_NOT_USED(d); return 0; } inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const { B2_NOT_USED(d); return m_p; } inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const { B2_NOT_USED(index); b2Assert(index == 0); return m_p; } #endif
scMarkus/zeppelin
rlang/src/main/java/org/apache/zeppelin/r/SparkRUtils.java
<reponame>scMarkus/zeppelin /* * 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 org.apache.zeppelin.r; import org.apache.zeppelin.interpreter.InterpreterException; import java.io.File; public class SparkRUtils { public static String getSparkRLib(boolean isSparkSupported) throws InterpreterException { String sparkRLibPath; if (System.getenv("SPARK_HOME") != null) { // local or yarn-client mode when SPARK_HOME is specified sparkRLibPath = System.getenv("SPARK_HOME") + "/R/lib"; } else if (System.getenv("ZEPPELIN_HOME") != null){ // embedded mode when SPARK_HOME is not specified or for native R support String interpreter = "r"; if (isSparkSupported) { interpreter = "spark"; } sparkRLibPath = System.getenv("ZEPPELIN_HOME") + "/interpreter/" + interpreter + "/R/lib"; // workaround to make sparkr work without SPARK_HOME System.setProperty("spark.test.home", System.getenv("ZEPPELIN_HOME") + "/interpreter/" + interpreter); } else { // yarn-cluster mode sparkRLibPath = "sparkr"; } if (!new File(sparkRLibPath).exists()) { throw new InterpreterException(String.format("sparkRLib '%s' doesn't exist", sparkRLibPath)); } return sparkRLibPath; } }
zhang-ray/audio-processing-module
independent_ns/src/complex_bit_reverse.cpp
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "signal_processing_library.hpp" /* Tables for data buffer indexes that are bit reversed and thus need to be * swapped. Note that, index_7[{0, 2, 4, ...}] are for the left side of the swap * operations, while index_7[{1, 3, 5, ...}] are for the right side of the * operation. Same for index_8. */ /* Indexes for the case of stages == 7. */ static const int16_t index_7[112] = { 1, 64, 2, 32, 3, 96, 4, 16, 5, 80, 6, 48, 7, 112, 9, 72, 10, 40, 11, 104, 12, 24, 13, 88, 14, 56, 15, 120, 17, 68, 18, 36, 19, 100, 21, 84, 22, 52, 23, 116, 25, 76, 26, 44, 27, 108, 29, 92, 30, 60, 31, 124, 33, 66, 35, 98, 37, 82, 38, 50, 39, 114, 41, 74, 43, 106, 45, 90, 46, 58, 47, 122, 49, 70, 51, 102, 53, 86, 55, 118, 57, 78, 59, 110, 61, 94, 63, 126, 67, 97, 69, 81, 71, 113, 75, 105, 77, 89, 79, 121, 83, 101, 87, 117, 91, 109, 95, 125, 103, 115, 111, 123 }; /* Indexes for the case of stages == 8. */ static const int16_t index_8[240] = { 1, 128, 2, 64, 3, 192, 4, 32, 5, 160, 6, 96, 7, 224, 8, 16, 9, 144, 10, 80, 11, 208, 12, 48, 13, 176, 14, 112, 15, 240, 17, 136, 18, 72, 19, 200, 20, 40, 21, 168, 22, 104, 23, 232, 25, 152, 26, 88, 27, 216, 28, 56, 29, 184, 30, 120, 31, 248, 33, 132, 34, 68, 35, 196, 37, 164, 38, 100, 39, 228, 41, 148, 42, 84, 43, 212, 44, 52, 45, 180, 46, 116, 47, 244, 49, 140, 50, 76, 51, 204, 53, 172, 54, 108, 55, 236, 57, 156, 58, 92, 59, 220, 61, 188, 62, 124, 63, 252, 65, 130, 67, 194, 69, 162, 70, 98, 71, 226, 73, 146, 74, 82, 75, 210, 77, 178, 78, 114, 79, 242, 81, 138, 83, 202, 85, 170, 86, 106, 87, 234, 89, 154, 91, 218, 93, 186, 94, 122, 95, 250, 97, 134, 99, 198, 101, 166, 103, 230, 105, 150, 107, 214, 109, 182, 110, 118, 111, 246, 113, 142, 115, 206, 117, 174, 119, 238, 121, 158, 123, 222, 125, 190, 127, 254, 131, 193, 133, 161, 135, 225, 137, 145, 139, 209, 141, 177, 143, 241, 147, 201, 149, 169, 151, 233, 155, 217, 157, 185, 159, 249, 163, 197, 167, 229, 171, 213, 173, 181, 175, 245, 179, 205, 183, 237, 187, 221, 191, 253, 199, 227, 203, 211, 207, 243, 215, 235, 223, 251, 239, 247 }; void WebRtcSpl_ComplexBitReverse(int16_t* __restrict complex_data, int stages) { /* For any specific value of stages, we know exactly the indexes that are * bit reversed. Currently (Feb. 2012) in WebRTC the only possible values of * stages are 7 and 8, so we use tables to save unnecessary iterations and * calculations for these two cases. */ if (stages == 7 || stages == 8) { int m = 0; int length = 112; const int16_t* index = index_7; if (stages == 8) { length = 240; index = index_8; } /* Decimation in time. Swap the elements with bit-reversed indexes. */ for (m = 0; m < length; m += 2) { /* We declare a int32_t* type pointer, to load both the 16-bit real * and imaginary elements from complex_data in one instruction, reducing * complexity. */ int32_t* complex_data_ptr = (int32_t*)complex_data; int32_t temp = 0; temp = complex_data_ptr[index[m]]; /* Real and imaginary */ complex_data_ptr[index[m]] = complex_data_ptr[index[m + 1]]; complex_data_ptr[index[m + 1]] = temp; } } else { int m = 0, mr = 0, l = 0; int n = 1 << stages; int nn = n - 1; /* Decimation in time - re-order data */ for (m = 1; m <= nn; ++m) { int32_t* complex_data_ptr = (int32_t*)complex_data; int32_t temp = 0; /* Find out indexes that are bit-reversed. */ l = n; do { l >>= 1; } while (l > nn - mr); mr = (mr & (l - 1)) + l; if (mr <= m) { continue; } /* Swap the elements with bit-reversed indexes. * This is similar to the loop in the stages == 7 or 8 cases. */ temp = complex_data_ptr[m]; /* Real and imaginary */ complex_data_ptr[m] = complex_data_ptr[mr]; complex_data_ptr[mr] = temp; } } }
ItsYoungDaddy/Templar-Cosmetics-Beta
src/main/java/tae/cosmetics/gui/util/packet/client/CPacketConfirmTransactionModule.java
<gh_stars>10-100 package tae.cosmetics.gui.util.packet.client; import java.awt.Color; import net.minecraft.network.play.client.CPacketConfirmTransaction; import tae.cosmetics.gui.util.packet.AbstractPacketModule; public class CPacketConfirmTransactionModule extends AbstractPacketModule { private CPacketConfirmTransaction packet; public CPacketConfirmTransactionModule(CPacketConfirmTransaction packet, long timestamp) { super("Supports ClickWindow Packets", timestamp, packet); this.packet = packet; } @Override public void drawText(int x, int y) { fontRenderer.drawString("CPacketConfirmTransaction", x, y, Color.WHITE.getRGB()); if(!minimized) { fontRenderer.drawString("UID: " + packet.getUid(), x, y + 14, Color.WHITE.getRGB()); fontRenderer.drawString("Window ID: " + packet.getWindowId(), x, y, Color.WHITE.getRGB()); } } @Override public boolean type() { return true; } }
majacQ/keywhiz
server/src/test/java/keywhiz/commands/DropDeletedSecretsCommandTest.java
package keywhiz.commands; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; import javax.inject.Inject; import keywhiz.KeywhizTestRunner; import keywhiz.api.ApiDate; import keywhiz.api.model.SecretContent; import keywhiz.api.model.SecretSeries; import keywhiz.api.model.SecretSeriesAndContent; import keywhiz.service.crypto.ContentCryptographer; import keywhiz.service.crypto.CryptoFixtures; import keywhiz.service.daos.SecretDAO; import net.sourceforge.argparse4j.inf.Namespace; import org.jooq.DSLContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toList; import static keywhiz.jooq.tables.Secrets.SECRETS; import static keywhiz.jooq.tables.SecretsContent.SECRETS_CONTENT; import static org.assertj.core.api.Assertions.assertThat; @RunWith(KeywhizTestRunner.class) public class DropDeletedSecretsCommandTest { @Inject private DSLContext jooqContext; @Inject private ObjectMapper objectMapper; @Inject private SecretDAO.SecretDAOFactory secretDAOFactory; private final static ContentCryptographer cryptographer = CryptoFixtures.contentCryptographer(); private final static ApiDate january18 = ApiDate.parse("2018-01-01T00:00:00Z"); private final static ApiDate january19 = ApiDate.parse("2019-01-01T00:00:00Z"); private ImmutableMap<String, String> emptyMetadata = ImmutableMap.of(); // an undeleted secret private SecretSeries series1 = SecretSeries.of(1, "secret1", "desc1", january18, "creator", january19, "updater", null, null, 101L); private String content = "c2VjcmV0MQ=="; private String encryptedContent = cryptographer.encryptionKeyDerivedFrom(series1.name()).encrypt(content); private SecretContent content1 = SecretContent.of(101, 1, encryptedContent, "checksum", january18, "creator", january18, "updater", emptyMetadata, 0); private SecretSeriesAndContent secret1 = SecretSeriesAndContent.of(series1, content1); // a secret deleted on 2018-01-01T00:00:00Z private SecretSeries series2 = SecretSeries.of(2, "secret2", "desc2", january18, "creator", january18, "updater", null, null, null); private SecretContent content2a = SecretContent.of(102, 2, encryptedContent, "checksum", january18, "creator", january18, "updater", emptyMetadata, 0); private SecretSeriesAndContent secret2a = SecretSeriesAndContent.of(series2, content2a); private SecretContent content2b = SecretContent.of(103, 2, "some other content", "checksum", january18, "creator", january18, "updater", emptyMetadata, 0); private SecretSeriesAndContent secret2b = SecretSeriesAndContent.of(series2, content2b); // a secret deleted on 2019-01-01T00:00:00Z private SecretSeries series3 = SecretSeries.of(3, "secret3", "desc3", january18, "creator", january19, "updater", null, null, null); private SecretContent content3 = SecretContent.of(104, 3, encryptedContent, "checksum", january18, "creator", january18, "updater", emptyMetadata, 0); private SecretSeriesAndContent secret3 = SecretSeriesAndContent.of(series3, content3); @Before public void setUp() throws Exception { // store an undeleted secret jooqContext.insertInto(SECRETS) .set(SECRETS.ID, series1.id()) .set(SECRETS.NAME, series1.name()) .set(SECRETS.DESCRIPTION, series1.description()) .set(SECRETS.CREATEDBY, series1.createdBy()) .set(SECRETS.CREATEDAT, series1.createdAt().toEpochSecond()) .set(SECRETS.UPDATEDBY, series1.updatedBy()) .set(SECRETS.UPDATEDAT, series1.updatedAt().toEpochSecond()) .set(SECRETS.CURRENT, series1.currentVersion().orElse(null)) .execute(); jooqContext.insertInto(SECRETS_CONTENT) .set(SECRETS_CONTENT.ID, secret1.content().id()) .set(SECRETS_CONTENT.SECRETID, secret1.series().id()) .set(SECRETS_CONTENT.ENCRYPTED_CONTENT, secret1.content().encryptedContent()) .set(SECRETS_CONTENT.CONTENT_HMAC, "checksum") .set(SECRETS_CONTENT.CREATEDBY, secret1.content().createdBy()) .set(SECRETS_CONTENT.CREATEDAT, secret1.content().createdAt().toEpochSecond()) .set(SECRETS_CONTENT.UPDATEDBY, secret1.content().updatedBy()) .set(SECRETS_CONTENT.UPDATEDAT, secret1.content().updatedAt().toEpochSecond()) .set(SECRETS_CONTENT.METADATA, objectMapper.writeValueAsString(secret1.content().metadata())) .execute(); // store a secret deleted on 2018-01-01T00:00:00Z jooqContext.insertInto(SECRETS) .set(SECRETS.ID, series2.id()) .set(SECRETS.NAME, series2.name()) .set(SECRETS.DESCRIPTION, series2.description()) .set(SECRETS.CREATEDBY, series2.createdBy()) .set(SECRETS.CREATEDAT, series2.createdAt().toEpochSecond()) .set(SECRETS.UPDATEDBY, series2.updatedBy()) .set(SECRETS.UPDATEDAT, series2.updatedAt().toEpochSecond()) .set(SECRETS.CURRENT, series2.currentVersion().orElse(null)) .execute(); jooqContext.insertInto(SECRETS_CONTENT) .set(SECRETS_CONTENT.ID, secret2a.content().id()) .set(SECRETS_CONTENT.SECRETID, secret2a.series().id()) .set(SECRETS_CONTENT.ENCRYPTED_CONTENT, secret2a.content().encryptedContent()) .set(SECRETS_CONTENT.CONTENT_HMAC, "checksum") .set(SECRETS_CONTENT.CREATEDBY, secret2a.content().createdBy()) .set(SECRETS_CONTENT.CREATEDAT, secret2a.content().createdAt().toEpochSecond()) .set(SECRETS_CONTENT.UPDATEDBY, secret2a.content().updatedBy()) .set(SECRETS_CONTENT.UPDATEDAT, secret2a.content().updatedAt().toEpochSecond()) .set(SECRETS_CONTENT.METADATA, objectMapper.writeValueAsString(secret2a.content().metadata())) .execute(); jooqContext.insertInto(SECRETS_CONTENT) .set(SECRETS_CONTENT.ID, secret2b.content().id()) .set(SECRETS_CONTENT.SECRETID, secret2b.series().id()) .set(SECRETS_CONTENT.ENCRYPTED_CONTENT, secret2b.content().encryptedContent()) .set(SECRETS_CONTENT.CONTENT_HMAC, "checksum") .set(SECRETS_CONTENT.CREATEDBY, secret2b.content().createdBy()) .set(SECRETS_CONTENT.CREATEDAT, secret2b.content().createdAt().toEpochSecond()) .set(SECRETS_CONTENT.UPDATEDBY, secret2b.content().updatedBy()) .set(SECRETS_CONTENT.UPDATEDAT, secret2b.content().updatedAt().toEpochSecond()) .set(SECRETS_CONTENT.METADATA, objectMapper.writeValueAsString(secret2b.content().metadata())) .execute(); // store a secret deleted on 2019-01-01T00:00:00Z jooqContext.insertInto(SECRETS) .set(SECRETS.ID, series3.id()) .set(SECRETS.NAME, series3.name()) .set(SECRETS.DESCRIPTION, series3.description()) .set(SECRETS.CREATEDBY, series3.createdBy()) .set(SECRETS.CREATEDAT, series3.createdAt().toEpochSecond()) .set(SECRETS.UPDATEDBY, series3.updatedBy()) .set(SECRETS.UPDATEDAT, series3.updatedAt().toEpochSecond()) .set(SECRETS.CURRENT, series3.currentVersion().orElse(null)) .execute(); jooqContext.insertInto(SECRETS_CONTENT) .set(SECRETS_CONTENT.ID, secret3.content().id()) .set(SECRETS_CONTENT.SECRETID, secret3.series().id()) .set(SECRETS_CONTENT.ENCRYPTED_CONTENT, secret3.content().encryptedContent()) .set(SECRETS_CONTENT.CONTENT_HMAC, "checksum") .set(SECRETS_CONTENT.CREATEDBY, secret3.content().createdBy()) .set(SECRETS_CONTENT.CREATEDAT, secret3.content().createdAt().toEpochSecond()) .set(SECRETS_CONTENT.UPDATEDBY, secret3.content().updatedBy()) .set(SECRETS_CONTENT.UPDATEDAT, secret3.content().updatedAt().toEpochSecond()) .set(SECRETS_CONTENT.METADATA, objectMapper.writeValueAsString(secret3.content().metadata())) .execute(); } @Test public void testSecretDeletion_allDeletedSecrets() throws Exception { runCommandWithConfirmationAndDate("yes", "2019-02-01T00:00:00Z", 0); // check the database state; secret2 and secret3 should have been removed checkExpectedSecretSeries(ImmutableList.of(series1), ImmutableList.of(series2, series3)); checkExpectedSecretContents(ImmutableList.of(content1), ImmutableList.of(content2a, content2b, content3)); } @Test public void testSecretDeletion_filterByDate_someSecretsRemoved() throws Exception { runCommandWithConfirmationAndDate("yes", "2018-02-01T00:00:00Z", 0); // check the database state; only secret2 should have been removed checkExpectedSecretSeries(ImmutableList.of(series1, series3), ImmutableList.of(series2)); checkExpectedSecretContents(ImmutableList.of(content1, content3), ImmutableList.of(content2a, content2b)); } @Test public void testSecretDeletion_filterByDate_noSecretsRemoved() throws Exception { runCommandWithConfirmationAndDate("yes", "2017-02-01T00:00:00Z", 0); // check the database state; no secrets should have been removed checkExpectedSecretSeries(ImmutableList.of(series1, series2, series3), ImmutableList.of()); checkExpectedSecretContents(ImmutableList.of(content1, content2a, content2b, content3), ImmutableList.of()); } @Test public void testSecretDeletion_futureDate() throws Exception { runCommandWithConfirmationAndDate("yes", "5000-02-01T00:00:00Z", 0); // check the database state; secrets should NOT have been removed checkExpectedSecretSeries(ImmutableList.of(series1, series2, series3), ImmutableList.of()); checkExpectedSecretContents(ImmutableList.of(content1, content2a, content2b, content3), ImmutableList.of()); } @Test public void testSecretDeletion_invalidDate() throws Exception { runCommandWithConfirmationAndDate("yes", "notadate", 0); // check the database state; secrets should NOT have been removed checkExpectedSecretSeries(ImmutableList.of(series1, series2, series3), ImmutableList.of()); checkExpectedSecretContents(ImmutableList.of(content1, content2a, content2b, content3), ImmutableList.of()); } @Test public void testSecretDeletion_noConfirmation() throws Exception { runCommandWithConfirmationAndDate("no", "2019-02-01T00:00:00Z", 0); // check the database state; secrets should NOT have been removed checkExpectedSecretSeries(ImmutableList.of(series1, series2, series3), ImmutableList.of()); checkExpectedSecretContents(ImmutableList.of(content1, content2a, content2b, content3), ImmutableList.of()); } @Test public void testSecretDeletion_negativeSleep() throws Exception { runCommandWithConfirmationAndDate("yes", "2019-02-01T00:00:00Z", -10); // check the database state; secrets should NOT have been removed checkExpectedSecretSeries(ImmutableList.of(series1, series2, series3), ImmutableList.of()); checkExpectedSecretContents(ImmutableList.of(content1, content2a, content2b, content3), ImmutableList.of()); } private void runCommandWithConfirmationAndDate(String confirmation, String date, int sleepMillis) throws Exception { SecretDAO secretDAO = secretDAOFactory.readwrite(); // confirm that the expected secrets are present checkExpectedSecretSeries(ImmutableList.of(series1, series2, series3), ImmutableList.of()); checkExpectedSecretContents(ImmutableList.of(content1, content2a, content2b, content3), ImmutableList.of()); DropDeletedSecretsCommand command = new DropDeletedSecretsCommand(secretDAO); // remove secrets InputStream in = new ByteArrayInputStream(confirmation.getBytes(UTF_8)); System.setIn(in); command.run(null, new Namespace( ImmutableMap.of( DropDeletedSecretsCommand.INPUT_DELETED_BEFORE, date, DropDeletedSecretsCommand.INPUT_SLEEP_MILLIS, sleepMillis)), null); System.setIn(System.in); } /** * Verify that the given sets of secrets are present/not present in the database. */ private void checkExpectedSecretSeries(List<SecretSeries> expectedPresentSeries, List<SecretSeries> expectedMissingSeries) { List<Long> secretSeriesIds = jooqContext.select(SECRETS.ID).from(SECRETS).fetch(SECRETS.ID); assertThat(secretSeriesIds).containsAll( expectedPresentSeries.stream().map(SecretSeries::id).collect(toList())); if (!expectedMissingSeries.isEmpty()) { assertThat(secretSeriesIds).doesNotContainAnyElementsOf( expectedMissingSeries.stream().map(SecretSeries::id).collect(toList())); } } /** * Verify that the given sets of secrets are present/not present in the database. */ private void checkExpectedSecretContents(List<SecretContent> expectedPresentContents, List<SecretContent> expectedMissingContents) { List<Long> secretContentsIds = jooqContext.select(SECRETS_CONTENT.ID).from(SECRETS_CONTENT).fetch(SECRETS_CONTENT.ID); assertThat(secretContentsIds).containsAll( expectedPresentContents.stream().map(SecretContent::id).collect(toList())); if (!expectedMissingContents.isEmpty()) { assertThat(secretContentsIds).doesNotContainAnyElementsOf( expectedMissingContents.stream().map(SecretContent::id).collect(toList())); } } }
MarkShawn2020/MachineLarning-Numpy-CodeCraft2020
core/models.py
# -*- coding: utf-8 -*- # ----------------------------------- # @CreateTime : 2020/3/19 23:54 # @Author : <NAME> # @Email : <EMAIL> # ------------------------------------ import os import logging import pickle import numpy as np from .functions import sigmoid, cross_entropy, mse class Model: def __init__(self, lr=0.03): self.lr = lr def fit(self, X, Y): raise NotImplementedError("该函数必须继承实现!") def predict(self, X): raise NotImplementedError("该函数必须继承实现!") @staticmethod def evaluate(Y_pred, Y_target): raise NotImplementedError("该函数必须继承实现!") def evaluate_data_loader(self, data_loader): return self.evaluate(self.predict(data_loader.X), data_loader.Y) def save_prediction(self, Y_pred, path, delimiter="\n"): with open(path, 'w') as f: for each_Y_pred in Y_pred: f.write("{}{}".format(each_Y_pred, delimiter)) logging.info("Saved prediction to file {}".format(os.path.abspath(path))) class LogisticRegression(Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def fit(self, X, Y_target): Y_pred = sigmoid(X @ self.w) self.w += self.lr * (Y_target - Y_pred).T @ X / len(X) def predict(self, X): Y_pred = ((X @ self.w) > 0).astype(int) return Y_pred @staticmethod def evaluate(Y_pred, Y_target) -> dict: loss_cross_entropy = cross_entropy(Y_pred, Y_target) n_errs = (Y_pred.astype(int) ^ Y_target.astype(int)).sum().item() N = len(Y_target) acc = (1 - n_errs / N) * 100 return { "n_errs": n_errs, "N_items": N, "acc": acc, "loss": loss_cross_entropy, } def init_weight(self, n_features, scale=0.01): self.w = np.random.random((n_features, )) * scale def dump_weight(self, path): pickle.dump(self.w, open(path, "wb")) logging.info("Dumped weights into file {}".format(os.path.abspath(path))) def load_weight(self, path): self.w = pickle.load(open(path, "rb")) logging.info("Loaded weights from file {}".format(os.path.abspath(path)))
cody110/flyertea
flyerteaCafes/src/main/java/com/ideal/flyerteacafes/adapters/HotelReservationAdapter.java
package com.ideal.flyerteacafes.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ideal.flyerteacafes.R; import com.ideal.flyerteacafes.model.entity.HotelBean; import com.ideal.flyerteacafes.utils.DataUtils; import java.util.List; public class HotelReservationAdapter extends BaseAdapter { private Context context; private LayoutInflater inflater; private List<HotelBean> listBean; public HotelReservationAdapter(Context context, List<HotelBean> listBean) { inflater = LayoutInflater.from(context); this.context = context; this.listBean = listBean; } @Override public int getCount() { // TODO Auto-generated method stub return listBean.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return listBean.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) convertView = inflater.inflate(R.layout.gridview_item_hotel_reservation, null); ImageView iconImg = (ImageView) convertView.findViewById(R.id.gridview_hotel_reservation_icon); HotelBean bean = (HotelBean) getItem(position); DataUtils.downloadPicture(iconImg, bean.getHotel_icon_url(), R.drawable.ic_launcher); TextView nameText = (TextView) convertView.findViewById(R.id.gridview_hotel_reservation_name); nameText.setText(bean.getHotel_name()); return convertView; } }
dachr8/Exercise
BUPT/Operating-System/Assignment 3/problem3.20/pid_manager.h
#define MIN_PID 300 #define MAX_PID 5000 #define PID_LEN MAX_PID - MIN_PID + 1 int PID[MAX_PID-MIN_PID]; /* Creates and initializes a data structure for representing pids; returns 0 if unsuccessful, 1 if successful */ int allocate_map(void); /* Allocates and returns a pid; returns 1 if unable to allocate a pid (all pids are in use) */ int allocate_pid(void); /* Releases a pid */ void release_pid(int);
Lezappen/Laravel4.2CRUD
public/bower_components/ckeditor/plugins/selectall/lang/cs.js
<filename>public/bower_components/ckeditor/plugins/selectall/lang/cs.js CKEDITOR.plugins.setLang("selectall","cs",{toolbar:"Vybrat vše"});
psbarrales/unleash
test/e2e/api/client/metrics.e2e.test.js
<filename>test/e2e/api/client/metrics.e2e.test.js 'use strict'; const { test } = require('ava'); const { setupApp } = require('./../../helpers/test-helper'); const metricsExample = require('../../../examples/client-metrics.json'); test.serial('should be possble to send metrics', async t => { t.plan(0); const { request, destroy } = await setupApp('metrics_api_client'); return request .post('/api/client/metrics') .send(metricsExample) .expect(202) .then(destroy); }); test.serial('should require valid send metrics', async t => { t.plan(0); const { request, destroy } = await setupApp('metrics_api_client'); return request .post('/api/client/metrics') .send({ appName: 'test', }) .expect(400) .then(destroy); });
JingQianCloud/ambry
ambry-router/src/test/java/com/github/ambry/router/QuotaAwareOperationControllerTest.java
<reponame>JingQianCloud/ambry /** * Copyright 2021 LinkedIn Corp. All rights reserved. * * 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. */ package com.github.ambry.router; import com.codahale.metrics.MetricRegistry; import com.github.ambry.clustermap.ClusterMap; import com.github.ambry.clustermap.MockDataNodeId; import com.github.ambry.clustermap.ReplicaId; import com.github.ambry.config.RouterConfig; import com.github.ambry.config.VerifiableProperties; import com.github.ambry.network.NetworkClient; import com.github.ambry.network.NetworkClientFactory; import com.github.ambry.network.Port; import com.github.ambry.network.PortType; import com.github.ambry.network.RequestInfo; import com.github.ambry.network.SendWithCorrelationId; import com.github.ambry.quota.Chargeable; import com.github.ambry.quota.QuotaAction; import com.github.ambry.quota.QuotaMethod; import com.github.ambry.quota.QuotaResource; import com.github.ambry.quota.QuotaResourceType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mockito; import org.mockito.internal.util.reflection.FieldSetter; import org.mockito.stubbing.Answer; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * Test for {@link QuotaAwareOperationController}. */ @RunWith(Parameterized.class) public class QuotaAwareOperationControllerTest { private static final String HOST = "HOST"; private static final Port PORT = new Port(80, PortType.PLAINTEXT); private static final SendWithCorrelationId SEND = Mockito.mock(SendWithCorrelationId.class); private static final ReplicaId REPLICA_ID = Mockito.mock(ReplicaId.class); private static final QuotaResource TEST_QUOTA_RESOURCE1 = new QuotaResource("test1", QuotaResourceType.ACCOUNT); private static final QuotaResource TEST_QUOTA_RESOURCE2 = new QuotaResource("test2", QuotaResourceType.ACCOUNT); private final PutManager putManager = Mockito.mock(PutManager.class); private final GetManager getManager = Mockito.mock(GetManager.class); private final NonBlockingRouter nonBlockingRouter = Mockito.mock(NonBlockingRouter.class); private final DeleteManager deleteManager = Mockito.mock(DeleteManager.class); private final TtlUpdateManager ttlUpdateManager = Mockito.mock(TtlUpdateManager.class); private final UndeleteManager undeleteManager = Mockito.mock(UndeleteManager.class); private final List<RequestInfo> requestsToSend = new LinkedList<>(); private final Set<Integer> requestsToDrop = new HashSet<>(); private final QuotaMethod quotaMethod; private QuotaAwareOperationController quotaAwareOperationController; /** * Constructor for {@link QuotaAwareOperationControllerTest}. * @param quotaMethod {@link QuotaMethod} to use for the test run. */ public QuotaAwareOperationControllerTest(QuotaMethod quotaMethod) { this.quotaMethod = quotaMethod; } @Parameterized.Parameters public static List<Object[]> data() { return Arrays.asList(new Object[][]{{QuotaMethod.READ}, {QuotaMethod.WRITE}}); } @Before public void setupMocks() throws Exception { NetworkClientFactory networkClientFactory = mock(NetworkClientFactory.class); NetworkClient networkClient = mock(NetworkClient.class); when(networkClientFactory.getNetworkClient()).thenReturn(networkClient); ClusterMap clusterMap = mock(ClusterMap.class); when(clusterMap.getLocalDatacenterId()).thenReturn((byte) 1); when(clusterMap.getDatacenterName((byte) 1)).thenReturn("test"); when(clusterMap.getMetricRegistry()).thenReturn(new MetricRegistry()); MockDataNodeId mockDataNodeId = new MockDataNodeId(Collections.singletonList(new Port(80, PortType.PLAINTEXT)), Collections.singletonList("/a/b"), "test"); List<MockDataNodeId> dataNodeIds = new ArrayList<>(); dataNodeIds.add(mockDataNodeId); doReturn(dataNodeIds).when(clusterMap).getDataNodeIds(); when(networkClient.warmUpConnections(anyList(), anyByte(), anyLong(), anyList())).thenReturn(1); Properties properties = new Properties(); properties.setProperty(RouterConfig.ROUTER_DATACENTER_NAME, "test"); properties.setProperty(RouterConfig.ROUTER_HOSTNAME, "test"); RouterConfig routerConfig = new RouterConfig(new VerifiableProperties(properties)); NonBlockingRouterMetrics routerMetrics = new NonBlockingRouterMetrics(clusterMap, routerConfig); quotaAwareOperationController = new QuotaAwareOperationController(null, null, null, networkClientFactory, clusterMap, routerConfig, null, null, routerMetrics, null, null, null, null, nonBlockingRouter); quotaAwareOperationController.putManager.close(); // closing existing put manager before setting mock to clean up the threads. FieldSetter.setField(quotaAwareOperationController, quotaAwareOperationController.getClass().getSuperclass().getDeclaredField("putManager"), putManager); FieldSetter.setField(quotaAwareOperationController, quotaAwareOperationController.getClass().getSuperclass().getDeclaredField("getManager"), getManager); FieldSetter.setField(quotaAwareOperationController, quotaAwareOperationController.getClass().getSuperclass().getDeclaredField("deleteManager"), deleteManager); FieldSetter.setField(quotaAwareOperationController, quotaAwareOperationController.getClass().getSuperclass().getDeclaredField("undeleteManager"), undeleteManager); FieldSetter.setField(quotaAwareOperationController, quotaAwareOperationController.getClass().getSuperclass().getDeclaredField("ttlUpdateManager"), ttlUpdateManager); doNothing().when(getManager).poll(requestsToSend, requestsToDrop); doNothing().when(deleteManager).poll(requestsToSend, requestsToDrop); doNothing().when(ttlUpdateManager).poll(requestsToSend, requestsToDrop); doNothing().when(nonBlockingRouter).initiateBackgroundDeletes(anyList()); } @Test public void testSimpleDrainageEmpty() { TestChargeable chargeable = new TestChargeable(QuotaAction.ALLOW, TEST_QUOTA_RESOURCE1, quotaMethod); doAnswer((Answer<Void>) invocation -> { List<RequestInfo> requestsToSend = (List<RequestInfo>) invocation.getArguments()[0]; requestsToSend.add(new RequestInfo(HOST, PORT, SEND, REPLICA_ID, chargeable)); return null; }).when(putManager).poll(requestsToSend, requestsToDrop); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(0, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); assertEquals(0, quotaAwareOperationController.getDelayedRequestsInQueue()); assertEquals(0, quotaAwareOperationController.getOutOfQuotaRequestsInQueue()); chargeable.verifyCalls(1, 1); } @Test public void testSimpleDrainageOutOfQuota() { TestChargeable testChargeable1 = new TestChargeable( Arrays.asList(QuotaAction.DELAY, QuotaAction.DELAY, QuotaAction.ALLOW, QuotaAction.DELAY, QuotaAction.DELAY, QuotaAction.ALLOW), TEST_QUOTA_RESOURCE1, quotaMethod); doAnswer((Answer<Void>) invocation -> { List<RequestInfo> requestsToSend = (List<RequestInfo>) invocation.getArguments()[0]; requestsToSend.add(new RequestInfo(HOST, PORT, SEND, REPLICA_ID, testChargeable1)); return null; }).when(putManager).poll(requestsToSend, requestsToDrop); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(1, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); assertEquals(1, quotaAwareOperationController.getRequestQueue(quotaMethod).get(TEST_QUOTA_RESOURCE1).size()); assertEquals(1, quotaAwareOperationController.getOutOfQuotaRequestsInQueue()); assertEquals(1, quotaAwareOperationController.getDelayedRequestsInQueue()); testChargeable1.verifyCalls(2, 1); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(1, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); assertEquals(1, quotaAwareOperationController.getRequestQueue(quotaMethod).get(TEST_QUOTA_RESOURCE1).size()); assertEquals(1, quotaAwareOperationController.getOutOfQuotaRequestsInQueue()); assertEquals(1, quotaAwareOperationController.getDelayedRequestsInQueue()); testChargeable1.verifyCalls(5, 2); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(0, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); assertEquals(0, quotaAwareOperationController.getOutOfQuotaRequestsInQueue()); assertEquals(0, quotaAwareOperationController.getDelayedRequestsInQueue()); testChargeable1.verifyCalls(6, 2); } @Test public void testSimpleDrainageOutOfQuotaMultipleAccounts() { TestChargeable testChargeable1 = new TestChargeable(QuotaAction.ALLOW, TEST_QUOTA_RESOURCE1, quotaMethod); TestChargeable testChargeable2 = new TestChargeable(QuotaAction.ALLOW, TEST_QUOTA_RESOURCE2, quotaMethod); doAnswer((Answer<Void>) invocation -> { List<RequestInfo> requestsToSend = (List<RequestInfo>) invocation.getArguments()[0]; requestsToSend.add(new RequestInfo(HOST, PORT, SEND, REPLICA_ID, testChargeable1)); requestsToSend.add(new RequestInfo(HOST, PORT, SEND, REPLICA_ID, testChargeable2)); return null; }).when(putManager).poll(requestsToSend, requestsToDrop); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(0, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); } @Test public void testSimpleDrainageOutOfQuotaWithExceedAllowed() { doAnswer((Answer<Void>) invocation -> { List<RequestInfo> requestsToSend = (List<RequestInfo>) invocation.getArguments()[0]; requestsToSend.add(new RequestInfo(HOST, PORT, SEND, REPLICA_ID, new TestChargeable(QuotaAction.ALLOW, TEST_QUOTA_RESOURCE1, quotaMethod))); return null; }).when(putManager).poll(requestsToSend, requestsToDrop); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(0, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); } @Test public void testDrainageForNullResourceIdOnly() { doAnswer((Answer<Void>) invocation -> { List<RequestInfo> requestsToSend = (List<RequestInfo>) invocation.getArguments()[0]; requestsToSend.add( new RequestInfo(HOST, PORT, SEND, REPLICA_ID, new TestChargeable(QuotaAction.ALLOW, null, quotaMethod))); return null; }).when(putManager).poll(requestsToSend, requestsToDrop); quotaAwareOperationController.pollForRequests(requestsToSend, requestsToDrop); assertEquals(0, quotaAwareOperationController.getRequestQueue(quotaMethod).size()); } /** * {@link Chargeable} implementation for test. */ static class TestChargeable implements Chargeable { private final QuotaResource quotaResource; private final List<QuotaMethod> quotaMethods; private final List<QuotaAction> chargeOutputs; private int numChargeCalls; private int numGetQuotaResourceCalls; private int numGetQuotaMethodCalls; /** * Constructor for {@link TestChargeable}. * @param chargeOutput output of charge method. * @param quotaResource output of getQuotaResource method. * @param quotaMethod output of the getQuotaMethod method. */ public TestChargeable(QuotaAction chargeOutput, QuotaResource quotaResource, QuotaMethod quotaMethod) { this.chargeOutputs = Collections.singletonList(chargeOutput); this.quotaResource = quotaResource; this.quotaMethods = Collections.singletonList(quotaMethod); } /** * Constructor for {@link TestChargeable}. * @param chargeOutputs {@link List} of {@link QuotaAction} as output of charge method. * @param quotaResource output of getQuotaResource method. * @param quotaMethod output of the getQuotaMethod method. */ public TestChargeable(List<QuotaAction> chargeOutputs, QuotaResource quotaResource, QuotaMethod quotaMethod) { this.chargeOutputs = chargeOutputs; this.quotaResource = quotaResource; this.quotaMethods = Collections.singletonList(quotaMethod); } /** * Constructor for {@link TestChargeable}. * @param chargeOutput output of charge method. * @param quotaResource output of getQuotaResource method. * @param quotaMethods {@link List} of {@link QuotaMethod}s representing the sequence of output of get quota method calls. */ public TestChargeable(QuotaAction chargeOutput, QuotaResource quotaResource, List<QuotaMethod> quotaMethods) { this.chargeOutputs = Collections.singletonList(chargeOutput); this.quotaResource = quotaResource; this.quotaMethods = quotaMethods; } @Override public QuotaAction checkAndCharge(boolean shouldCheckExceedAllowed) { QuotaAction out = chargeOutputs.get(numChargeCalls % chargeOutputs.size()); numChargeCalls++; return out; } @Override public QuotaResource getQuotaResource() { numGetQuotaResourceCalls++; return quotaResource; } @Override public QuotaMethod getQuotaMethod() { QuotaMethod out = quotaMethods.get(numGetQuotaMethodCalls % quotaMethods.size()); numGetQuotaMethodCalls++; return out; } /** * Verify that the interface methods have been called expected number of times. * @param numChargeCalls expected number of charge calls. * @param numGetQuotaResourceCalls expected number of getQuotaResource calls. */ public void verifyCalls(int numChargeCalls, int numGetQuotaResourceCalls) { assertEquals("Invalid charge calls", numChargeCalls, this.numChargeCalls); assertEquals("Invalid getQuotaResource calls", numGetQuotaResourceCalls, this.numGetQuotaResourceCalls); } } }
Arusekk/snakeoil
src/snakeoil/compression/_util.py
<filename>src/snakeoil/compression/_util.py __all__ = ("compress_data", "decompress_data") import errno import os import subprocess def _drive_process(args, mode, data): p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) try: stdout, stderr = p.communicate(data) if p.returncode != 0: raise ValueError( "%s returned %i exitcode from '%s', stderr=%r" % (mode, p.returncode, ' '.join(args), stderr)) return stdout finally: if p is not None and p.returncode is None: p.kill() def compress_data(binary, data, compresslevel=9, extra_args=()): args = [binary, '-%ic' % compresslevel] args.extend(extra_args) return _drive_process(args, 'compression', data) def decompress_data(binary, data, extra_args=()): args = [binary, '-dc'] args.extend(extra_args) return _drive_process(args, 'decompression', data) class _process_handle: def __init__(self, handle, args, is_read=False): self.mode = 'wb' if is_read: self.mode = 'rb' self.args = tuple(args) self.is_read = is_read self._open_handle(handle) def _open_handle(self, handle): self._allow_reopen = None close = False if isinstance(handle, str): if self.is_read: self._allow_reopen = handle handle = open(handle, mode=self.mode) close = True elif not isinstance(handle, int): if not hasattr(handle, 'fileno'): raise TypeError( "handle %r isn't a string, integer, and lacks a fileno " "method" % (handle,)) handle = handle.fileno() try: self._setup_process(handle) finally: if close: handle.close() def _setup_process(self, handle): self.position = 0 stderr = open(os.devnull, 'wb') kwds = dict(stderr=stderr) if self.is_read: kwds['stdin'] = handle kwds['stdout'] = subprocess.PIPE else: kwds['stdout'] = handle kwds['stdin'] = subprocess.PIPE try: self._process = subprocess.Popen( self.args, close_fds=True, **kwds) finally: stderr.close() if self.is_read: self.handle = self._process.stdout else: self.handle = self._process.stdin def read(self, amount=None): if amount is None: data = self.handle.read() else: data = self.handle.read(amount) self.position += len(data) return data def write(self, data): self.position += len(data) self.handle.write(data) def tell(self): return self.position def seek(self, position=0): fwd_seek = position - self.position if fwd_seek < 0: if self._allow_reopen is None: raise TypeError( "instance %s can't do negative seeks: asked for %i, " "was at %i" % (self, position, self.position)) self._terminate() self._open_handle(self._allow_reopen) return self.seek(position) elif fwd_seek > 0: if self.is_read: self._read_seek(fwd_seek) else: self._write_seek(fwd_seek) return self.position def _read_seek(self, offset, seek_size=(64 * 1024)): val = min(offset, seek_size) while val: self.read(val) offset -= val val = min(offset, seek_size) def _write_seek(self, offset, seek_size=64 * 1024): val = min(offset, seek_size) # allocate up front a null block so we can avoid # reallocating it continually; via this usage, we # only slice once the val is less than seek_size; # iow, two allocations worst case. null_block = '\0' * seek_size while val: self.write(null_block[:val]) offset -= val val = min(offset, seek_size) def _terminate(self): try: self._process.terminate() except EnvironmentError as e: # allow no such process only. if e.errno != errno.ESRCH: raise def close(self): if self._process.returncode is not None: if self._process.returncode != 0: raise Exception("%s invocation had non zero exit: %i" % (self.args, self._process.returncode)) return self.handle.close() if self.is_read: self._terminate() else: self._process.wait() def __del__(self): self.close() def compress_handle(binary_path, handle, compresslevel=9, extra_args=()): args = [binary_path, '-%ic' % compresslevel] args.extend(extra_args) return _process_handle(handle, args, False) def decompress_handle(binary_path, handle, extra_args=()): args = [binary_path, '-dc'] args.extend(extra_args) return _process_handle(handle, args, True)
Fun2LearnCode/Java
custom-projects/shabingasplayground/src/shabingasplayground/world/block/BlockLayerChunkThread.java
<gh_stars>0 package shabingasplayground.world.block; public class BlockLayerChunkThread { }
CodingAir/CodingAPI
src/main/java/de/codingair/codingapi/tools/Call.java
<filename>src/main/java/de/codingair/codingapi/tools/Call.java package de.codingair.codingapi.tools; public interface Call { void proceed(); }
yunger7/laboratory
Projects/React/react-todo-app/src/App.js
<gh_stars>1-10 import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { Firestore } from './firebase/config'; import { useCollection } from 'react-firebase-hooks/firestore' import AddTask from './components/AddTask'; import Footer from './components/Footer'; import Header from './components/Header'; import TaskList from './components/TaskList'; function App() { const [tasks, loading, error] = useCollection(Firestore.collection('tasks')); const deleteTask = (id) => { Firestore.collection('tasks').doc(id).delete(); } return ( <Router> <div className="App"> <Header tasks={tasks} /> <Switch> <Route exact path="/"> { loading && <span>Loading...</span> } { error && <span>{ error }</span> } { tasks && <TaskList tasks={tasks} deleteTask={deleteTask} /> } </Route> <Route path="/add"> <AddTask /> </Route> </Switch> <Footer /> </div> </Router> ); } export default App;
digitalbuddha/androidx
core/core/src/androidTest/java/androidx/core/app/NotificationChannelCompatTest.java
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.app; import static androidx.core.app.NotificationManagerCompat.IMPORTANCE_HIGH; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import android.app.NotificationChannel; import android.media.AudioAttributes; import android.net.Uri; import android.os.Build; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SdkSuppress; import androidx.test.filters.SmallTest; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.Collection; import java.util.Objects; @RunWith(AndroidJUnit4.class) @SmallTest public class NotificationChannelCompatTest { /** * Test that the NotificationChannel.equals() method counts as equal the minimally-defined * channel using the platform API and the Builder. Also tests visible fields on the Compat * object against the platform object. */ @SdkSuppress(minSdkVersion = 26) @Test public void testDefaultBuilderEqualsPlatform() { String channelId = "channelId"; String channelName = "channelName"; NotificationChannel platformChannel = new NotificationChannel(channelId, channelName, IMPORTANCE_HIGH); NotificationChannelCompat.Builder builder = new NotificationChannelCompat.Builder(channelId, IMPORTANCE_HIGH) .setName(channelName); NotificationChannelCompat compatChannel = builder.build(); TestHelper.assertChannelEquals(platformChannel, compatChannel); NotificationChannel builderChannel = compatChannel.getNotificationChannel(); assertEquals(platformChannel, builderChannel); } /** * Test that the NotificationChannel.equals() method counts as equal the maximally-defined * channel using the platform API and the Builder. Also tests visible fields on the Compat * object against the platform object. */ @SdkSuppress(minSdkVersion = 26) @Test public void testFullyDefinedBuilderEqualsPlatform() { String channelId = "channelId"; String groupId = "groupId"; String parentChannelId = "parentChannelId"; String shortcutId = "shortcutId"; String channelName = "channelName"; String channelDescription = "channelDescription"; int lightColor = 1234567; Uri soundUri = Uri.parse("http://foo.com/sound"); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) .setUsage(AudioAttributes.USAGE_ASSISTANT) .build(); long[] vibrationPattern = {100, 200, 100, 100}; NotificationChannel platformChannel = new NotificationChannel(channelId, channelName, IMPORTANCE_HIGH); platformChannel.setGroup(groupId); platformChannel.setDescription(channelDescription); platformChannel.setLightColor(lightColor); platformChannel.enableLights(true); platformChannel.setShowBadge(false); platformChannel.setSound(soundUri, audioAttributes); platformChannel.setVibrationPattern(vibrationPattern); if (Build.VERSION.SDK_INT >= 30) { platformChannel.setConversationId(parentChannelId, shortcutId); } NotificationChannelCompat.Builder builder = new NotificationChannelCompat.Builder(channelId, IMPORTANCE_HIGH) .setName(channelName) .setGroup(groupId) .setDescription(channelDescription) .setLightColor(lightColor) .setLightsEnabled(true) .setShowBadge(false) .setSound(soundUri, audioAttributes) .setVibrationPattern(vibrationPattern); if (Build.VERSION.SDK_INT >= 30) { builder.setConversationId(parentChannelId, shortcutId); } NotificationChannelCompat compatChannel = builder.build(); TestHelper.assertChannelEquals(platformChannel, compatChannel); NotificationChannel builderChannel = compatChannel.getNotificationChannel(); assertEquals(platformChannel, builderChannel); } /* * On older versions of the OS that do not have the NotificationChannel class, * loading this test class with a method that has NotificationChannel in its parameters * signature will throw a NoClassDefFoundError at runtime. * To work around this, we use a separate inner class that provides static helper methods */ static class TestHelper { static boolean listContains(Collection<NotificationChannel> containsAll, Collection<NotificationChannel> containedList) { boolean contains = false; for (NotificationChannel nc : containedList) { for (NotificationChannel member : containsAll) { contains |= areEqual(nc, member); } if (!contains) { return false; } contains = false; } return true; } static boolean listContainsCompat(Collection<NotificationChannel> containsAll, Collection<NotificationChannelCompat> containedList) { boolean contains = false; for (NotificationChannelCompat nc : containedList) { for (NotificationChannel member : containsAll) { contains |= areEqual(nc, member); } if (!contains) { return false; } contains = false; } return true; } static boolean areEqual(NotificationChannel nc1, NotificationChannel nc2) { boolean equality = nc1.getImportance() == nc2.getImportance() && nc1.canBypassDnd() == nc2.canBypassDnd() && nc1.getLockscreenVisibility() == nc2.getLockscreenVisibility() && nc1.getLightColor() == nc2.getLightColor() && Objects.equals(nc1.getId(), nc2.getId()) && Objects.equals(nc1.getName(), nc2.getName()) && Objects.equals(nc1.getDescription(), nc2.getDescription()) && Objects.equals(nc1.getSound(), nc2.getSound()) && Arrays.equals(nc1.getVibrationPattern(), nc2.getVibrationPattern()) && Objects.equals(nc1.getGroup(), nc2.getGroup()) && Objects.equals(nc1.getAudioAttributes(), nc2.getAudioAttributes()); if (Build.VERSION.SDK_INT >= 30) { equality = equality && Objects.equals(nc1.getParentChannelId(), nc2.getParentChannelId()) && Objects.equals(nc1.getConversationId(), nc2.getConversationId()); } return equality; } static boolean areEqual(NotificationChannelCompat nc1, NotificationChannel nc2) { return areEqual(nc1.getNotificationChannel(), nc2); } static void assertChannelEquals(NotificationChannel expected, NotificationChannelCompat actual) { assertEquals(expected.getImportance(), actual.getImportance()); assertEquals(expected.getLightColor(), actual.getLightColor()); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getDescription(), actual.getDescription()); assertEquals(expected.getSound(), actual.getSound()); assertArrayEquals(expected.getVibrationPattern(), actual.getVibrationPattern()); assertEquals(expected.getGroup(), actual.getGroup()); assertEquals(expected.getAudioAttributes(), actual.getAudioAttributes()); if (Build.VERSION.SDK_INT >= 30) { assertEquals(expected.getParentChannelId(), actual.getParentChannelId()); assertEquals(expected.getConversationId(), actual.getConversationId()); } assertTrue(areEqual(actual, expected)); } } }
xzrunner/raytracing
include/raytracing/texture/RectangleChecker.h
<filename>include/raytracing/texture/RectangleChecker.h #pragma once #include "raytracing/texture/Texture.h" #include "raytracing/maths/Point3D.h" #include "raytracing/maths/Vector3D.h" namespace rt { class RectangleChecker : public Texture { public: RectangleChecker() {} virtual RGBColor GetColor(const ShadeRec& sr) const override; void SetNumXCheckers(int num) { m_num_x_checkers = num; } void SetNumZCheckers(int num) { m_num_z_checkers = num; } void SetXLineWidth(float width) { m_x_line_width = width; } void SetZLineWidth(float width) { m_z_line_width = width; } void SetP0(const Point3D& p) { m_p0 = p; } void SetA(const Vector3D& v) { m_a = v; } void SetB(const Vector3D& v) { m_b = v; } void SetColor1(const RGBColor& c) { m_color1 = c; } void SetColor2(const RGBColor& c) { m_color2 = c; } void SetLineColor(const RGBColor& c) { m_line_color = c; } private: int m_num_x_checkers = 20; int m_num_z_checkers = 20; float m_x_line_width = 0; float m_z_line_width = 0; Point3D m_p0 = Point3D(-1, 0, -1); Vector3D m_a = Vector3D(0, 0, 2); Vector3D m_b = Vector3D(2, 0, 0); RGBColor m_color1 = RGBColor(1.0f, 1.0f, 1.0f); // checker color 1 RGBColor m_color2 = RGBColor(0.5f, 0.5f, 0.5f); // checker color 2 RGBColor m_line_color = RGBColor(0, 0, 0); // the line color }; // RectangleChecker }
josephevans/WeVoteServer
polling_location/serializers.py
# polling_location/serializers.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from .models import PollingLocation from rest_framework import serializers class PollingLocationSerializer(serializers.ModelSerializer): class Meta: model = PollingLocation fields = ('we_vote_id', 'city', 'directions_text', 'line1', 'line2', 'location_name', 'polling_hours_text', 'polling_location_id', 'state', 'zip_long', )
Kunkkaa/proxibanquev3
src/main/java/fr/formation/proxi/metier/entity/BankCard.java
package fr.formation.proxi.metier.entity; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="bankcard") public class BankCard { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column private Integer id; @Column private String number; @Column private String isElectron; @Column private LocalDate expirationDate; public LocalDate getExpirationDate() { return expirationDate; } public void setExpirationDate(LocalDate expirationDate) { this.expirationDate = expirationDate; } public BankCard() { } public BankCard(String number, String isElectron) { this.number = number; this.isElectron = isElectron; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getIsElectron() { return isElectron; } public void setIsElectron(String isElectron) { this.isElectron = isElectron; } }
carbonscott/pyrotein
examples/plot_fwk.u.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pyrotein as pr import givens as gv from display import plot_dmat, plot_singular, plot_left_singular, plot_coeff import multiprocessing as mp from loaddata import load_xlsx, label_TMs import colorsimple as cs def reverse_sign(u, vh, rank, index_from_zero = True): # Adjust the index base... index_base = 0 if index_from_zero else 1 # Reverse sign... u[:, rank] = - u[:, rank] vh[rank, :] = -vh[rank, :] return None # Specify chains to process... fl_chain = "chains.comp.xlsx" lines = load_xlsx(fl_chain) # Specify the range of atoms from rhodopsin... nterm = 1 cterm = 322 # It was 348 backbone = ["N", "CA", "C", "O"] length_backbone = (cterm - nterm + 1) * len(backbone) # Load upstream data... dmats = np.load("dmats.npy") u = np.load("u.npy") s = np.load("s.npy") vh = np.load("vh.npy") # Allow positive value that fits the distance in nature (optinal)... reverse_sign(u, vh, 1, index_from_zero = False) reverse_sign(u, vh, 2, index_from_zero = False) reverse_sign(u, vh, 4, index_from_zero = False) # Calculate the coefficients... c = np.matmul(np.diag(s), vh) # Standardize u and c and assign units... u_ave = np.sqrt(u.shape[0]) c = c / u_ave # Count #cpu for multiprocessing (optional)... num_cpu = mp.cpu_count() num_job = num_cpu # Draw guidelines (optional)... lbls = {} cmds_guideline_top = [""] cmds_guideline_bottom = [""] color_guideline = '#BBBBBB' # Draw the rigid framework... ## fl_fwk = 'extracellular.fwk.dat' fl_fwk = 'intracellular.fwk.dat' fwk = pr.utils.read_file(fl_fwk, numerical = True) cmd_fwk = [] for i in range(len(fwk)): cmd = [] b1, e1 = [ k * 4 for k in fwk[i] ] cmd.append(f"set object rectangle front from {b1},{e1} to {e1},{b1} fs empty border linecolor rgb 'black'") for j in range(i + 1, len(fwk)): b2, e2 = [ k * 4 for k in fwk[j] ] cmd.append(f"set object rectangle front from {b1},{b2} to {e1},{e2} fs empty linecolor rgb '{color_guideline}'") cmd_fwk.extend(cmd) cmds_guideline_bottom.extend(cmd_fwk) cmds_guideline_top.append(f"set key top left") labels_TM = label_TMs() for k, v in labels_TM.items(): labels_TM[k] = [ i * 4 for i in v ] # Visualize a u matrix... def plot_left_singualr_by_rank(rank): return plot_left_singular(u, rank, length_mat = length_backbone, guidelines = labels_TM, width = 10, height = 12, fontsize = 29, lbl_fontsize = 29, linewidth = 2.0, frac = 1.0, binning = 1, cmds_top = cmds_guideline_top, cmds_bottom = cmds_guideline_bottom, index_from_zero = False) plot_left_singualr_by_rank(2) ## num_job = 2 ## with mp.Pool(num_job) as proc: ## proc.map( plot_left_singualr_by_rank, [rank1, rank2] )
Shashi-rk/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/PipelineOptions.java
<filename>sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/models/PipelineOptions.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.containerregistry.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for PipelineOptions. */ public final class PipelineOptions extends ExpandableStringEnum<PipelineOptions> { /** Static value OverwriteTags for PipelineOptions. */ public static final PipelineOptions OVERWRITE_TAGS = fromString("OverwriteTags"); /** Static value OverwriteBlobs for PipelineOptions. */ public static final PipelineOptions OVERWRITE_BLOBS = fromString("OverwriteBlobs"); /** Static value DeleteSourceBlobOnSuccess for PipelineOptions. */ public static final PipelineOptions DELETE_SOURCE_BLOB_ON_SUCCESS = fromString("DeleteSourceBlobOnSuccess"); /** Static value ContinueOnErrors for PipelineOptions. */ public static final PipelineOptions CONTINUE_ON_ERRORS = fromString("ContinueOnErrors"); /** * Creates or finds a PipelineOptions from its string representation. * * @param name a name to look for. * @return the corresponding PipelineOptions. */ @JsonCreator public static PipelineOptions fromString(String name) { return fromString(name, PipelineOptions.class); } /** @return known PipelineOptions values. */ public static Collection<PipelineOptions> values() { return values(PipelineOptions.class); } }
alexandersinkovic/motis
modules/paxmon/include/motis/paxmon/service_info.h
<filename>modules/paxmon/include/motis/paxmon/service_info.h #pragma once #include <cstdint> #include <string> #include <string_view> #include <utility> #include <vector> #include "cista/reflection/comparable.h" #include "motis/core/schedule/schedule.h" #include "motis/paxmon/compact_journey.h" namespace motis::paxmon { struct service_info { CISTA_COMPARABLE(); std::string name_; std::string_view category_; std::uint32_t train_nr_{}; std::string_view line_; std::string_view provider_; service_class clasz_{service_class::OTHER}; }; service_info get_service_info(schedule const& sched, connection const& fc, connection_info const* ci); std::vector<std::pair<service_info, unsigned>> get_service_infos( schedule const& sched, trip const* trp); std::vector<std::pair<service_info, unsigned>> get_service_infos_for_leg( schedule const& sched, journey_leg const& leg); } // namespace motis::paxmon
cambw/mod-circulation
src/test/java/api/support/http/UserResource.java
package api.support.http; public class UserResource extends IndividualResource { public UserResource(IndividualResource resource) { super(resource.getResponse()); } public String getBarcode() { return response.getJson().getString("barcode"); } }
forkkit/webiny-js
packages/app-mailchimp/src/admin/components/MailchimpElement.js
<gh_stars>1-10 // @flow import * as React from "react"; import { ElementRoot } from "@webiny/app-page-builder/render/components/ElementRoot"; import { Form } from "@webiny/form"; import { get } from "lodash"; import { getPlugins } from "@webiny/plugins"; const MailchimpElement = React.memo(({ element }: *) => { let selected = get(element, "data.settings.component", get(element, "settings.component")); const component = getPlugins("pb-page-element-mailchimp-component").find( cmp => cmp.componentName === selected ); let render = <span>You must configure your embed in the settings!</span>; if (component) { const Component = component.component; render = ( <Form key={component.name}> {({ form }) => ( <Component processing={false} // It will suffice for editor preview needs. {...form} submit={async ({ onSuccess }) => { if (await form.validate()) { form.submit(); onSuccess && onSuccess(); } }} /> )} </Form> ); } return ( <ElementRoot key={component ? component.name : "no-component"} element={element} className={"webiny-pb-page-element-mailchimp"} > {render} </ElementRoot> ); }); MailchimpElement.displayName = "MailchimpElement"; export default MailchimpElement;
icecrystal23/onebusaway-iphone
models/dao/OBAModelDAO.h
/** * Copyright (C) 2009 bdferris <<EMAIL>> * * 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. */ #import "OBAStopV2.h" #import "OBABookmarkV2.h" #import "OBAStopAccessEventV2.h" #import "OBAStopPreferencesV2.h" #import "OBAServiceAlertsModel.h" #import "OBARegionV2.h" @class OBAModelDAOUserPreferencesImpl; @interface OBAModelDAO : NSObject { OBAModelDAOUserPreferencesImpl * _preferencesDao; NSMutableArray * _bookmarks; NSMutableArray * _bookmarkGroups; NSMutableArray * _mostRecentStops; NSMutableDictionary * _stopPreferences; CLLocation * _mostRecentLocation; NSMutableSet * _visitedSituationIds; OBARegionV2 * _region; NSMutableArray * _mostRecentCustomApiUrls; } @property (weak, nonatomic,readonly) NSArray * bookmarks; @property (weak, nonatomic,readonly) NSArray * bookmarkGroups; @property (weak, nonatomic,readonly) NSArray * mostRecentStops; @property (nonatomic,weak) CLLocation * mostRecentLocation; @property (nonatomic,readonly) OBARegionV2 * region; @property (weak, nonatomic,readonly) NSArray * mostRecentCustomApiUrls; - (OBABookmarkV2*) createTransientBookmark:(OBAStopV2*)stop; - (void) addNewBookmark:(OBABookmarkV2*)bookmark; - (void) saveExistingBookmark:(OBABookmarkV2*)bookmark; - (void) moveBookmark:(NSInteger)startIndex to:(NSInteger)endIndex; - (void) removeBookmark:(OBABookmarkV2*) bookmark; - (void) addOrSaveBookmarkGroup:(OBABookmarkGroup *)bookmarkGroup; - (void) removeBookmarkGroup:(OBABookmarkGroup*)bookmarkGroup; - (void) moveBookmark:(OBABookmarkV2*)bookmark toGroup:(OBABookmarkGroup*)group; - (void) moveBookmark:(NSInteger)startIndex to:(NSInteger)endIndex inGroup:(OBABookmarkGroup*)group; - (void) addStopAccessEvent:(OBAStopAccessEventV2*)event; - (OBAStopPreferencesV2*) stopPreferencesForStopWithId:(NSString*)stopId; - (void) setStopPreferences:(OBAStopPreferencesV2*)preferences forStopWithId:(NSString*)stopId; - (BOOL) isVisitedSituationWithId:(NSString*)situationId; - (void) setVisited:(BOOL)visited forSituationWithId:(NSString*)situationId; - (OBAServiceAlertsModel*) getServiceAlertsModelForSituations:(NSArray*)situations; - (void) setOBARegion:(OBARegionV2*)newRegion; /** * We persist hiding location warnings across application settings for users who have disabled location services for the app */ - (BOOL) hideFutureLocationWarnings; - (void) setHideFutureLocationWarnings:(BOOL)hideFutureLocationWarnings; - (BOOL) readSetRegionAutomatically; - (void) writeSetRegionAutomatically:(BOOL)setRegionAutomatically; - (NSString*) readCustomApiUrl; - (void) writeCustomApiUrl:(NSString*)customApiUrl; - (void) addCustomApiUrl:(NSString*)customApiUrl; @end
euspectre/syzkaller-repros
linux/8b456d9f4b011cb98abfcc9264b55420ad6f9ab0.c
<filename>linux/8b456d9f4b011cb98abfcc9264b55420ad6f9ab0.c // possible deadlock in generic_file_write_iter // https://syzkaller.appspot.com/bug?id=8b456d9f4b011cb98abfcc9264b55420ad6f9ab0 // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #ifndef __NR_memfd_create #define __NR_memfd_create 319 #endif #define _GNU_SOURCE #include <fcntl.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> static uintptr_t syz_open_dev(uintptr_t a0, uintptr_t a1, uintptr_t a2) { if (a0 == 0xc || a0 == 0xb) { char buf[128]; sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2); return open(buf, O_RDWR, 0); } else { char buf[1024]; char* hash; strncpy(buf, (char*)a0, sizeof(buf)); buf[sizeof(buf) - 1] = 0; while ((hash = strchr(buf, '#'))) { *hash = '0' + (char)(a1 % 10); a1 /= 10; } return open(buf, a2, 0); } } long r[15]; void* thr(void* arg) { switch ((long)arg) { case 0: r[0] = syscall(__NR_mmap, 0x20000000ul, 0xfff000ul, 0x3ul, 0x32ul, 0xfffffffffffffffful, 0x0ul); break; case 1: memcpy((void*)0x20ee1000, "\x2f\x64\x65\x76\x2f\x6c\x6f\x6f\x70\x23\x00", 11); r[2] = syz_open_dev(0x20ee1000ul, 0x0ul, 0x2ul); break; case 2: memcpy((void*)0x20000000, "\xff\xf8", 2); r[4] = syscall(__NR_memfd_create, 0x20000000ul, 0x2ul); break; case 3: *(uint64_t*)0x20fe6fb0 = (uint64_t)0x2064d000; *(uint64_t*)0x20fe6fb8 = (uint64_t)0x0; *(uint64_t*)0x20fe6fc0 = (uint64_t)0x20e04f4f; *(uint64_t*)0x20fe6fc8 = (uint64_t)0xb1; memcpy((void*)0x20e04f4f, "\x69\x7d\x06\x0c\xf9\xd8\xbc\x6d\xf3\xc8\x51\x00\x11\x43" "\x8b\xa2\x4e\xa2\xb2\x26\x10\xaa\xb4\xd2\xb6\xdc\xe4\xf2" "\xaa\x43\xff\xa8\xa9\xfa\x8a\x9e\x94\x2b\x2d\x65\x90\xea" "\xf4\x9c\xf0\xe3\xfd\x23\x85\x81\x42\xe0\x29\x53\xdf\xc6" "\x5f\xde\x3b\xb8\x56\x5c\xcf\x35\xc5\x5f\xc2\x48\xd0\xad" "\x6c\x47\x3f\x76\x63\x55\xd2\x2a\x9d\x2f\x43\xf4\x49\x3c" "\xd5\x07\xf9\x19\xab\x87\x3a\xa3\xc9\xfb\x28\x8f\x4a\xe3" "\xa1\x34\xda\x84\x40\xae\xee\x57\xd6\x4a\x2a\x47\x14\x2d" "\x56\x92\x64\xdd\x9e\xc1\xfa\x49\x25\x33\xe8\x14\x53\xf1" "\xad\x1d\xae\x61\xd9\xbe\x13\xe0\x70\xac\x9d\x36\xf4\x33" "\xc0\xf1\x2a\xe8\xd5\x6a\xf7\xfb\x38\x01\xa8\x29\xa6\x26" "\xa8\x7b\x14\x23\x5f\x44\xc2\x86\x51\xbf\x99\xa7\x80\x82" "\x94\x96\x57\xf7\x4b\x04\x8a\xe1\xca", 177); r[10] = syscall(__NR_pwritev, r[4], 0x20fe6fb0ul, 0x2ul, 0x80fcul); break; case 4: r[11] = syscall(__NR_ioctl, r[2], 0x4c00ul, r[4]); break; case 5: memcpy((void*)0x2034f000, "\x2f\x64\x65\x76\x2f\x6c\x6f\x6f\x70\x23\x00", 11); r[13] = syz_open_dev(0x2034f000ul, 0x0ul, 0x5ul); break; case 6: r[14] = syscall(__NR_fallocate, r[13], 0x11ul, 0x800ul, 0x44400004ul); break; } return 0; } void loop() { long i; pthread_t th[14]; memset(r, -1, sizeof(r)); srand(getpid()); for (i = 0; i < 7; i++) { pthread_create(&th[i], 0, thr, (void*)i); usleep(rand() % 10000); } for (i = 0; i < 7; i++) { pthread_create(&th[7 + i], 0, thr, (void*)i); if (rand() % 2) usleep(rand() % 10000); } usleep(rand() % 100000); } int main() { loop(); return 0; }
grapecity/codespark
common/models/user.js
<reponame>grapecity/codespark<gh_stars>0 let path = require('path'), validator = require('validator'), crypto = require('crypto'), mongoose = require('../utils/mongoose'), Schema = mongoose.Schema; function validateLocalStrategyEmail(email) { return ((this.provider !== 'local' && !this.updated) || validator.isEmail(email)); } let UserSchema = new Schema({ mail: { type: String, unique: true, required: true, sparse: true, lowercase: true, trim: true, validate: [validateLocalStrategyEmail, 'INVALID_EMAIL'] }, username: { type: String, required: true, lowercase: true, trim: true }, displayName: { type: String, trim: true }, password: { type: String, default: '', index: false }, salt: { type: String }, profileImageURL: { type: String, default: '', index: false }, provider: { type: String, default: 'local', required: 'Provider is required' }, providerData: {}, additionalProvidersData: {}, updated: { type: Date }, created: { type: Date, default: Date.now }, resetPasswordToken: { type: String }, resetPasswordExpires: { type: Date }, disabled: { type: Boolean, default: false }, activated: { type: Boolean, default: false }, activeToken: { type: String }, activeExpires: { type: Date } }, {collection: 'csUsers'} ); /** * Hook a pre save method to hash the password */ UserSchema.pre('save', function (next) { if (this.password && this.isModified('password')) { this.salt = crypto.randomBytes(16).toString('base64'); this.password = this.hashPassword(this.password); } if (!this.displayName) { this.displayName = this.email.substring(0, this.email.lastIndexOf('@')); } next(); }); /** * Create instance method for hashing a password */ UserSchema.methods.hashPassword = function (password) { if (this.salt && password) { return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 64, 'sha1').toString('base64'); } else { return password; } }; /** * Create instance method for authenticating user */ UserSchema.methods.authenticate = function (password) { return this.password === this.hashPassword(password); }; /** * Register user model. */ mongoose.model('User', UserSchema);
xxxcrel/algorithms
java/src/algs4/fundamentals/Vector.java
<reponame>xxxcrel/algorithms<filename>java/src/algs4/fundamentals/Vector.java /****************************************************************************** * Compilation: javac Vector.java * Execution: java Vector * Dependencies: StdOut.java * * Implementation of a vector of real numbers. * * This class is implemented to be immutable: once the client program * initialize a Vector, it cannot change any of its fields * (d or data[i]) either directly or indirectly. Immutability is a * very desirable feature of a data type. * * % java Vector * x = [ 1.0 2.0 3.0 4.0 ] * y = [ 5.0 2.0 4.0 1.0 ] * z = [ 6.0 4.0 7.0 5.0 ] * 10z = [ 60.0 40.0 70.0 50.0 ] * |x| = 5.477225575051661 * <x, y> = 25.0 * * * Note that Vector is also the name of an unrelated Java library class * in the package java.util. * ******************************************************************************/ package algs4.fundamentals; import algs4.edu.*; /** * The {@code Vector} class represents a <em>d</em>-dimensional Euclidean * vector. Vectors are immutable: their values cannot be changed after they are * created. It includes methods for addition, subtraction, dot product, scalar * product, unit vector, Euclidean norm, and the Euclidean distance between two * vectors. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/12oop">Section 1.2</a> of * <i>Algorithms, 4th Edition</i> by <NAME> and <NAME>. * * @author <NAME> * @author <NAME> */ public class Vector { private int d; // dimension of the vector private double[] data; // array of vector's components /** * Initializes a d-dimensional zero vector. * * @param d the dimension of the vector */ public Vector(int d) { this.d = d; data = new double[d]; } /** * Initializes a vector from either an array or a vararg list. The vararg syntax * supports a constructor that takes a variable number of arugments such as * Vector x = new Vector(1.0, 2.0, 3.0, 4.0). * * @param a the array or vararg list */ public Vector(double... a) { d = a.length; // defensive copy so that client can't alter our copy of data[] data = new double[d]; for (int i = 0; i < d; i++) data[i] = a[i]; } /** * Returns the length of this vector. * * @return the dimension of this vector * @deprecated Replaced by {@link #dimension()}. */ @Deprecated public int length() { return d; } /** * Returns the dimension of this vector. * * @return the dimension of this vector */ public int dimension() { return d; } /** * Returns the do product of this vector with the specified vector. * * @param that the other vector * @return the dot product of this vector and that vector * @throws IllegalArgumentException if the dimensions of the two vectors are not * equal */ public double dot(Vector that) { if (this.d != that.d) throw new IllegalArgumentException("Dimensions don't agree"); double sum = 0.0; for (int i = 0; i < d; i++) sum = sum + (this.data[i] * that.data[i]); return sum; } /** * Returns the magnitude of this vector. This is also known as the L2 norm or * the Euclidean norm. * * @return the magnitude of this vector */ public double magnitude() { return Math.sqrt(this.dot(this)); } /** * Returns the Euclidean distance between this vector and the specified vector. * * @param that the other vector * @return the Euclidean distance between this vector and that vector * @throws IllegalArgumentException if the dimensions of the two vectors are not * equal */ public double distanceTo(Vector that) { if (this.d != that.d) throw new IllegalArgumentException("Dimensions don't agree"); return this.minus(that).magnitude(); } /** * Returns the sum of this vector and the specified vector. * * @param that the vector to add to this vector * @return the vector whose value is {@code (this + that)} * @throws IllegalArgumentException if the dimensions of the two vectors are not * equal */ public Vector plus(Vector that) { if (this.d != that.d) throw new IllegalArgumentException("Dimensions don't agree"); Vector c = new Vector(d); for (int i = 0; i < d; i++) c.data[i] = this.data[i] + that.data[i]; return c; } /** * Returns the difference between this vector and the specified vector. * * @param that the vector to subtract from this vector * @return the vector whose value is {@code (this - that)} * @throws IllegalArgumentException if the dimensions of the two vectors are not * equal */ public Vector minus(Vector that) { if (this.d != that.d) throw new IllegalArgumentException("Dimensions don't agree"); Vector c = new Vector(d); for (int i = 0; i < d; i++) c.data[i] = this.data[i] - that.data[i]; return c; } /** * Returns the ith cartesian coordinate. * * @param i the coordinate index * @return the ith cartesian coordinate */ public double cartesian(int i) { return data[i]; } /** * Returns the scalar-vector product of this vector and the specified scalar * * @param alpha the scalar * @return the vector whose value is {@code (alpha * this)} * @deprecated Replaced by {@link #scale(double)}. */ @Deprecated public Vector times(double alpha) { Vector c = new Vector(d); for (int i = 0; i < d; i++) c.data[i] = alpha * data[i]; return c; } /** * Returns the scalar-vector product of this vector and the specified scalar * * @param alpha the scalar * @return the vector whose value is {@code (alpha * this)} */ public Vector scale(double alpha) { Vector c = new Vector(d); for (int i = 0; i < d; i++) c.data[i] = alpha * data[i]; return c; } /** * Returns a unit vector in the direction of this vector. * * @return a unit vector in the direction of this vector * @throws ArithmeticException if this vector is the zero vector */ public Vector direction() { if (this.magnitude() == 0.0) throw new ArithmeticException("Zero-vector has no direction"); return this.times(1.0 / this.magnitude()); } /** * Returns a string representation of this vector. * * @return a string representation of this vector, which consists of the the * vector entries, separates by single spaces */ @Override public String toString() { StringBuilder s = new StringBuilder(); for (int i = 0; i < d; i++) s.append(data[i] + " "); return s.toString(); } /** * Unit tests the {@code Vector} data type. * * @param args the command-line arguments */ public static void main(String[] args) { double[] xdata = { 1.0, 2.0, 3.0, 4.0 }; double[] ydata = { 5.0, 2.0, 4.0, 1.0 }; Vector x = new Vector(xdata); Vector y = new Vector(ydata); StdOut.println(" x = " + x); StdOut.println(" y = " + y); Vector z = x.plus(y); StdOut.println(" z = " + z); z = z.times(10.0); StdOut.println(" 10z = " + z); StdOut.println(" |x| = " + x.magnitude()); StdOut.println(" <x, y> = " + x.dot(y)); StdOut.println("dist(x, y) = " + x.distanceTo(y)); StdOut.println("dir(x) = " + x.direction()); } } /****************************************************************************** * Copyright 2002-2018, <NAME> and <NAME>. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by <NAME> and <NAME>, Addison-Wesley * Professional, 2011, ISBN 0-321-57351-X. http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * algs4.jar is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
mrslezak/Engine
OREData/test/ored_commodityforward.cpp
<reponame>mrslezak/Engine /* Copyright (C) 2018 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <boost/test/unit_test.hpp> #include <oret/toplevelfixture.hpp> #include <boost/make_shared.hpp> #include <ql/currencies/america.hpp> #include <ql/math/interpolations/linearinterpolation.hpp> #include <ql/termstructures/yield/flatforward.hpp> #include <qle/termstructures/pricecurve.hpp> #include <ored/marketdata/marketimpl.hpp> #include <ored/portfolio/builders/commodityforward.hpp> #include <ored/portfolio/commodityforward.hpp> #include <ored/portfolio/portfolio.hpp> using namespace std; using namespace boost::unit_test_framework; using namespace QuantLib; using namespace QuantExt; using namespace ore::data; namespace { // testTolerance for Real comparison Real testTolerance = 1e-10; class TestMarket : public MarketImpl { public: TestMarket() { // Reference date and common day counter asof_ = Date(19, Feb, 2018); Actual365Fixed dayCounter; // Add USD discount curve, discount = 1.0 everywhere Handle<YieldTermStructure> discount(boost::make_shared<FlatForward>(asof_, 0.0, dayCounter)); yieldCurves_[make_tuple(Market::defaultConfiguration, YieldCurveType::Discount, "USD")] = discount; // Add GOLD_USD price curve vector<Date> dates = {asof_, Date(19, Feb, 2019)}; vector<Real> prices = {1346.0, 1348.0}; Handle<PriceTermStructure> priceCurve( boost::make_shared<InterpolatedPriceCurve<Linear>>(asof_, dates, prices, dayCounter, USDCurrency())); Handle<CommodityIndex> commIdx(boost::make_shared<CommoditySpotIndex>("GOLD_USD", NullCalendar(), priceCurve)); commodityIndices_[make_pair(Market::defaultConfiguration, "GOLD_USD")] = commIdx; } }; } // namespace BOOST_FIXTURE_TEST_SUITE(OREDataTestSuite, ore::test::TopLevelFixture) BOOST_AUTO_TEST_SUITE(CommodityForwardTests) BOOST_AUTO_TEST_CASE(testCommodityForwardTradeBuilding) { BOOST_TEST_MESSAGE("Testing commodity forward trade building"); // Create market boost::shared_ptr<Market> market = boost::make_shared<TestMarket>(); Settings::instance().evaluationDate() = market->asofDate(); // Create engine factory boost::shared_ptr<EngineData> engineData = boost::make_shared<EngineData>(); engineData->model("CommodityForward") = "DiscountedCashflows"; engineData->engine("CommodityForward") = "DiscountingCommodityForwardEngine"; boost::shared_ptr<EngineFactory> engineFactory = boost::make_shared<EngineFactory>(engineData, market); // Base commodity values string position = "Long"; string commodityName = "GOLD_USD"; string currency = "USD"; Real quantity = 100.0; string maturity = "2019-02-19"; Real strike = 1340.0; // Test the building of a commodity forward doesn't throw Envelope envelope; boost::shared_ptr<ore::data::CommodityForward> forward = boost::make_shared<ore::data::CommodityForward>( envelope, position, commodityName, currency, quantity, maturity, strike); BOOST_CHECK_NO_THROW(forward->build(engineFactory)); // Check the instrument was built as expected boost::shared_ptr<Instrument> qlInstrument = forward->instrument()->qlInstrument(); boost::shared_ptr<QuantExt::CommodityForward> commodityForward = boost::dynamic_pointer_cast<QuantExt::CommodityForward>(qlInstrument); BOOST_CHECK(commodityForward); BOOST_CHECK_EQUAL(commodityForward->position(), Position::Type::Long); BOOST_CHECK_EQUAL(commodityForward->index()->name(), "COMM-GOLD_USD"); BOOST_CHECK_EQUAL(commodityForward->currency(), USDCurrency()); BOOST_CHECK_CLOSE(commodityForward->quantity(), 100.0, testTolerance); BOOST_CHECK_EQUAL(commodityForward->maturityDate(), Date(19, Feb, 2019)); BOOST_CHECK_CLOSE(commodityForward->strike(), 1340.0, testTolerance); // Check the price (simple because DF = 1.0, 100 * (1348 - 1340)) BOOST_CHECK_CLOSE(commodityForward->NPV(), 800.0, testTolerance); // Check short forward = boost::make_shared<ore::data::CommodityForward>(envelope, "Short", commodityName, currency, quantity, maturity, strike); BOOST_CHECK_NO_THROW(forward->build(engineFactory)); qlInstrument = forward->instrument()->qlInstrument(); commodityForward = boost::dynamic_pointer_cast<QuantExt::CommodityForward>(qlInstrument); BOOST_CHECK(commodityForward); BOOST_CHECK_EQUAL(commodityForward->position(), Position::Type::Short); BOOST_CHECK_CLOSE(commodityForward->NPV(), -800.0, testTolerance); // Check that negative quantity throws an error forward = boost::make_shared<ore::data::CommodityForward>(envelope, position, commodityName, currency, -quantity, maturity, strike); BOOST_CHECK_THROW(forward->build(engineFactory), Error); // Check that negative strike throws an error forward = boost::make_shared<ore::data::CommodityForward>(envelope, position, commodityName, currency, quantity, maturity, -strike); BOOST_CHECK_THROW(forward->build(engineFactory), Error); // Check that build fails when commodity name does not match that in the market forward = boost::make_shared<ore::data::CommodityForward>(envelope, position, "GOLD", currency, quantity, maturity, strike); BOOST_CHECK_THROW(forward->build(engineFactory), Error); } BOOST_AUTO_TEST_CASE(testCommodityForwardFromXml) { BOOST_TEST_MESSAGE("Testing parsing of commodity forward trade from XML"); // Create an XML string representation of the trade string tradeXml; tradeXml.append("<Portfolio>"); tradeXml.append(" <Trade id=\"CommodityForward_WTI_Oct_21\">"); tradeXml.append(" <TradeType>CommodityForward</TradeType>"); tradeXml.append(" <Envelope>"); tradeXml.append(" <CounterParty>CPTY_A</CounterParty>"); tradeXml.append(" <NettingSetId>CPTY_A</NettingSetId>"); tradeXml.append(" <AdditionalFields/>"); tradeXml.append(" </Envelope>"); tradeXml.append(" <CommodityForwardData>"); tradeXml.append(" <Position>Short</Position>"); tradeXml.append(" <Maturity>2021-10-31</Maturity>"); tradeXml.append(" <Name>COMDTY_WTI_USD</Name>"); tradeXml.append(" <Currency>USD</Currency>"); tradeXml.append(" <Strike>49.75</Strike>"); tradeXml.append(" <Quantity>500000</Quantity>"); tradeXml.append(" </CommodityForwardData>"); tradeXml.append(" </Trade>"); tradeXml.append("</Portfolio>"); // Load portfolio from XML string Portfolio portfolio; portfolio.loadFromXMLString(tradeXml); // Extract CommodityForward trade from portfolio boost::shared_ptr<Trade> trade = portfolio.trades()[0]; boost::shared_ptr<ore::data::CommodityForward> commodityForward = boost::dynamic_pointer_cast<ore::data::CommodityForward>(trade); // Check fields after checking that the cast was successful BOOST_CHECK(commodityForward); BOOST_CHECK_EQUAL(commodityForward->tradeType(), "CommodityForward"); BOOST_CHECK_EQUAL(commodityForward->id(), "CommodityForward_WTI_Oct_21"); BOOST_CHECK_EQUAL(commodityForward->position(), "Short"); BOOST_CHECK_EQUAL(commodityForward->maturityDate(), "2021-10-31"); BOOST_CHECK_EQUAL(commodityForward->commodityName(), "COMDTY_WTI_USD"); BOOST_CHECK_EQUAL(commodityForward->currency(), "USD"); BOOST_CHECK_CLOSE(commodityForward->strike(), 49.75, testTolerance); BOOST_CHECK_CLOSE(commodityForward->quantity(), 500000.0, testTolerance); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
andersdellien/pyelftools
test/test_compressed_support.py
#------------------------------------------------------------------------------- # Test handling for compressed debug sections # # <NAME> (<EMAIL>) # This code is in the public domain #------------------------------------------------------------------------------- from contextlib import contextmanager import os import unittest from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFCompressionError class TestCompressedSupport(unittest.TestCase): def test_compressed_32(self): with self.elffile('32') as elf: section = elf.get_section_by_name('.debug_info') self.assertTrue(section.compressed) self.assertEqual(section.data_size, 0x330) self.assertEqual(section.data_alignment, 1) self.assertEqual(self.get_cus_info(elf), ['CU 0x0: 0xb-0x322']) def test_compressed_64(self): with self.elffile('64') as elf: section = elf.get_section_by_name('.debug_info') self.assertTrue(section.compressed) self.assertEqual(section.data_size, 0x327) self.assertEqual(section.data_alignment, 1) self.assertEqual(self.get_cus_info(elf), ['CU 0x0: 0xb-0x319']) def test_compressed_unknown_type(self): with self.elffile('unknown_type') as elf: section = elf.get_section_by_name('.debug_info') try: section.data() except ELFCompressionError as exc: self.assertEqual( str(exc), 'Unknown compression type: 0x7ffffffe' ) else: self.fail('An exception was exected') def test_compressed_bad_size(self): with self.elffile('bad_size') as elf: section = elf.get_section_by_name('.debug_info') try: section.data() except ELFCompressionError as exc: self.assertEqual( str(exc), 'Decompressed data is 807 bytes long, should be 808 bytes' ' long' ) else: self.fail('An exception was exected') # Test helpers @contextmanager def elffile(self, name): """ Context manager to open and parse an ELF file. """ with open(os.path.join('test', 'testfiles_for_unittests', 'compressed_{}.o'.format(name)), 'rb') as f: yield ELFFile(f) def get_cus_info(self, elffile): """ Return basic info about the compile units in `elffile`. This is used as a basic sanity check for decompressed DWARF data. """ result = [] dwarf = elffile.get_dwarf_info() for cu in dwarf.iter_CUs(): dies = [] def traverse(die): dies.append(die.offset) for child in die.iter_children(): traverse(child) traverse(cu.get_top_DIE()) result.append('CU {:#0x}: {:#0x}-{:#0x}'.format( cu.cu_offset, dies[0], dies[-1] )) return result
joschout/Multi-Directional-Rule-Set-Learning
mdrsl/rule_models/mids/model_fitting/mids_with_value_reuse.py
from typing import Optional, Dict, Type, Set from mdrsl.rule_models.mids.model_fitting.mids_abstract_base import MIDSAbstractBase from mdrsl.rule_models.mids.objective_function.mids_objective_function_parameters import ObjectiveFunctionParameters from mdrsl.rule_models.mids.objective_function.mids_objective_function_value_reuse import MIDSObjectiveFunctionValueReuse, MIDSFuncInfo from mdrsl.rule_models.mids.mids_rule import MIDSRule from submodmax.value_reuse.abstract_optimizer import AbstractOptimizerValueReuse from submodmax.value_reuse.deterministic_double_greedy_search import DeterministicDoubleGreedySearch from submodmax.value_reuse.deterministic_local_search_simple_value_reuse import DeterministicLocalSearchValueReuse from submodmax.value_reuse.randomized_double_greedy_search import RandomizedDoubleGreedySearch from submodmax.value_reuse.set_info import SetInfo from submodmax.value_reuse.ground_set_returner import GroundSetReturner class MIDSValueReuse(MIDSAbstractBase): """ Encapsulates the MIDS algorithm. """ algorithms: Dict[str, Type[AbstractOptimizerValueReuse]] = dict( DLS=DeterministicLocalSearchValueReuse, DDGS=DeterministicDoubleGreedySearch, RDGS=RandomizedDoubleGreedySearch, GroundSetReturner=GroundSetReturner ) def __init__(self): super().__init__() self.rule_set_info: Optional[SetInfo] = None self.obj_func_val_info: Optional[MIDSFuncInfo] = None def _optimize(self, objective_function_parameters: ObjectiveFunctionParameters, algorithm: str, objective_scale_factor: float, debug: bool) -> Set[MIDSRule]: # init objective function objective_function = MIDSObjectiveFunctionValueReuse(objective_func_params=objective_function_parameters, cover_checker=self.cover_checker, overlap_checker=self.overlap_checker, scale_factor=objective_scale_factor) self.objective_function = objective_function optimizer: AbstractOptimizerValueReuse = self.algorithms[algorithm]( objective_function=objective_function, ground_set=objective_function_parameters.all_rules.ruleset, debug=debug) rule_set_info: SetInfo obj_func_val_info: MIDSFuncInfo rule_set_info, obj_func_val_info = optimizer.optimize() self.rule_set_info = rule_set_info self.obj_func_val_info = obj_func_val_info solution_set = rule_set_info.current_set self.nb_of_objective_function_calls_necessary_for_training = objective_function.call_counter return solution_set
Charged/CCChargedMinersLauncher
CCChargedMinersLauncher/src/com/chargedminers/launcher/gui/PromptScreen.java
package com.chargedminers.launcher.gui; import java.awt.Dimension; import java.awt.Frame; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class PromptScreen extends javax.swing.JDialog { public static String show(final String title, final String message, final String placeholder, final boolean allowModification) { PromptScreen screen = new PromptScreen(title, message, placeholder, allowModification); screen.setVisible(true); return screen.input; } private String input; private PromptScreen(final String title, final String message, final String placeholder, final boolean allowModification) { // set title, add border super((Frame) null, title, true); // set background final ImagePanel bgPanel = new ImagePanel(null, true); bgPanel.setGradient(true); bgPanel.setImage(Resources.getClassiCubeBackground()); bgPanel.setGradientColor(Resources.colorGradient); bgPanel.setBorder(new EmptyBorder(8, 8, 8, 8)); setContentPane(bgPanel); initComponents(); this.tInput.setText(placeholder); this.tInput.selectAll(); this.tInput.setEditable(allowModification); this.tInput.getDocument().addDocumentListener(new TextChangeListener()); // print the message if (message.startsWith("<html>")) { this.lMessage.setText(message); } else { this.lMessage.setText("<html><b>" + message); } // focus & highlight [OK] getRootPane().setDefaultButton(bOK); // Show GridBagLayout who's boss. this.imgErrorIcon.setImage(Resources.getInfoIcon()); this.imgErrorIcon.setMinimumSize(new Dimension(64, 64)); this.imgErrorIcon.setPreferredSize(new Dimension(64, 64)); this.imgErrorIcon.setSize(new Dimension(64, 64)); // Add cut/copy/paste menu to text box CutCopyPasteAdapter.addToComponent(tInput, true, allowModification); // Set windows icon and location this.setIconImages(Resources.getWindowIcons()); pack(); setLocationRelativeTo(null); } class TextChangeListener implements DocumentListener { @Override public void changedUpdate(DocumentEvent e) { onTextChange(); } @Override public void removeUpdate(DocumentEvent e) { onTextChange(); } @Override public void insertUpdate(DocumentEvent e) { onTextChange(); } } void onTextChange() { this.bOK.setEnabled(!tInput.getText().isEmpty()); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT * modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; imgErrorIcon = new com.chargedminers.launcher.gui.ImagePanel(); lMessage = new javax.swing.JLabel(); bOK = new com.chargedminers.launcher.gui.JNiceLookingButton(); bNo = new com.chargedminers.launcher.gui.JNiceLookingButton(); tInput = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setType(java.awt.Window.Type.UTILITY); getContentPane().setLayout(new java.awt.GridBagLayout()); imgErrorIcon.setMaximumSize(new java.awt.Dimension(64, 64)); imgErrorIcon.setMinimumSize(new java.awt.Dimension(64, 64)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8); getContentPane().add(imgErrorIcon, gridBagConstraints); lMessage.setForeground(new java.awt.Color(255, 255, 255)); lMessage.setText("Someone set up us the bomb!"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; getContentPane().add(lMessage, gridBagConstraints); bOK.setText("OK"); bOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bOKActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END; gridBagConstraints.weightx = 0.1; getContentPane().add(bOK, gridBagConstraints); bNo.setText("Cancel"); bNo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bNoActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END; getContentPane().add(bNo, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8); getContentPane().add(tInput, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void bNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNoActionPerformed dispose(); }//GEN-LAST:event_bNoActionPerformed private void bOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bOKActionPerformed this.input = this.tInput.getText(); dispose(); }//GEN-LAST:event_bOKActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private com.chargedminers.launcher.gui.JNiceLookingButton bNo; private com.chargedminers.launcher.gui.JNiceLookingButton bOK; private com.chargedminers.launcher.gui.ImagePanel imgErrorIcon; private javax.swing.JLabel lMessage; private javax.swing.JTextField tInput; // End of variables declaration//GEN-END:variables }
yonfong/OSChina
OSChina/OSCEventPersonInfo.h
// // OSCEventPersonInfo.h // OSChina // // Created by sky on 15/7/15. // Copyright (c) 2015年 bluesky. All rights reserved. // #import "OSCBaseObject.h" @interface OSCEventPersonInfo : OSCBaseObject @property (nonatomic, readonly, copy ) NSString *userName; @property (nonatomic, readonly, assign) int64_t userID; @property (nonatomic, readonly, strong) NSURL *portraitURL; @property (nonatomic, readonly, copy ) NSString *company; @property (nonatomic, readonly, copy ) NSString *job; @end
Mpetrel/graduate
app/account/service/cmd/server/wire_gen.go
// Code generated by Wire. DO NOT EDIT. //go:generate go run github.com/google/wire/cmd/wire //+build !wireinject package main import ( "base-service/app/account/service/internal/biz" "base-service/app/account/service/internal/conf" "base-service/app/account/service/internal/data" "base-service/app/account/service/internal/server" "base-service/app/account/service/internal/service" "github.com/go-kratos/kratos/v2" "github.com/go-kratos/kratos/v2/log" ) // Injectors from wire.go: // initApp init kratos application. func initApp(confServer *conf.Server, registry *conf.Registry, confData *conf.Data, logger log.Logger) (*kratos.App, func(), error) { dataData, cleanup, err := data.NewData(confData, logger) if err != nil { return nil, nil, err } accountRepo := data.NewAccountRepo(dataData, logger) accountUsecase := biz.NewAccountUsecase(accountRepo, logger) accountService := service.NewAccountService(accountUsecase, logger) httpServer := server.NewHTTPServer(confServer, accountService, logger) grpcServer := server.NewGRPCServer(confServer, accountService, logger) registrar := server.NewRegistrar(registry) app := newApp(logger, httpServer, grpcServer, registrar) return app, func() { cleanup() }, nil }
cristim/aws-cdk-go
awscdk/awskinesis/awskinesis.init.go
package awskinesis import ( "reflect" _jsii_ "github.com/aws/jsii-runtime-go" ) func init() { _jsii_.RegisterClass( "monocdk.aws_kinesis.CfnStream", reflect.TypeOf((*CfnStream)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "addDeletionOverride", GoMethod: "AddDeletionOverride"}, _jsii_.MemberMethod{JsiiMethod: "addDependsOn", GoMethod: "AddDependsOn"}, _jsii_.MemberMethod{JsiiMethod: "addMetadata", GoMethod: "AddMetadata"}, _jsii_.MemberMethod{JsiiMethod: "addOverride", GoMethod: "AddOverride"}, _jsii_.MemberMethod{JsiiMethod: "addPropertyDeletionOverride", GoMethod: "AddPropertyDeletionOverride"}, _jsii_.MemberMethod{JsiiMethod: "addPropertyOverride", GoMethod: "AddPropertyOverride"}, _jsii_.MemberMethod{JsiiMethod: "applyRemovalPolicy", GoMethod: "ApplyRemovalPolicy"}, _jsii_.MemberProperty{JsiiProperty: "attrArn", GoGetter: "AttrArn"}, _jsii_.MemberProperty{JsiiProperty: "cfnOptions", GoGetter: "CfnOptions"}, _jsii_.MemberProperty{JsiiProperty: "cfnProperties", GoGetter: "CfnProperties"}, _jsii_.MemberProperty{JsiiProperty: "cfnResourceType", GoGetter: "CfnResourceType"}, _jsii_.MemberProperty{JsiiProperty: "creationStack", GoGetter: "CreationStack"}, _jsii_.MemberMethod{JsiiMethod: "getAtt", GoMethod: "GetAtt"}, _jsii_.MemberMethod{JsiiMethod: "getMetadata", GoMethod: "GetMetadata"}, _jsii_.MemberMethod{JsiiMethod: "inspect", GoMethod: "Inspect"}, _jsii_.MemberProperty{JsiiProperty: "logicalId", GoGetter: "LogicalId"}, _jsii_.MemberProperty{JsiiProperty: "name", GoGetter: "Name"}, _jsii_.MemberProperty{JsiiProperty: "node", GoGetter: "Node"}, _jsii_.MemberMethod{JsiiMethod: "onPrepare", GoMethod: "OnPrepare"}, _jsii_.MemberMethod{JsiiMethod: "onSynthesize", GoMethod: "OnSynthesize"}, _jsii_.MemberMethod{JsiiMethod: "onValidate", GoMethod: "OnValidate"}, _jsii_.MemberMethod{JsiiMethod: "overrideLogicalId", GoMethod: "OverrideLogicalId"}, _jsii_.MemberMethod{JsiiMethod: "prepare", GoMethod: "Prepare"}, _jsii_.MemberProperty{JsiiProperty: "ref", GoGetter: "Ref"}, _jsii_.MemberMethod{JsiiMethod: "renderProperties", GoMethod: "RenderProperties"}, _jsii_.MemberProperty{JsiiProperty: "retentionPeriodHours", GoGetter: "RetentionPeriodHours"}, _jsii_.MemberProperty{JsiiProperty: "shardCount", GoGetter: "ShardCount"}, _jsii_.MemberMethod{JsiiMethod: "shouldSynthesize", GoMethod: "ShouldSynthesize"}, _jsii_.MemberProperty{JsiiProperty: "stack", GoGetter: "Stack"}, _jsii_.MemberProperty{JsiiProperty: "streamEncryption", GoGetter: "StreamEncryption"}, _jsii_.MemberMethod{JsiiMethod: "synthesize", GoMethod: "Synthesize"}, _jsii_.MemberProperty{JsiiProperty: "tags", GoGetter: "Tags"}, _jsii_.MemberMethod{JsiiMethod: "toString", GoMethod: "ToString"}, _jsii_.MemberProperty{JsiiProperty: "updatedProperites", GoGetter: "UpdatedProperites"}, _jsii_.MemberMethod{JsiiMethod: "validate", GoMethod: "Validate"}, _jsii_.MemberMethod{JsiiMethod: "validateProperties", GoMethod: "ValidateProperties"}, }, func() interface{} { j := jsiiProxy_CfnStream{} _jsii_.InitJsiiProxy(&j.Type__awscdkCfnResource) _jsii_.InitJsiiProxy(&j.Type__awscdkIInspectable) return &j }, ) _jsii_.RegisterStruct( "monocdk.aws_kinesis.CfnStream.StreamEncryptionProperty", reflect.TypeOf((*CfnStream_StreamEncryptionProperty)(nil)).Elem(), ) _jsii_.RegisterClass( "monocdk.aws_kinesis.CfnStreamConsumer", reflect.TypeOf((*CfnStreamConsumer)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "addDeletionOverride", GoMethod: "AddDeletionOverride"}, _jsii_.MemberMethod{JsiiMethod: "addDependsOn", GoMethod: "AddDependsOn"}, _jsii_.MemberMethod{JsiiMethod: "addMetadata", GoMethod: "AddMetadata"}, _jsii_.MemberMethod{JsiiMethod: "addOverride", GoMethod: "AddOverride"}, _jsii_.MemberMethod{JsiiMethod: "addPropertyDeletionOverride", GoMethod: "AddPropertyDeletionOverride"}, _jsii_.MemberMethod{JsiiMethod: "addPropertyOverride", GoMethod: "AddPropertyOverride"}, _jsii_.MemberMethod{JsiiMethod: "applyRemovalPolicy", GoMethod: "ApplyRemovalPolicy"}, _jsii_.MemberProperty{JsiiProperty: "attrConsumerArn", GoGetter: "AttrConsumerArn"}, _jsii_.MemberProperty{JsiiProperty: "attrConsumerCreationTimestamp", GoGetter: "AttrConsumerCreationTimestamp"}, _jsii_.MemberProperty{JsiiProperty: "attrConsumerName", GoGetter: "AttrConsumerName"}, _jsii_.MemberProperty{JsiiProperty: "attrConsumerStatus", GoGetter: "AttrConsumerStatus"}, _jsii_.MemberProperty{JsiiProperty: "attrStreamArn", GoGetter: "AttrStreamArn"}, _jsii_.MemberProperty{JsiiProperty: "cfnOptions", GoGetter: "CfnOptions"}, _jsii_.MemberProperty{JsiiProperty: "cfnProperties", GoGetter: "CfnProperties"}, _jsii_.MemberProperty{JsiiProperty: "cfnResourceType", GoGetter: "CfnResourceType"}, _jsii_.MemberProperty{JsiiProperty: "consumerName", GoGetter: "ConsumerName"}, _jsii_.MemberProperty{JsiiProperty: "creationStack", GoGetter: "CreationStack"}, _jsii_.MemberMethod{JsiiMethod: "getAtt", GoMethod: "GetAtt"}, _jsii_.MemberMethod{JsiiMethod: "getMetadata", GoMethod: "GetMetadata"}, _jsii_.MemberMethod{JsiiMethod: "inspect", GoMethod: "Inspect"}, _jsii_.MemberProperty{JsiiProperty: "logicalId", GoGetter: "LogicalId"}, _jsii_.MemberProperty{JsiiProperty: "node", GoGetter: "Node"}, _jsii_.MemberMethod{JsiiMethod: "onPrepare", GoMethod: "OnPrepare"}, _jsii_.MemberMethod{JsiiMethod: "onSynthesize", GoMethod: "OnSynthesize"}, _jsii_.MemberMethod{JsiiMethod: "onValidate", GoMethod: "OnValidate"}, _jsii_.MemberMethod{JsiiMethod: "overrideLogicalId", GoMethod: "OverrideLogicalId"}, _jsii_.MemberMethod{JsiiMethod: "prepare", GoMethod: "Prepare"}, _jsii_.MemberProperty{JsiiProperty: "ref", GoGetter: "Ref"}, _jsii_.MemberMethod{JsiiMethod: "renderProperties", GoMethod: "RenderProperties"}, _jsii_.MemberMethod{JsiiMethod: "shouldSynthesize", GoMethod: "ShouldSynthesize"}, _jsii_.MemberProperty{JsiiProperty: "stack", GoGetter: "Stack"}, _jsii_.MemberProperty{JsiiProperty: "streamArn", GoGetter: "StreamArn"}, _jsii_.MemberMethod{JsiiMethod: "synthesize", GoMethod: "Synthesize"}, _jsii_.MemberMethod{JsiiMethod: "toString", GoMethod: "ToString"}, _jsii_.MemberProperty{JsiiProperty: "updatedProperites", GoGetter: "UpdatedProperites"}, _jsii_.MemberMethod{JsiiMethod: "validate", GoMethod: "Validate"}, _jsii_.MemberMethod{JsiiMethod: "validateProperties", GoMethod: "ValidateProperties"}, }, func() interface{} { j := jsiiProxy_CfnStreamConsumer{} _jsii_.InitJsiiProxy(&j.Type__awscdkCfnResource) _jsii_.InitJsiiProxy(&j.Type__awscdkIInspectable) return &j }, ) _jsii_.RegisterStruct( "monocdk.aws_kinesis.CfnStreamConsumerProps", reflect.TypeOf((*CfnStreamConsumerProps)(nil)).Elem(), ) _jsii_.RegisterStruct( "monocdk.aws_kinesis.CfnStreamProps", reflect.TypeOf((*CfnStreamProps)(nil)).Elem(), ) _jsii_.RegisterInterface( "monocdk.aws_kinesis.IStream", reflect.TypeOf((*IStream)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberProperty{JsiiProperty: "encryptionKey", GoGetter: "EncryptionKey"}, _jsii_.MemberProperty{JsiiProperty: "env", GoGetter: "Env"}, _jsii_.MemberMethod{JsiiMethod: "grant", GoMethod: "Grant"}, _jsii_.MemberMethod{JsiiMethod: "grantRead", GoMethod: "GrantRead"}, _jsii_.MemberMethod{JsiiMethod: "grantReadWrite", GoMethod: "GrantReadWrite"}, _jsii_.MemberMethod{JsiiMethod: "grantWrite", GoMethod: "GrantWrite"}, _jsii_.MemberProperty{JsiiProperty: "node", GoGetter: "Node"}, _jsii_.MemberProperty{JsiiProperty: "stack", GoGetter: "Stack"}, _jsii_.MemberProperty{JsiiProperty: "streamArn", GoGetter: "StreamArn"}, _jsii_.MemberProperty{JsiiProperty: "streamName", GoGetter: "StreamName"}, }, func() interface{} { j := jsiiProxy_IStream{} _jsii_.InitJsiiProxy(&j.Type__awscdkIResource) return &j }, ) _jsii_.RegisterClass( "monocdk.aws_kinesis.Stream", reflect.TypeOf((*Stream)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "applyRemovalPolicy", GoMethod: "ApplyRemovalPolicy"}, _jsii_.MemberProperty{JsiiProperty: "encryptionKey", GoGetter: "EncryptionKey"}, _jsii_.MemberProperty{JsiiProperty: "env", GoGetter: "Env"}, _jsii_.MemberMethod{JsiiMethod: "generatePhysicalName", GoMethod: "GeneratePhysicalName"}, _jsii_.MemberMethod{JsiiMethod: "getResourceArnAttribute", GoMethod: "GetResourceArnAttribute"}, _jsii_.MemberMethod{JsiiMethod: "getResourceNameAttribute", GoMethod: "GetResourceNameAttribute"}, _jsii_.MemberMethod{JsiiMethod: "grant", GoMethod: "Grant"}, _jsii_.MemberMethod{JsiiMethod: "grantRead", GoMethod: "GrantRead"}, _jsii_.MemberMethod{JsiiMethod: "grantReadWrite", GoMethod: "GrantReadWrite"}, _jsii_.MemberMethod{JsiiMethod: "grantWrite", GoMethod: "GrantWrite"}, _jsii_.MemberProperty{JsiiProperty: "node", GoGetter: "Node"}, _jsii_.MemberMethod{JsiiMethod: "onPrepare", GoMethod: "OnPrepare"}, _jsii_.MemberMethod{JsiiMethod: "onSynthesize", GoMethod: "OnSynthesize"}, _jsii_.MemberMethod{JsiiMethod: "onValidate", GoMethod: "OnValidate"}, _jsii_.MemberProperty{JsiiProperty: "physicalName", GoGetter: "PhysicalName"}, _jsii_.MemberMethod{JsiiMethod: "prepare", GoMethod: "Prepare"}, _jsii_.MemberProperty{JsiiProperty: "stack", GoGetter: "Stack"}, _jsii_.MemberProperty{JsiiProperty: "streamArn", GoGetter: "StreamArn"}, _jsii_.MemberProperty{JsiiProperty: "streamName", GoGetter: "StreamName"}, _jsii_.MemberMethod{JsiiMethod: "synthesize", GoMethod: "Synthesize"}, _jsii_.MemberMethod{JsiiMethod: "toString", GoMethod: "ToString"}, _jsii_.MemberMethod{JsiiMethod: "validate", GoMethod: "Validate"}, }, func() interface{} { j := jsiiProxy_Stream{} _jsii_.InitJsiiProxy(&j.Type__awscdkResource) _jsii_.InitJsiiProxy(&j.jsiiProxy_IStream) return &j }, ) _jsii_.RegisterStruct( "monocdk.aws_kinesis.StreamAttributes", reflect.TypeOf((*StreamAttributes)(nil)).Elem(), ) _jsii_.RegisterEnum( "monocdk.aws_kinesis.StreamEncryption", reflect.TypeOf((*StreamEncryption)(nil)).Elem(), map[string]interface{}{ "UNENCRYPTED": StreamEncryption_UNENCRYPTED, "KMS": StreamEncryption_KMS, "MANAGED": StreamEncryption_MANAGED, }, ) _jsii_.RegisterStruct( "monocdk.aws_kinesis.StreamProps", reflect.TypeOf((*StreamProps)(nil)).Elem(), ) }
bogdansava/egeria-test
open-metadata-implementation/access-services/glossary-view/glossary-view-server/src/main/java/org/odpi/openmetadata/accessservices/glossaryview/server/service/GlossaryViewOMAS.java
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.glossaryview.server.service; import org.odpi.openmetadata.accessservices.glossaryview.exception.OMRSExceptionWrapper; import org.odpi.openmetadata.accessservices.glossaryview.exception.OMRSRuntimeExceptionWrapper; import org.odpi.openmetadata.accessservices.glossaryview.rest.GlossaryViewClassification; import org.odpi.openmetadata.accessservices.glossaryview.rest.GlossaryViewEntityDetail; import org.odpi.openmetadata.accessservices.glossaryview.rest.GlossaryViewEntityDetailResponse; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.Classification; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.EntityDetail; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceProperties; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.Relationship; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper; import org.springframework.http.HttpStatus; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Composes OMRS calls into needed operations, handles the exceptions specific to this OMAS, converts result to needed * format */ public class GlossaryViewOMAS extends OMRSClient { private final static String GLOSSARY_VIEW_OMAS = "Glossary View Omas"; /** * Converts a {@code Classification} into a {@code GlossaryViewClassification} with the help of a {@code OMRSRepositoryHelper} * * @param classification * @param helper * * @return glossaryViewClassification */ private final BiFunction<Classification, OMRSRepositoryHelper, GlossaryViewClassification> classificationConverter = (classification, helper) -> { GlossaryViewClassification glossaryViewClassification = new GlossaryViewClassification(); glossaryViewClassification.setName(classification.getName()); glossaryViewClassification.setClassificationType(classification.getType().getTypeDefName()); glossaryViewClassification.setCreatedBy(classification.getCreatedBy()); glossaryViewClassification.setUpdatedBy(classification.getUpdatedBy()); glossaryViewClassification.setCreateTime(classification.getCreateTime()); glossaryViewClassification.setUpdateTime(classification.getUpdateTime()); glossaryViewClassification.setStatus(classification.getStatus().getName()); classification.getProperties().getInstanceProperties().entrySet().stream() .forEach( incoming -> { glossaryViewClassification.addProperty(incoming.getKey(), helper.getStringProperty(GLOSSARY_VIEW_OMAS, incoming.getKey(), classification.getProperties(), "GlossaryViewOMAS.classificationConverter.apply")); }); return glossaryViewClassification; }; /** * Converts an {@code EntityDetail} into a {@code GlossaryViewEntityDetail} with the help of a {@code OMRSRepositoryHelper} * * @param entityDetail * @param helper * * @return glossaryViewEntityDetail */ private final BiFunction<EntityDetail, OMRSRepositoryHelper, GlossaryViewEntityDetail> entityDetailConverter = (entityDetail, helper) -> { Optional<InstanceProperties> optionalProperties = Optional.ofNullable(entityDetail.getProperties()); GlossaryViewEntityDetail glossaryViewEntityDetail = new GlossaryViewEntityDetail() .setEntityType(entityDetail.getType().getTypeDefName()) .setCreatedBy(entityDetail.getCreatedBy()) .setUpdatedBy(entityDetail.getUpdatedBy()) .setCreateTime(entityDetail.getCreateTime()) .setUpdateTime(entityDetail.getUpdateTime()) .setVersion(entityDetail.getVersion()) .setGuid(entityDetail.getGUID()) .setStatus(entityDetail.getStatus().getName()); /*Encountered a case where an entity did not have properties. However, this should not be possible in non-dev envs*/ if(optionalProperties.isPresent()){ glossaryViewEntityDetail.setEffectiveFromTime(optionalProperties.get().getEffectiveFromTime()); glossaryViewEntityDetail.setEffectiveToTime(optionalProperties.get().getEffectiveToTime()); optionalProperties.get().getInstanceProperties().entrySet() .forEach( incoming -> { glossaryViewEntityDetail.putProperty(incoming.getKey(), helper.getStringProperty(GLOSSARY_VIEW_OMAS, incoming.getKey(), optionalProperties.get(), "GlossaryViewOMAS.entityDetailConverter.apply")); }); } if(entityDetail.getClassifications() != null) { glossaryViewEntityDetail.addClassifications(entityDetail.getClassifications().stream() .map(c -> classificationConverter.apply(c, helper)).collect(Collectors.toList())); } return glossaryViewEntityDetail; }; /** * Extract an entity based on provided GUID * * @param userId calling user * @param serverName instance to call * @param entityGUID guid to search for * * @return EntityDetailResponse entity */ protected GlossaryViewEntityDetailResponse getEntityDetailResponse(String userId, String serverName, String entityGUID){ GlossaryViewEntityDetailResponse response = new GlossaryViewEntityDetailResponse(); try { Optional<EntityDetail> entityDetail = getEntityDetail(userId, serverName, entityGUID); Optional<OMRSRepositoryHelper> omrsRepositoryHelper = getOMRSRepositoryHelper(serverName); if( entityDetail.isPresent() && omrsRepositoryHelper.isPresent()) { response.addEntityDetail(entityDetailConverter.apply(entityDetail.get(), omrsRepositoryHelper.get())); } }catch (OMRSExceptionWrapper e){ prepare(response, e); } return response; } /** * Extract all entities related to given entity. This is done by first extracting the GUID for specified * relationship type, then the actual relationships and, ultimately, the entities at end two of these relationships * * @param userId calling user * @param serverName instance to call * @param relationshipEndOneEntityGUID entity for which we extract relationships * @param relationshipTypeDefNames relationship type * * @return EntityDetailResponse related entities */ protected GlossaryViewEntityDetailResponse getRelatedEntities(String userId, String serverName, String relationshipEndOneEntityGUID, String relationshipTypeDefNames){ GlossaryViewEntityDetailResponse response = new GlossaryViewEntityDetailResponse(); try { String relationshipTypeGUIDs = getTypeDefGUIDs(userId, serverName, relationshipTypeDefNames).get(0); List<Relationship> relationships = getRelationships(userId, serverName, relationshipEndOneEntityGUID, relationshipTypeGUIDs); List<EntityDetail> entities = getEntityDetails(userId, serverName, relationships, entityProxyTwoGUIDExtractor); Optional<OMRSRepositoryHelper> omrsRepositoryHelper = getOMRSRepositoryHelper(serverName); response.addEntityDetails(entities.stream() .map(entity -> entityDetailConverter.apply(entity, omrsRepositoryHelper.get())) .collect(Collectors.toList())); }catch (OMRSExceptionWrapper e){ prepare(response, e); }catch (OMRSRuntimeExceptionWrapper ew){ prepare(response, ew); } return response; } /** * Extract all entities of specified type * * @param userId calling user * @param serverName instance to call * @param typeDefName entity type name * * @return EntityDetailResponse all entities */ protected GlossaryViewEntityDetailResponse getAllEntityDetailsResponse(String userId, String serverName, String typeDefName){ GlossaryViewEntityDetailResponse response = new GlossaryViewEntityDetailResponse(); try { List<EntityDetail> entities = getAllEntityDetails(userId, serverName, typeDefName); Optional<OMRSRepositoryHelper> omrsRepositoryHelper = getOMRSRepositoryHelper(serverName); response.addEntityDetails(entities.stream() .map(entity -> entityDetailConverter.apply(entity, omrsRepositoryHelper.get()) ) .collect(Collectors.toList())); }catch (OMRSExceptionWrapper ew){ prepare(response, ew); } return response; } /** * Prepares the response with information from caught exception * * @param response * @param exception */ private void prepare(GlossaryViewEntityDetailResponse response, Exception exception) { response.setExceptionClassName(exception.getClass().getName()); response.setExceptionErrorMessage(exception.getMessage()); response.setRelatedHTTPCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); } }
hrakaroo/soda-water-ray-tracer
basics/point.cpp
#include <SW/point.h> #include <math.h> SWpoint::SWpoint() { _x = _y = _z = 0.0f; } SWpoint::SWpoint(float x, float y, float z) { _x = x; _y = y; _z = z; } ostream & operator<<(ostream & os, const SWpoint & point) { return os << "SWpoint: (" << point._x << ", " << point._y << ", " << point._z << ")"; } float operator-(const SWpoint & point1, const SWpoint & point2) { float x = point2._x - point1._x; float y = point2._y - point1._y; float z = point2._z - point1._z; return sqrtf( x*x + y*y + z*z ); } SWpoint operator+(const SWpoint & point, const SWvector & vector) { return SWpoint( point._x + vector._x, point._y + vector._y, point._z + vector._z ); } SWpoint operator-(const SWpoint & point, const SWvector & vector) { return SWpoint( point._x - vector._x, point._y - vector._y, point._z - vector._z ); }
07jeancms/HelloWorld
node_modules/jovo-core/dist/src/plugins/BaseCmsPlugin.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Extensible_1 = require("../core/Extensible"); class BaseCmsPlugin extends Extensible_1.Extensible { /** * Implemented install method * @param {BaseApp} app */ install(app) { app.middleware('after.platform.init').use(this.copyCmsDataToContext.bind(this)); } /** * Copies cms data from the app object to the jovo object. * @param {HandleRequest} handleRequest * @returns {Promise<void>} */ async copyCmsDataToContext(handleRequest) { if (handleRequest.jovo) { handleRequest.jovo.$cms.$jovo = handleRequest.jovo; Object.assign(handleRequest.jovo.$cms, handleRequest.app.$cms); } } } exports.BaseCmsPlugin = BaseCmsPlugin; //# sourceMappingURL=BaseCmsPlugin.js.map
UbuntuEvangelist/OG-Platform
projects/OG-Engine/src/main/java/com/opengamma/engine/marketdata/live/LiveDataFactory.java
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.marketdata.live; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.opengamma.engine.marketdata.availability.MarketDataAvailabilityFilter; import com.opengamma.id.ExternalScheme; import com.opengamma.livedata.LiveDataClient; import com.opengamma.livedata.UserPrincipal; import com.opengamma.util.ArgumentChecker; /** * Factory for building {@link LiveMarketDataProvider} instances. */ public class LiveDataFactory { /** Logger */ private static final Logger s_logger = LoggerFactory.getLogger(LiveDataFactory.class); /** Underlying source of the live data. */ private final LiveDataClient _liveDataClient; /** For checking availability of live data. */ private final MarketDataAvailabilityFilter _availabilityFilter; /** * All providers created by this factory. They are accessed via weak references so they will be GCd when they're * no longer being used by the engine. This will grow indefinitely unless {@link #resubscribe} is called. If that * turns out to be a problem then a periodic task to clean out empty references will be needed. */ private final List<WeakReference<InMemoryLKVLiveMarketDataProvider>> _providers = Lists.newArrayList(); /** Lock for accessing the list of providers. */ private final Object _providerListLock = new Object(); /** * Creates a new factory. * * @param liveDataClient the live data client to use to source data values * @param availabilityFilter the filter describing which values to source from this live data client */ public LiveDataFactory(final LiveDataClient liveDataClient, final MarketDataAvailabilityFilter availabilityFilter) { ArgumentChecker.notNull(liveDataClient, "liveDataClient"); ArgumentChecker.notNull(availabilityFilter, "availabilityFilter"); _liveDataClient = liveDataClient; _availabilityFilter = availabilityFilter; } /* package */ LiveMarketDataProvider create(final UserPrincipal user) { InMemoryLKVLiveMarketDataProvider provider = new InMemoryLKVLiveMarketDataProvider(_liveDataClient, _availabilityFilter, user); synchronized (_providerListLock) { _providers.add(new WeakReference<>(provider)); } return provider; } /** * If a data provider becomes available this method will be invoked with the schemes handled by the provider. * This gives market data providers the opportunity to reattempt previously failed subscriptions. * @param schemes The schemes for which market data subscriptions should be reattempted. */ /* package */ void resubscribe(Set<ExternalScheme> schemes) { synchronized (_providerListLock) { s_logger.info("Telling providers to resubscribe to data for schemes: {}", schemes); for (Iterator<WeakReference<InMemoryLKVLiveMarketDataProvider>> it = _providers.iterator(); it.hasNext(); ) { WeakReference<InMemoryLKVLiveMarketDataProvider> ref = it.next(); InMemoryLKVLiveMarketDataProvider provider = ref.get(); if (provider != null) { provider.resubscribe(schemes); } else { it.remove(); } } } } }
YuriyLisovskiy/xalwart
src/controllers/static.h
/** * controllers/static.h * * Copyright (c) 2019-2021 <NAME> * * Controller for serving static files. These are only to be used * during development, and SHOULD NOT be used in a production setting. */ #pragma once // Module definitions. #include "./_def_.h" // Framework libraries. #include "./controller.h" __CONTROLLERS_BEGIN__ // TESTME: was_modified_since // Checks if something was modified since the user last downloaded it. extern bool was_modified_since(const std::string& header, size_t time, size_t size); // TESTME: StaticController // TODO: docs for 'StaticController' // Serve static files below a given point in the directory structure. class StaticController final : public Controller<const std::string&> { public: inline explicit StaticController( std::string static_root, const conf::Settings* settings, const ILogger* logger ) : Controller({"get"}, logger), _static_root(std::move(static_root)) { this->settings = require_non_null(settings, "'settings' is nullptr", _ERROR_DETAILS_); } [[nodiscard]] std::unique_ptr<http::IResponse> get(http::IRequest* request, const std::string& p) const final; private: const conf::Settings* settings = nullptr; std::string _static_root; }; __CONTROLLERS_END__
mchristofersen/effective-octo-happiness
diagram-js/test/spec/i18n/I18NSpec.js
'use strict'; require('../../TestHelper'); /* global bootstrapDiagram, inject */ var paletteModule = require('../../../lib/features/palette'), i18nModule = require('../../../lib/i18n'); var spy = sinon.spy; describe('i18n', function() { describe('events', function() { beforeEach(bootstrapDiagram({ modules: [ i18nModule ] })); it('should emit i18n.changed event', inject(function(i18n, eventBus) { // given var listener = spy(function() {}); eventBus.on('i18n.changed', listener); // when i18n.changed(); // then expect(listener).to.have.been.called; })); }); describe('integration', function() { beforeEach(bootstrapDiagram({ modules: [ i18nModule, paletteModule ] })); it('should update palette', inject(function(palette, i18n) { // given var paletteUpdate = spy(palette, '_update'); palette._init(); // when i18n.changed(); // then expect(paletteUpdate).to.have.been.called; })); }); });
ivanvotti/svg-jar-demo
app/asset-selector/service.js
import Service from '@ember/service'; import { set } from '@ember/object'; export default Service.extend({ currentAsset: null, setCurrentAsset(asset) { set(this, 'currentAsset', asset); }, isCurrent(asset) { return asset === this.currentAsset; } });
elvinvalentino/yoapp
client/src/redux/reducers/chatReducer.js
import { SET_CHAT_ROOM, SET_SELECTED_USER, SET_MESSAGES, SET_NEW_MESSAGE, USER_LOGOUT } from '../constants'; const initialState = { chatRooms: [], selectedUser: null } const chatReducer = (state = initialState, action) => { const chatRooms = [...state.chatRooms]; let index; switch (action.type) { case SET_CHAT_ROOM: return { ...state, chatRooms: action.payload } case SET_SELECTED_USER: return { ...state, selectedUser: action.payload } case SET_MESSAGES: index = state.chatRooms.findIndex(room => room.from.id === action.payload.from.id); if (index === -1) { chatRooms.push(action.payload) } else { chatRooms[index] = { ...chatRooms[index], messages: action.payload.messages }; } return { ...state, chatRooms } case SET_NEW_MESSAGE: index = state.chatRooms.findIndex(room => room.from.id === action.payload.from.id); if (index !== -1) { if (chatRooms[index].hasOwnProperty('messages')) { chatRooms[index] = { ...chatRooms[index], lastMessage: action.payload.lastMessage, messages: [ ...chatRooms[index].messages, action.payload.lastMessage, ] }; } else { chatRooms[index] = { ...chatRooms[index], lastMessage: action.payload.lastMessage, }; } } else { return { ...state, chatRooms: [action.payload, ...chatRooms] } } return { ...state, chatRooms: [ chatRooms[index], ...chatRooms.filter(room => room.from.id !== action.payload.from.id) ] } case USER_LOGOUT: return { ...state, chatRooms: [], selectedUser: null } default: return state; } } export default chatReducer;
0x0015/CP2DG
Util/OneHeader/main.cpp
#include <iostream> #include <vector> #include <memory> #include <algorithm> #include <filesystem> #include "ArguementHandler/ArgHandle.hpp" #include "SimpleCppTextFileHandler/file.hpp" #include "main.hpp" //https://thispointer.com/find-all-occurrences-of-a-sub-string-in-a-string-c-both-case-sensitive-insensitive/ void findAllOccurances(std::vector<size_t> & vec, std::string& data, std::string toSearch) { // Get the first occurrence size_t pos = data.find(toSearch); // Repeat till end is reached while( pos != std::string::npos) { // Add position to the vector vec.push_back(pos); // Get the next occurrence from the current position pos =data.find(toSearch, pos + toSearch.size()); } } std::pair<std::string, int> findNextChar(std::string& data, size_t position){ for(int i=position;i<data.length();i++){ std::string let = data.substr(i, 1); if(let != " " && let != "\n" && let != "\t"){ return(std::pair<std::string, int>(let, i)); } } return(std::pair<std::string, int>("", -1)); } int findNextOccurenceChar(std::string& data, size_t position, std::string what){ for(int i=position;i<data.length();i++){ std::string let = data.substr(i, 1); if(let == what){ return(i); } } return(-1); } int main(int argc, char** argv){ ArguementHandler Args(argc, argv); std::string outputFile = "OneHeader_out.hpp"; std::vector<std::string> inputFiles; if(Args.hasArg("-o")){ outputFile = Args.findArgs("-o")[0].value; } if(Args.hasArg("")){ auto inputs = Args.findArgs(""); for(int i=0;i<inputs.size();i++){ inputFiles.push_back(inputs[i].value); } } std::cout<<"outputFile: "<<outputFile<<std::endl; std::cout<<"inputFiles: "<<std::endl; for(int i=0;i<inputFiles.size();i++){ std::cout<<inputFiles[i]<<std::endl; } std::vector<std::filesystem::path> doneFiles;//TODO make into paths so json.hpp and ../json.hpp will be treated as the same thing because it is the same thing called from different locations. std::vector<std::string> systemIncludes; std::string outString; std::filesystem::path basePath = std::filesystem::current_path(); for(int i=0;i<inputFiles.size();i++){ parse(&doneFiles, &systemIncludes, &outString, inputFiles[i], basePath); } std::cout<<"Done files: "<<std::endl; for(int i=0;i<doneFiles.size();i++){ std::cout<<doneFiles[i]<<std::endl; } std::cout<<"Found system includes: "<<std::endl; for(int i=0;i<systemIncludes.size();i++){ std::cout<<systemIncludes[i]<<std::endl; } } void parse(std::vector<std::filesystem::path>* doneFiles, std::vector<std::string>* systemIncludes, std::string* outString, std::filesystem::path inputFilename, std::filesystem::path currentPath){ doneFiles->push_back(inputFilename); //std::string pathChange = currentPath.lexically_normal().string(); //if(pathChange.substr(pathChange.length()-2, 1) != "/"){ // pathChange.append("/"); //} std::string fileContents = readFile(inputFilename.string()); if(fileContents == ""){ std::cout<<"Unable to find file '"<<inputFilename<<"'"<<std::endl; return; } std::vector<size_t> includeIndexes; findAllOccurances(includeIndexes, fileContents, "#include "); for(int i=0;i<includeIndexes.size();i++){ includeIndexes[i] += 9;//length of the include statement } int maxIncludeLength = 35; for(int i=0;i<includeIndexes.size();i++){ auto nextChar = findNextChar(fileContents, includeIndexes[i]); std::string let = nextChar.first; int let_pos = nextChar.second; //std::cout<<"nextchar "<<let<<std::endl; if(let == "\""){ int nextIndex = findNextOccurenceChar(fileContents, let_pos+1, "\""); std::string includeContents = fileContents.substr(let_pos+1, nextIndex-(let_pos+1)); if(includeContents.length() > maxIncludeLength){ continue; } //std::cout<<"Found local include: "<<includeContents<<std::endl; std::filesystem::path itemPath = (currentPath/std::filesystem::path(includeContents)).lexically_normal(); std::filesystem::path newPath = itemPath.parent_path(); if(std::find(doneFiles->begin(), doneFiles->end(), itemPath) != doneFiles->end()) { std::cout<<"Found repeat include of '"<<itemPath.string()<<"'"<<std::endl; } else { parse(doneFiles, systemIncludes, outString, itemPath, newPath);//yay recursion. what could go wrong? } }else if(let == "<"){ int nextIndex = findNextOccurenceChar(fileContents, let_pos+1, ">"); std::string includeContents = fileContents.substr(let_pos+1, nextIndex-(let_pos+1)); if(includeContents.length() > maxIncludeLength){ continue; } //std::cout<<"Found system include: "<<includeContents<<std::endl; if(std::find(systemIncludes->begin(), systemIncludes->end(), includeContents) != systemIncludes->end()) { //done't announce it to the whole world. this one is just gonna happen :/ } else { systemIncludes->push_back(includeContents); } } } }
ThatCmd/Utils
src/ttt/utils/xml/document/XMLElement.java
<reponame>ThatCmd/Utils /* * Copyright 2021 TTT. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ttt.utils.xml.document; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import ttt.utils.xml.engine.interfaces.IXMLComment; import ttt.utils.xml.engine.interfaces.IXMLElement; import ttt.utils.xml.engine.interfaces.IXMLTag; /** * Elemento base di un file XML. Può contenere zero o molteplici tags * ({@link IXMLTag}) e può avere anche altri sotto-elementi * ({@link IXMLElement}).<br> * Fornisce tutti i metodi in modo che una classe possa estendre * {@link XMLElement} definendo solo metodi funzionali per la gestione dei tag o * comportamenti specifici. * * @author TTT */ public class XMLElement implements IXMLElement { private final String name; private String value; private final HashMap<String, IXMLTag> tags = new HashMap<>(); private final ArrayList<IXMLElement> sub_elements = new ArrayList<>(); private final ArrayList<IXMLComment> comments = new ArrayList<>(); /** * Crea un nuovo elemento generico con tutti i metodi base già implementati. * * @param name Il nome dell'elemento */ public XMLElement(String name) { this.name = name; } @Override public boolean hasSubElements() { return sub_elements.size() > 0; } @Override public void addSubElement(IXMLElement element) { sub_elements.add(element); } @Override public void removeSubElement(IXMLElement element) { sub_elements.remove(element); } @Override public boolean hasTag(String name) { return tags.containsKey(name); } @Override public IXMLTag getTag(String name) { return tags.get(name); } @Override public String getName() { return name; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public boolean hasElement(IXMLElement element) { return sub_elements.contains(element); } @Override public void addTag(IXMLTag tag) { tags.put(tag.getName(), tag); } @Override public void removeTag(IXMLTag tag) { tags.remove(tag.getName(), tag); } @Override public List<IXMLTag> getTags() { ArrayList<IXMLTag> tgs = new ArrayList<>(); tgs.addAll(tags.values()); return Collections.unmodifiableList(tgs); } @Override public List<IXMLElement> getElements() { return Collections.unmodifiableList(sub_elements); } @Override public IXMLElement getFirstElement(String name) { return sub_elements.stream().filter((t) -> { return t.getName().equals(name); }).findFirst().orElse(null); } private boolean closed = false; @Override public boolean isClosed() { return closed; } @Override public void close() { closed = true; } @Override public IXMLElement getLast() { if (!closed) { if (hasSubElements()) { IXMLElement last = sub_elements.get(sub_elements.size() - 1).getLast(); if (last != null) { return last; } } return this; } return null; } @Override public List<IXMLComment> getComments() { return Collections.unmodifiableList(comments); } @Override public void addComment(IXMLComment comment) { if (comment != null && comment.getValue() != null && !"".equals(comment.getValue().trim())) { comments.add(comment); } } }
bubble501/gcplot
com.gcplot.api/src/main/java/com/gcplot/model/stats/GenerationStats.java
package com.gcplot.model.stats; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * 2/24/17 */ public interface GenerationStats { long totalPauseTimeMu(); long totalPauseCount(); long eventsCount(); long reclaimedBytes(); MinMaxAvg pauses(); DMinMaxAvg intervalBetweenEvents(); }
jpluscplusm/paas-cf
platform-tests/src/platform/vendor/github.com/vito/go-sse/sse/event_test.go
<reponame>jpluscplusm/paas-cf package sse_test import ( "time" . "github.com/vito/go-sse/sse" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" ) var _ = Describe("Event", func() { Describe("Encode", func() { It("encodes to a dispatchable event", func() { Ω(Event{ ID: "some-id", Name: "some-name", Data: []byte("some-data"), }.Encode()).Should(Equal("id: some-id\nevent: some-name\ndata: some-data\n\n")) }) It("splits lines across multiple data segments", func() { Ω(Event{ ID: "some-id", Name: "some-name", Data: []byte("some-data\nsome-more-data\n"), }.Encode()).Should(Equal("id: some-id\nevent: some-name\ndata: some-data\ndata: some-more-data\ndata\n\n")) }) It("includes retry if present", func() { Ω(Event{ ID: "some-id", Name: "some-name", Data: []byte("some-data"), Retry: 123 * time.Millisecond, }.Encode()).Should(Equal("id: some-id\nevent: some-name\nretry: 123\ndata: some-data\n\n")) }) }) Describe("Write", func() { var destination *gbytes.Buffer BeforeEach(func() { destination = gbytes.NewBuffer() }) It("writes the encoded event to the destination", func() { event := Event{ ID: "some-id", Name: "some-name", Data: []byte("some-data\nsome-more-data\n"), } err := event.Write(destination) Ω(err).ShouldNot(HaveOccurred()) Ω(destination.Contents()).Should(Equal([]byte(event.Encode()))) }) }) })
iris-dni/iris-backend
src/iris/service/content/file/__init__.py
<reponame>iris-dni/iris-backend from .document import File # noqa def includeme(config): from iris.service.rest import auth config.add_route('file_public_api', 'files', static=True) config.add_route('file_admin_api', 'admin/files', static=True, factory=auth.AdminServiceAuthFactory)
BuildforceDigital/olingo-odata4
lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/primitivetype/EdmString.java
/* * 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 org.apache.olingo.commons.core.edm.primitivetype; import java.util.regex.Pattern; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; /** * Implementation of the EDM primitive type String. */ public final class EdmString extends SingletonPrimitiveType { private static final Pattern PATTERN_ASCII = Pattern.compile("\\p{ASCII}*"); private static final EdmString INSTANCE = new EdmString(); { uriPrefix = "'"; uriSuffix = "'"; } public static EdmString getInstance() { return INSTANCE; } @Override public Class<?> getDefaultType() { return String.class; } @Override protected <T> T internalValueOfString(String value, Boolean isNullable, Integer maxLength, Integer precision, Integer scale, Boolean isUnicode, Class<T> returnType) throws EdmPrimitiveTypeException { if (isUnicode != null && !isUnicode && !PATTERN_ASCII.matcher(value).matches() || maxLength != null && maxLength < value.length()) { throw new EdmPrimitiveTypeException("The literal '" + value + "' does not match the facets' constraints."); } if (returnType.isAssignableFrom(String.class)) { return returnType.cast(value); } else { throw new EdmPrimitiveTypeException("The value type " + returnType + " is not supported."); } } @Override protected <T> String internalValueToString(T value, Boolean isNullable, Integer maxLength, Integer precision, Integer scale, Boolean isUnicode) throws EdmPrimitiveTypeException { String result = value instanceof String ? (String) value : String.valueOf(value); if (isUnicode != null && !isUnicode && !PATTERN_ASCII.matcher(result).matches() || maxLength != null && maxLength < result.length()) { throw new EdmPrimitiveTypeException("The value '" + value + "' does not match the facets' constraints."); } return result; } @Override public String toUriLiteral(String literal) { if (literal == null) { return null; } int length = literal.length(); StringBuilder uriLiteral = new StringBuilder(length + 2); uriLiteral.append(uriPrefix); for (int i = 0; i < length; i++) { char c = literal.charAt(i); if (c == '\'') { uriLiteral.append(c); } uriLiteral.append(c); } uriLiteral.append(uriSuffix); return uriLiteral.toString(); } @Override public String fromUriLiteral(String literal) throws EdmPrimitiveTypeException { return literal == null ? null : super.fromUriLiteral(literal).replace("''", "'"); } }
jiangminggithub/Android-NewsApp
app/src/main/java/com/jm/news/util/CommonUtils.java
package com.jm.news.util; import android.Manifest; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.Rect; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.TouchDelegate; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.PopupMenu; import android.widget.Toast; import com.jm.news.R; import com.jm.news.activity.MainActivity; import com.jm.news.common.Common; import java.lang.reflect.Field; import java.lang.reflect.Method; import cn.pedant.SweetAlert.SweetAlertDialog; public class CommonUtils { // static field private static final String TAG = "CommonUtils"; public static final int RESTART_TYPE_ALL_ACTIVITY = 0; public static final int RESTART_TYPE_APP = 1; public static final int APP_VERSION_FAILED_GET = -1; public static final int PERMISSION_REQUEST_CODE = 1; private static final int SHARE_CHOOSE_COPY_LINK = 0; private static final String REFLEX_DECLARED_FIELD = "mPopup"; private static final String REFLEX_DECLARED_METHOD = "setForceShowIcon"; private static CommonUtils mInstance = null; // function field private Context mContext = null; private SweetAlertDialog mNetInvisibleDialog; private CommonUtils() { } public static final synchronized CommonUtils getInstance() { if (null == mInstance) { mInstance = new CommonUtils(); } return mInstance; } public void initialize(@NonNull Context context) { this.mContext = context; } /************************************** public method *************************************/ /** * 通过text显示Toast * * @param text 显示的文本 */ public void showToastView(@NonNull String text) { if (null != mContext) { Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show(); } } /** * 通过ResourceID显示Toast * * @param resID 显示的ResourceID */ public void showToastView(int resID) { if (null != mContext) { Toast.makeText(mContext, resID, Toast.LENGTH_SHORT).show(); } } /** * 显示自定义显示时间和文本的Toast * * @param text 显示的字符 * @param time 显示的时间 */ public void showToastView(String text, int time) { if (null != mContext) { Toast.makeText(mContext, text, time).show(); } } /** * 重启App,两种方式,重启APP或者所有Activity * * @param type 重启操作类型 RESTART_TYPE_ALL_ACTIVITY,RESTART_TYPE_APP */ public void restartApp(int type) { if (null != mContext) { Intent intent = null; if (type == RESTART_TYPE_ALL_ACTIVITY) { intent = new Intent(mContext, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); } else if (type == RESTART_TYPE_APP) { intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); } else { return; } mContext.startActivity(intent); System.exit(0); } } /* * 获取当前程序的版本号名 */ public String getVersionName() { if (null != mContext) { PackageManager packageManager = mContext.getPackageManager(); PackageInfo packInfo = null; try { packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); LogUtils.e(TAG, "getVersionName: --------- failed -----------"); } LogUtils.d("TAG", "getVersionName = " + packInfo.versionName); return packInfo.versionName; } return null; } /* * 获取当前程序的版本号 */ public long getVersionCode() { if (null != mContext) { PackageManager packageManager = mContext.getPackageManager(); PackageInfo packInfo = null; try { packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { LogUtils.e("TAG", "getVersionCode versionCode = " + packInfo.getLongVersionCode()); return packInfo.getLongVersionCode(); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); LogUtils.e(TAG, "getVersionCode: --------- failed -----------"); } LogUtils.d(TAG, "getVersionCode versionCode = " + packInfo.versionCode); return packInfo.versionCode; } return APP_VERSION_FAILED_GET; } /** * 检查网络是否可用 * * @return Boolean */ public boolean isNetworkAvailable() { if (null != mContext) { ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 当前网络是连接的 if (info.getState() == NetworkInfo.State.CONNECTED) { // 当前所连接的网络可用 return true; } } } } return false; } /** * 显示网络断开的提示框 * * @param activity 目标的Activity对象 */ public void showNetInvisibleDialog(Activity activity) { if (null == activity) { return; } if (null == mNetInvisibleDialog) { Common common = Common.getInstance(); mNetInvisibleDialog = new SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE); mNetInvisibleDialog.setTitleText(activity.getString(R.string.dialog_waring_tips)) .setContentText(activity.getString(R.string.dialog_net_invisible_content)) .setConfirmText(activity.getString(R.string.dialog_confirm)) .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { sweetAlertDialog.dismiss(); mNetInvisibleDialog = null; } }); mNetInvisibleDialog.setCancelable(false); mNetInvisibleDialog.show(); LogUtils.d(TAG, "showNetInvisibleDialog: show"); } else if (!mNetInvisibleDialog.isShowing()) { mNetInvisibleDialog.show(); } else { // nothing to do } } /** * 关闭网络断开的提示框 */ public void dismissNetInvisibleDialog() { if (null != mNetInvisibleDialog && mNetInvisibleDialog.isShowing()) { mNetInvisibleDialog.dismiss(); mNetInvisibleDialog = null; LogUtils.d(TAG, "dismissNetInvisibleDialog: dismiss"); } } /************************************** static method *************************************/ /** * 增加View触摸区域大小,最小区域为View的默认大小 * * @param view target 目标View * @param top 增加上部区域大小 * @param bottom 增加下部区域大小 * @param left 增加左部区域大小 * @param right 增加右部区域大小 */ public static void expandViewTouchDelegate(@NonNull final View view, final int top, final int bottom, final int left, final int right) { if (null != view) { ((View) view.getParent()).post(new Runnable() { @Override public void run() { Rect bounds = new Rect(); view.setEnabled(true); view.getHitRect(bounds); bounds.top -= top; bounds.bottom += bottom; bounds.left -= left; bounds.right += right; TouchDelegate touchDelegate = new TouchDelegate(bounds, view); if (View.class.isInstance(view.getParent())) { ((View) view.getParent()).setTouchDelegate(touchDelegate); } } }); } } /** * 恢复view触摸区域大小 * * @param view 目标View */ public static void restoreViewTouchDelegate(@NonNull final View view) { if (null != view) { ((View) view.getParent()).post(new Runnable() { @Override public void run() { Rect bounds = new Rect(); bounds.setEmpty(); TouchDelegate touchDelegate = new TouchDelegate(bounds, view); if (View.class.isInstance(view.getParent())) { ((View) view.getParent()).setTouchDelegate(touchDelegate); } } }); } } /** * 为指定View创建popupMenu * * @param context 目标的Context * @param view 需要显示popupMenu的对象 * @param resMenuID 需要显示Menu的ResourceID * @param hasIcon 标记可以带icon的选项,注意在不同系统中显示不可控,谨慎使用 * @return PopupMenu PopupMenu 对象 */ public static PopupMenu getPopupMenu(@NonNull Context context, @NonNull View view, int resMenuID, boolean hasIcon) { if (null == context || null == view) { return null; } PopupMenu popupMenu = new PopupMenu(context, view); popupMenu.inflate(resMenuID); if (hasIcon) { // used reflex show menu icon try { Field field = popupMenu.getClass().getDeclaredField(REFLEX_DECLARED_FIELD); field.setAccessible(true); Object helper = field.get(popupMenu); Method mSetForceShowIcon = helper.getClass().getDeclaredMethod(REFLEX_DECLARED_METHOD, boolean.class); mSetForceShowIcon.invoke(helper, true); field.setAccessible(false); } catch (Exception e) { e.printStackTrace(); LogUtils.e(TAG, "getPopupMenuIcon: class reflex failed "); } } return popupMenu; } /** * 解决部分虚拟键手机Menu键显示 * * @param activity 目标activity */ public static void setNeedsMenuKey(@NonNull Activity activity) { if (null == activity || Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return; } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { try { int flags = WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null); activity.getWindow().addFlags(flags); } catch (Exception e) { e.printStackTrace(); } } else { try { Method setNeedsMenuKey = Window.class.getDeclaredMethod("setNeedsMenuKey", int.class); setNeedsMenuKey.setAccessible(true); int value = WindowManager.LayoutParams.class.getField("NEEDS_MENU_SET_TRUE").getInt(null); setNeedsMenuKey.invoke(activity.getWindow(), value); } catch (Exception e) { e.printStackTrace(); } } } /** * Android P 异型屏全屏页面显示 * * @param window Activity的window对象 */ public static void setFullScreenWindowLayout(Window window) { if (null != window && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); //设置页面全屏显示 WindowManager.LayoutParams lp = window.getAttributes(); lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; //设置页面延伸到刘海区显示 window.setAttributes(lp); } } /** * 显示暂时未实现功能提示框 * * @param activity context对象 */ public static void showFunctionNotOpenDialog(Activity activity) { if (null != activity) { Common common = Common.getInstance(); new SweetAlertDialog(activity, SweetAlertDialog.WARNING_TYPE) .setTitleText(activity.getString(R.string.dialog_waring_tips)) .setContentText(activity.getString(R.string.dialog_waring_content)) .setConfirmText(activity.getString(R.string.dialog_confirm)) .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.dismiss(); } }) .show(); } } /** * 检查应用权限 * * @param activity activity对象 * @return 是否有权限true:具备,false:没有权限 */ public static boolean checkPermissions(Activity activity) { if (null != activity) { int writeStorageState = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); LogUtils.d(TAG, "checkPermissions: writeStorageState = " + writeStorageState); if (writeStorageState != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); return false; } else { return true; } } return false; } /** * 显示没有权限的提示框 * * @param activity activity对象 */ public static void showNoPermission(final Activity activity) { if (null != activity) { Common common = Common.getInstance(); new SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE) .setTitleText(activity.getString(R.string.dialog_permission_title)) .setContentText(activity.getString(R.string.dialog_permission_content)) .setCancelText(activity.getString(R.string.dialog_permission_cancel)) .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.dismiss(); activity.finish(); } }) .setConfirmText(activity.getString(R.string.dialog_permission_setting)) .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", activity.getPackageName(), null); intent.setData(uri); activity.startActivity(intent); sDialog.dismiss(); } }) .show(); } } /** * 打开分享选择框,分享的文本信息 * * @param activity 目标activity对象 * @param content 分享的文本信息 */ public static void shareDialog(final Activity activity, final String content) { LogUtils.d(TAG, "shareDialog: content = " + content); if (null != activity && !TextUtils.isEmpty(content)) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.share_choose); builder.setItems(Common.getInstance().getResourcesStringArray(R.array.share_choose), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LogUtils.d(TAG, "shareDialog onClick: which = " + which); // 选择复制分享链接 if (which == SHARE_CHOOSE_COPY_LINK) { ClipboardManager clipboardManager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setPrimaryClip(ClipData.newPlainText(null, content)); CommonUtils.getInstance().showToastView(R.string.toast_setting_share_success); } else { // 系统选择框,分享到支持的应用 Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, content); activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.share_title))); } } }); builder.setCancelable(true).create().show(); } else { CommonUtils.getInstance().showToastView(R.string.toast_setting_share_failed); } } }
PDCbc/health-data-standards
test/unit/util/vs_api_test.rb
require 'test_helper' require 'webmock' class EntryTest < MiniTest::Unit::TestCase include WebMock::API def test_api stub_request(:post,'https://localhost/token').with(:body =>{"password"=>"<PASSWORD>", "username"=>"myusername"}).to_return( :body=>"proxy_ticket") stub_request(:get,'https://localhost/vsservice').with(:query =>{:id=>"oid", :ticket=>"ticket"}).to_return( :body=>"<ValuesetResponse/>") stub_request(:post,'https://localhost/token/proxy_ticket').with(:body =>{"service"=>"http://umlsks.nlm.nih.gov"}).to_return( :body=>"ticket") api = HealthDataStandards::Util::VSApi.new("https://localhost/token", "https://localhost/vsservice", "myusername", "<PASSWORD>") assert_equal "proxy_ticket" , api.proxy_ticket assert_equal "ticket", api.get_ticket assert_equal "<ValuesetResponse/>", api.get_valueset("oid") api.get_valueset("oid") do |oid,vs| assert_equal "oid", oid assert_equal "<ValuesetResponse/>", vs end end end
kilroyrlc/kaflib
src/kaflib/applications/mtg/CardUtils.java
<filename>src/kaflib/applications/mtg/CardUtils.java package kaflib.applications.mtg; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.filechooser.FileNameExtensionFilter; import kaflib.types.Directory; import kaflib.types.Matrix; import kaflib.utils.FileUtils; import kaflib.utils.StringUtils; /** * Utilities for the mtg stuff. */ public class CardUtils { public static Set<Integer> getIDs(final File file) throws Exception { String text = FileUtils.readString(file, null); Set<Integer> ids = new HashSet<Integer>(); Pattern pattern = Pattern.compile("^(\\d+)\\D.*", Pattern.MULTILINE); String chunks[] = text.split("multiverseid\\="); for (int i = 1; i < chunks.length; i++) { String chunk = StringUtils.truncateIf(chunks[i], 16); Matcher matcher = pattern.matcher(chunk); if (matcher.matches()) { ids.add(Integer.valueOf(matcher.group(1))); } } return ids; } public static void importScrapeBlobs() throws Exception { Set<Integer> ids = new HashSet<Integer>(); File directory = null; JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION || chooser.getSelectedFiles() == null) { return; } for (File file : chooser.getSelectedFiles()) { ids.addAll(getIDs(file)); if (directory == null) { directory = file.getParentFile(); } } FileUtils.write(new File(directory, "ids.txt"), StringUtils.concatenate(ids, "\n")); } /** * Import an excel file with cards that are owned, including gui file * prompt. * @throws Exception */ public static void importHaveFile() throws Exception { CardDatabase db = new CardDatabase(); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JFileChooser chooser = new JFileChooser(db.getDeckDirectory()); chooser.setMultiSelectionEnabled(false); chooser.setFileFilter(new FileNameExtensionFilter("List files", "xlsx")); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION || chooser.getSelectedFile() == null) { return; } List<String> names = readNameList(chooser.getSelectedFile()); frame.setVisible(false); importHaveList(db, names, true); } /** * Read a list of card names. * @param excelFile * @return * @throws Exception */ public static List<String> readNameList(final File excelFile) throws Exception { Matrix<String> matrix = FileUtils.readXLSXSheet(excelFile, false); List<String> names = new ArrayList<String>(); for (int i = 0; i < matrix.getRowCount(); i++) { if (matrix.hasValue(i, 0)) { names.add(matrix.get(i, 0).trim()); } } return names; } /** * Import a list of cards that are owned. * @param db * @param names * @param print * @throws Exception */ public static void importHaveList(final CardDatabase db, final List<String> names, final boolean print) throws Exception { Set<String> missing = new HashSet<String>(); for (String name : names) { if (!db.checkName(name)) { missing.add(name); } } if (missing.size() > 0) { System.out.println("" + missing.size() + " cards missing, database unchanged:\n" + StringUtils.concatenate(missing, "\n")); return; } if (print) { System.out.println("Marking " + names.size() + " cards as have."); } for (String name : names) { boolean had = db.have(name); db.setHave(name, true); if (print) { String line = StringUtils.resize(name + ":", 32); if (had) { line += "yes"; } else { line += "no "; } line += " -> "; if (db.have(name)) { line += "yes"; } else { line += "no "; } System.out.println(line); } } db.write(); } /** * Write an html file with all the cards in the list. * @param db * @param directory * @param name * @param names * @throws Exception */ public static void generateHTML(final CardDatabase db, final File directory, final String name, final List<String> names) throws Exception { CardList list = CardList.getList(db, names); StringBuffer buffer = new StringBuffer(); buffer.append("<html>\n<body>\n<table>\n <tr>\n"); int column = 0; for (Card card : list) { File image = db.getImage(card.getName()); FileUtils.copy(new File(directory, image.getName()), image); buffer.append(" <td><img src=\"" + image.getName() + "\" alt=\"" + card.getName() + "\" border=\"0\" /></td>\n"); column++; if (column == 4) { column = 0; buffer.append(" </tr>\n <tr>\n"); } } buffer.append(" </tr>\n</table>\n</body>\n</html>\n"); FileUtils.write(new File(directory, name + ".html"), new String(buffer)); } public static void generateText(final CardDatabase db, final File directory, final String name, final List<String> names) throws Exception { CardList list = CardList.getList(db, names); StringBuffer buffer = new StringBuffer(); for (Card card : list) { buffer.append(card.getName() + "; "); } FileUtils.write(new File(directory, name + ".txt"), new String(buffer)); } public static Map<String, CardInstance> getMergedCards(final CardDatabase db) throws Exception { Map<String, CardInstance> cards = new HashMap<String, CardInstance>(); for (CardInstance instance : db) { if (instance.isInvalidOrForeign()) { continue; } if (!cards.containsKey(instance.getName())) { cards.put(instance.getName(), instance); } else { cards.put(instance.getName(), CardInstance.merge(cards.get(instance.getName()), instance)); } } return cards; } /** * Write an html file with all the cards in the list. * @param db * @param directory * @param name * @param names * @throws Exception */ public static void generateRated(final CardDatabase db, final Directory directory, final String name, final int count, final boolean reverse) throws Exception { // Create a map with all card instances merged. Map<String, CardInstance> cards = getMergedCards(db); List<CardInstance> artifacts = new ArrayList<CardInstance>(); List<CardInstance> spells = new ArrayList<CardInstance>(); List<CardInstance> land = new ArrayList<CardInstance>(); List<CardInstance> enchantment = new ArrayList<CardInstance>(); List<CardInstance> planeswalker = new ArrayList<CardInstance>(); List<CardInstance> creature = new ArrayList<CardInstance>(); for (CardInstance instance : cards.values()) { if (!instance.hasRating()) { continue; } if (Type.getTypes(instance.getTypes()).contains(Type.ARTIFACT)) { artifacts.add(instance); Collections.sort(artifacts, CardInstance.getRatingComparator()); if (reverse) { Collections.reverse(artifacts); } artifacts = artifacts.subList(0, Math.min(count, artifacts.size())); } if (Type.getTypes(instance.getTypes()).contains(Type.INSTANT) || Type.getTypes(instance.getTypes()).contains(Type.SORCERY)) { spells.add(instance); Collections.sort(spells, CardInstance.getRatingComparator()); if (reverse) { Collections.reverse(spells); } spells = spells.subList(0, Math.min(count, spells.size())); } if (Type.getTypes(instance.getTypes()).contains(Type.LAND) && !Type.getTypes(instance.getTypes()).contains(Type.BASIC_LAND)) { land.add(instance); Collections.sort(land, CardInstance.getRatingComparator()); if (reverse) { Collections.reverse(land); } land = land.subList(0, Math.min(count, land.size())); } if (Type.getTypes(instance.getTypes()).contains(Type.ENCHANTMENT)) { enchantment.add(instance); Collections.sort(enchantment, CardInstance.getRatingComparator()); if (reverse) { Collections.reverse(enchantment); } enchantment = enchantment.subList(0, Math.min(count, enchantment.size())); } if (Type.getTypes(instance.getTypes()).contains(Type.PLANESWALKER)) { planeswalker.add(instance); Collections.sort(planeswalker, CardInstance.getRatingComparator()); if (reverse) { Collections.reverse(planeswalker); } planeswalker = planeswalker.subList(0, Math.min(count, planeswalker.size())); } if (Type.getTypes(instance.getTypes()).contains(Type.CREATURE)) { creature.add(instance); Collections.sort(creature, CardInstance.getRatingComparator()); if (reverse) { Collections.reverse(creature); } creature = creature.subList(0, Math.min(count, creature.size())); } } StringBuffer buffer = new StringBuffer(); buffer.append("<html>\n<body>\n"); buffer.append(getTable(db, "Lands", directory, land)); buffer.append(getTable(db, "Planeswalkers", directory, planeswalker)); buffer.append(getTable(db, "Creatures", directory, creature)); buffer.append(getTable(db, "Artifacts", directory, artifacts)); buffer.append(getTable(db, "Enchantments", directory, enchantment)); buffer.append(getTable(db, "Spells", directory, spells)); buffer.append("</body>\n</html>\n"); FileUtils.write(new File(directory, name + ".html"), new String(buffer)); } public static String getTable(final CardDatabase db, final String title, final Directory directory, final List<CardInstance> list) throws Exception { StringBuffer buffer = new StringBuffer(); buffer.append("<table>\n"); buffer.append(" <tr><th colspan=\"4\">" + title + "</th></tr>\n <tr>\n"); int column = 0; for (CardInstance card : list) { if (card.isInvalidOrForeign() || !card.hasRating()) { System.err.println("Snuck through:\n" + card.toString()); continue; } File image = db.getRandomImage(card.getName()); FileUtils.copy(new File(directory, image.getName()), image); buffer.append(" <td><img src=\"" + image.getName() + "\" alt=\"" + card.getName() + "\" border=\"0\" /><br>\n" + card.getRating() + " (" + card.getVotes() + ")</td>"); column++; if (column == 4) { column = 0; buffer.append(" </tr>\n <tr>\n"); } } buffer.append(" </tr>\n</table>\n\n"); return buffer.toString(); } /** * Generate an html file with a table of all have cards. * @param db * @param directory * @throws Exception */ public static void generateHaveHTML(final CardDatabase db, final File directory) throws Exception { List<String> names = new ArrayList<String>(); names.addAll(db.getHaves()); Collections.sort(names); StringBuffer buffer = new StringBuffer(); buffer.append("<html>\n<body>\n<table>\n"); String bgcolor = "bgcolor = \"#eeeeee\""; for (String name : names) { if (bgcolor.equals("bgcolor = \"#eeeeee\"")) { bgcolor = "bgcolor = \"#dddddd\""; } else { bgcolor = "bgcolor = \"#eeeeee\""; } buffer.append(" <tr " + bgcolor + "><td>"); Integer id = db.getIDs(name).iterator().next(); if (id != null) { buffer.append("<a href=\"http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=" + id + "\">"); } buffer.append(name); if (id != null) { buffer.append("</a>"); } buffer.append("</td></tr>"); } buffer.append(" </tr>\n</table>\n</body>\n</html>\n"); FileUtils.write(new File(directory, "havelist.html"), new String(buffer)); } public static void main(String args[]) { try { //CardDatabase db = new CardDatabase(); //generateHaveHTML(db, db.getDeckDirectory()); //generateRated(db, db.getTempDirectory(), "top", 32, false); //generateRated(db, db.getTempDirectory(), "bottom", 32, true); //importHaveFile(); importScrapeBlobs(); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } }
ali-haider-qbatch/qbatch
src/pages/work/bwd.js
import React from "react" import SEO from "../../components/seo" import Layout from "../../components/layout" import WorkDetail from "../../components/workDetail" import { Container } from "react-bootstrap" import BwdImg from "../../images/work/bwd.png" import WorkSlider from "../../components/workSlider" import BWDWeb1 from "../../images/BWDweb/BWDWeb1.png" import BWDWeb2 from "../../images/BWDweb/BWDWeb2.png" import BWDWeb3 from "../../images/BWDweb/BWDWeb3.png" import BWDWeb4 from "../../images/BWDweb/BWDWeb4.png" import BWDWeb5 from "../../images/BWDweb/BWDWeb5.png" import ContactForm from "../../components/contactForm" import ClientFeedback from "../../components/clientFeedback" const Bwd = () => { const firstList = [ "ReactJS", "React Native", "Redux", "MongoDB", "Node.js", "Docker", "AWS", ] const secondList = [ "Bradning", "User Research", "Wireframing", "UI Design ", "Interactive Prototyping", "User Testing", ] const products = [ { img: BWDWeb1, }, { img: BWDWeb2, }, { img: BWDWeb3, }, { img: BWDWeb4, }, { img: BWDWeb5, }, ] return ( <Layout> <SEO title="Bwd App" /> <WorkDetail heading="Blue Warehouse Discounts - Web" paragraph="Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, information on its origins, well as a random Lipsum generator." Image={BwdImg} paraHeading="The Problem" problem="Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, information on its origins, well as a random Lipsum generator." listHeading="Tech Stack" solHeading="The solution" solPara="Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, giving information on its origins, well as a random Lipsum generator. Reference site about Lorem Ipsum, information on its origins, well as a random Lipsum generator." firstList={firstList} secondList={secondList} /> <WorkSlider products={products} /> <ClientFeedback /> <div className="py-75 bg-mdnight"> <Container> <ContactForm /> </Container> </div> </Layout> ) } export default Bwd
benderjs/benderjs
lib/pagebuilders/manual.js
/** * Copyright (c) 2014-2015, CKSource - <NAME>. All rights reserved. * Licensed under the terms of the MIT License (see LICENSE.md). * * @file Page builder responsible for manual tests */ 'use strict'; var marked = require( 'marked' ), path = require( 'path' ); /** * @module pagebuilders/manual */ module.exports = { name: 'bender-pagebuilder-manual', /** * Include manual test script and template in a test page * @param {Object} data Test page data * @return {Object} */ build: function( data ) { var bender = this, pattern = /@bender\-([\w\-]+)\:([\w \-\.\/\\\:\?\+\$@~_,=#%';!]+)/gi, file; if ( !data.manual ) { return data; } file = data.snapshot ? path.join( '.bender/jobs/', data.jobId, '/tests/', data.script ) : data.script; // removes bender directives (@bender-*) from the script function stripDirectives( content ) { return content.replace( pattern, '' ); } var promise = bender.files.readString( path.join( __dirname, '../../static/manual.html' ) ) .then( function( template ) { file = bender.files.get( file ); return file.read() .then( function( content ) { return bender.utils.template( template.toString(), { SCRIPT: marked( stripDirectives( content.toString() ) ) } ); } ); } ); data.parts.push( promise ); return data; } };
serval-uni-lu/IBIR
src/main/java/edu/lu/uni/serval/ibir/output/ProgressPrinter.java
<reponame>serval-uni-lu/IBIR package edu.lu.uni.serval.ibir.output; import com.opencsv.CSVReaderHeaderAware; import com.opencsv.exceptions.CsvValidationException; import edu.lu.uni.serval.ibir.utils.FileUtils; import edu.lu.uni.serval.tbar.info.Patch; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; import static edu.lu.uni.serval.ibir.output.CsvConsts.*; import static edu.lu.uni.serval.ibir.utils.FileUtils.appendLineToFile; public class ProgressPrinter { private final List<PatchEntry> triedPatchCandidates; private final File file; public ProgressPrinter(String progressFilePath) { this.file = new File(progressFilePath); triedPatchCandidates = new ArrayList<>(); } public void init() throws IOException, CsvValidationException { // prepare results dir. if (!file.exists() || file.length() == 0) { FileUtils.createFile(file, PATCH_ENTRY_CSV_HEADER + "\n"); } else { loadPreviouslyGeneratedPatches(); } } List<PatchEntry> getTriedPatchCandidates(){ return triedPatchCandidates; } private void loadPreviouslyGeneratedPatches() throws IOException, CsvValidationException { CSVReaderHeaderAware reader = new CSVReaderHeaderAware(new FileReader(file)); Map<String, String> line = reader.readMap(); while (line != null) { PatchEntry entry = new PatchEntry(line); if (entry.duplicateId == null || entry.duplicateId.length() == 0 || "null".equals(entry.duplicateId)) triedPatchCandidates.add(entry); line = reader.readMap(); } } public PatchEntry addPatch(int[] lineNumbers, int fl_loc, int id, Patch patch, long elapsedTime) throws IOException { return addPatch(lineNumbers, String.valueOf(fl_loc), String.valueOf(id), patch, elapsedTime); } public PatchEntry addPatch(int[] lineNumbers, String fl_loc, String id, Patch patch, long elapsedTime) throws IOException { PatchEntry dupl = getDuplicate(patch); boolean isDupl = dupl != null; String lineStart = String.valueOf(lineNumbers[0]); String lineEnd = String.valueOf(lineNumbers[1]); PatchEntry patchEntry = isDupl ? new PatchEntry(fl_loc, id, patch, dupl, lineStart,lineEnd) : new PatchEntry(fl_loc, id, patch, lineStart,lineEnd); printPatch(patchEntry, elapsedTime); if (!isDupl) { triedPatchCandidates.add(patchEntry); return null; } else { return dupl; } } private void printPatch(PatchEntry patchEntry, long elapsedTime) throws IOException { appendLineToFile(file, patchEntry.toCsv() + "," + elapsedTime); } private PatchEntry getDuplicate(Patch patch) { for (PatchEntry triedPatchCandidate : triedPatchCandidates) { // oh yes that's against java best-practices! but don't change it !!! // To know more why, check the implementation of equals... check Tbar... if (triedPatchCandidate.equals(patch)) return triedPatchCandidate; } return null; } public List<Patch> removeTriedOnes(List<Patch> patchCandidates) { for (PatchEntry triedPatchCandidate : triedPatchCandidates) { patchCandidates.remove(triedPatchCandidate.patch); } return patchCandidates; } public int triedPatchesCount() { return triedPatchCandidates.size(); } }
awltux/scm-manager
scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryRootResourceTest.java
package sonia.scm.api.v2.resources; import com.github.sdorra.shiro.ShiroRule; import com.github.sdorra.shiro.SubjectAware; import com.google.common.io.Resources; import com.google.inject.util.Providers; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.jboss.resteasy.mock.MockHttpRequest; import org.jboss.resteasy.mock.MockHttpResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import sonia.scm.PageResult; import sonia.scm.repository.NamespaceAndName; import sonia.scm.repository.Repository; import sonia.scm.repository.RepositoryInitializer; import sonia.scm.repository.RepositoryManager; import sonia.scm.repository.api.RepositoryService; import sonia.scm.repository.api.RepositoryServiceFactory; import sonia.scm.user.User; import sonia.scm.web.RestDispatcher; import sonia.scm.web.VndMediaType; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.function.Predicate; import static java.util.Collections.singletonList; import static java.util.stream.Stream.of; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static javax.servlet.http.HttpServletResponse.SC_OK; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; @SubjectAware( username = "trillian", password = "<PASSWORD>", configuration = "classpath:sonia/scm/repository/shiro.ini" ) public class RepositoryRootResourceTest extends RepositoryTestBase { private static final String REALM = "AdminRealm"; private RestDispatcher dispatcher = new RestDispatcher(); @Rule public ShiroRule shiro = new ShiroRule(); @Mock private RepositoryManager repositoryManager; @Mock private RepositoryServiceFactory serviceFactory; @Mock private RepositoryService service; @Mock private ScmPathInfoStore scmPathInfoStore; @Mock private ScmPathInfo uriInfo; @Mock private RepositoryInitializer repositoryInitializer; @Captor private ArgumentCaptor<Predicate<Repository>> filterCaptor; private final URI baseUri = URI.create("/"); private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri); @InjectMocks private RepositoryToRepositoryDtoMapperImpl repositoryToDtoMapper; @InjectMocks private RepositoryDtoToRepositoryMapperImpl dtoToRepositoryMapper; @Before public void prepareEnvironment() { initMocks(this); super.repositoryToDtoMapper = repositoryToDtoMapper; super.dtoToRepositoryMapper = dtoToRepositoryMapper; super.manager = repositoryManager; RepositoryCollectionToDtoMapper repositoryCollectionToDtoMapper = new RepositoryCollectionToDtoMapper(repositoryToDtoMapper, resourceLinks); super.repositoryCollectionResource = Providers.of(new RepositoryCollectionResource(repositoryManager, repositoryCollectionToDtoMapper, dtoToRepositoryMapper, resourceLinks, repositoryInitializer)); dispatcher.addSingletonResource(getRepositoryRootResource()); when(serviceFactory.create(any(Repository.class))).thenReturn(service); when(scmPathInfoStore.get()).thenReturn(uriInfo); when(uriInfo.getApiRestUri()).thenReturn(URI.create("/x/y")); SimplePrincipalCollection trillian = new SimplePrincipalCollection("trillian", REALM); trillian.add(new User("trillian"), REALM); shiro.setSubject( new Subject.Builder() .principals(trillian) .authenticated(true) .buildSubject()); } @Test public void shouldFailForNotExistingRepository() throws URISyntaxException { when(repositoryManager.get(any(NamespaceAndName.class))).thenReturn(null); mockRepository("space", "repo"); MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/other"); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_NOT_FOUND, response.getStatus()); } @Test public void shouldFindExistingRepository() throws URISyntaxException, UnsupportedEncodingException { mockRepository("space", "repo"); MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo"); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_OK, response.getStatus()); assertTrue(response.getContentAsString().contains("\"name\":\"repo\"")); } @Test public void shouldGetAll() throws URISyntaxException, UnsupportedEncodingException { PageResult<Repository> singletonPageResult = createSingletonPageResult(mockRepository("space", "repo")); when(repositoryManager.getPage(any(), any(), eq(0), eq(10))).thenReturn(singletonPageResult); MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_OK, response.getStatus()); assertTrue(response.getContentAsString().contains("\"name\":\"repo\"")); } @Test public void shouldCreateFilterForSearch() throws URISyntaxException { PageResult<Repository> singletonPageResult = createSingletonPageResult(mockRepository("space", "repo")); when(repositoryManager.getPage(filterCaptor.capture(), any(), eq(0), eq(10))).thenReturn(singletonPageResult); MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "?q=Rep"); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_OK, response.getStatus()); assertTrue(filterCaptor.getValue().test(new Repository("x", "git", "all_repos", "x"))); assertTrue(filterCaptor.getValue().test(new Repository("x", "git", "x", "repository"))); assertFalse(filterCaptor.getValue().test(new Repository("rep", "rep", "x", "x"))); } @Test public void shouldHandleUpdateForNotExistingRepository() throws URISyntaxException, IOException { URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repository = Resources.toByteArray(url); when(repositoryManager.get(any(NamespaceAndName.class))).thenReturn(null); MockHttpRequest request = MockHttpRequest .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo") .contentType(VndMediaType.REPOSITORY) .content(repository); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_NOT_FOUND, response.getStatus()); } @Test public void shouldHandleUpdateForExistingRepository() throws Exception { mockRepository("space", "repo"); URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repository = Resources.toByteArray(url); MockHttpRequest request = MockHttpRequest .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo") .contentType(VndMediaType.REPOSITORY) .content(repository); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_NO_CONTENT, response.getStatus()); verify(repositoryManager).modify(anyObject()); } @Test public void shouldHandleUpdateForConcurrentlyChangedRepository() throws Exception { mockRepository("space", "repo", 1337); URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repository = Resources.toByteArray(url); MockHttpRequest request = MockHttpRequest .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo") .contentType(VndMediaType.REPOSITORY) .content(repository); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_CONFLICT, response.getStatus()); assertThat(response.getContentAsString()).contains("space/repo"); verify(repositoryManager, never()).modify(anyObject()); } @Test public void shouldHandleUpdateForExistingRepositoryForChangedNamespace() throws Exception { mockRepository("wrong", "repo"); URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repository = Resources.toByteArray(url); MockHttpRequest request = MockHttpRequest .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "wrong/repo") .contentType(VndMediaType.REPOSITORY) .content(repository); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_BAD_REQUEST, response.getStatus()); verify(repositoryManager, never()).modify(anyObject()); } @Test public void shouldHandleDeleteForExistingRepository() throws Exception { mockRepository("space", "repo"); MockHttpRequest request = MockHttpRequest.delete("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo"); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_NO_CONTENT, response.getStatus()); verify(repositoryManager).delete(anyObject()); } @Test public void shouldCreateNewRepositoryInCorrectNamespace() throws Exception { when(repositoryManager.create(any())).thenAnswer(invocation -> { Repository repository = (Repository) invocation.getArguments()[0]; repository.setNamespace("otherspace"); return repository; }); URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repositoryJson = Resources.toByteArray(url); MockHttpRequest request = MockHttpRequest .post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2) .contentType(VndMediaType.REPOSITORY) .content(repositoryJson); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(HttpServletResponse.SC_CREATED, response.getStatus()); assertEquals("/v2/repositories/otherspace/repo", response.getOutputHeaders().get("Location").get(0).toString()); verify(repositoryManager).create(any(Repository.class)); verify(repositoryInitializer, never()).initialize(any(Repository.class)); } @Test public void shouldCreateNewRepositoryAndInitialize() throws Exception { when(repositoryManager.create(any())).thenAnswer(invocation -> invocation.getArgument(0)); URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repositoryJson = Resources.toByteArray(url); MockHttpRequest request = MockHttpRequest .post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "?initialize=true") .contentType(VndMediaType.REPOSITORY) .content(repositoryJson); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(HttpServletResponse.SC_CREATED, response.getStatus()); ArgumentCaptor<Repository> captor = ArgumentCaptor.forClass(Repository.class); verify(repositoryInitializer).initialize(captor.capture()); Repository repository = captor.getValue(); assertEquals("space", repository.getNamespace()); assertEquals("repo", repository.getName()); } @Test public void shouldSetCurrentUserAsOwner() throws Exception { ArgumentCaptor<Repository> createCaptor = ArgumentCaptor.forClass(Repository.class); when(repositoryManager.create(createCaptor.capture())).thenAnswer(invocation -> { Repository repository = (Repository) invocation.getArguments()[0]; repository.setNamespace("otherspace"); return repository; }); URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); byte[] repositoryJson = Resources.toByteArray(url); MockHttpRequest request = MockHttpRequest .post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2) .contentType(VndMediaType.REPOSITORY) .content(repositoryJson); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertThat(createCaptor.getValue().getPermissions()) .hasSize(1) .allSatisfy(p -> { assertThat(p.getName()).isEqualTo("trillian"); assertThat(p.getRole()).isEqualTo("OWNER"); }); } @Test public void shouldCreateArrayOfProtocolUrls() throws Exception { mockRepository("space", "repo"); when(service.getSupportedProtocols()).thenReturn(of(new MockScmProtocol("http", "http://"), new MockScmProtocol("ssh", "ssh://"))); MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo"); MockHttpResponse response = new MockHttpResponse(); dispatcher.invoke(request, response); assertEquals(SC_OK, response.getStatus()); assertTrue(response.getContentAsString().contains("\"protocol\":[{\"href\":\"http://\",\"name\":\"http\"},{\"href\":\"ssh://\",\"name\":\"ssh\"}]")); } private PageResult<Repository> createSingletonPageResult(Repository repository) { return new PageResult<>(singletonList(repository), 0); } private Repository mockRepository(String namespace, String name) { return mockRepository(namespace, name, 0); } private Repository mockRepository(String namespace, String name, long lastModified) { Repository repository = new Repository(); repository.setNamespace(namespace); repository.setName(name); if (lastModified > 0) { repository.setLastModified(lastModified); } String id = namespace + "-" + name; repository.setId(id); when(repositoryManager.get(new NamespaceAndName(namespace, name))).thenReturn(repository); when(repositoryManager.get(id)).thenReturn(repository); return repository; } }
whodunnit/andlytics
src/com/github/andlyticsproject/LoginActivity.java
package com.github.andlyticsproject; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import java.io.IOException; public class LoginActivity extends BaseActivity { private static final String TAG = "Andlytics"; protected static final int CREATE_ACCOUNT_REQUEST = 1; private LinearLayout accountList; private TextView headline; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); headline = (TextView) findViewById(R.id.login_headline); Style.getInstance(getAssets()).styleHeadline(headline); TextView headlineBeta = (TextView) findViewById(R.id.login_headline_beta); Style.getInstance(getAssets()).styleHeadline(headlineBeta); accountList = (LinearLayout) findViewById(R.id.login_input); View addAccountButton = (View) findViewById(R.id.login_add_account_button); addAccountButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addNewGoogleAccount(); } }); } @Override protected void onResume() { super.onResume(); String selectedAccount = Preferences.getAccountName(this); boolean skipAutologin = Preferences.getSkipAutologin(this); if (!skipAutologin & selectedAccount != null) { redirectToMain(selectedAccount); } else { showAccountList(); } } protected void showAccountList() { final AccountManager manager = AccountManager.get(this); final Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE_GOOGLE); final int size = accounts.length; String[] names = new String[size]; accountList.removeAllViews(); for (int i = 0; i < size; i++) { names[i] = accounts[i].name; View inflate = getLayoutInflater().inflate(R.layout.login_list_item, null); TextView accountName = (TextView) inflate.findViewById(R.id.login_list_item_text); accountName.setText(accounts[i].name); inflate.setTag(accounts[i].name); inflate.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String selectedAccount = (String) view.getTag(); redirectToMain(selectedAccount); } }); accountList.addView(inflate); } } private void addNewGoogleAccount() { AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle bundle = future.getResult(); bundle.keySet(); Log.d(TAG, "account added: " + bundle); showAccountList(); } catch (OperationCanceledException e) { Log.d(TAG, "addAccount was canceled"); } catch (IOException e) { Log.d(TAG, "addAccount failed: " + e); } catch (AuthenticatorException e) { Log.d(TAG, "addAccount failed: " + e); } // gotAccount(false); } }; AccountManager.get(LoginActivity.this).addAccount(Constants.ACCOUNT_TYPE_GOOGLE, Constants.AUTH_TOKEN_TYPE_ANDROID_DEVLOPER, null, null /* options */, LoginActivity.this, callback, null /* handler */); } private void redirectToMain(String selectedAccount) { Preferences.saveSkipAutoLogin(this, false); Intent intent = new Intent(LoginActivity.this, Main.class); intent.putExtra(Constants.AUTH_ACCOUNT_NAME, selectedAccount); startActivity(intent); overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_fade_out); } }
android-nostalgic/platform_dalvik
libcore/x-net/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java
<filename>libcore/x-net/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java /* * 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. */ /** * @author <NAME> * @version $Revision$ */ package tests.api.javax.net; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.SocketException; import java.net.UnknownHostException; import javax.net.ServerSocketFactory; import junit.framework.TestCase; /** * Tests for <code>ServerSocketFactory</code> class constructors and methods. */ public class ServerSocketFactoryTest extends TestCase { /** * @tests javax.net.SocketFactory#SocketFactory() */ public void test_Constructor() { try { new MyServerSocketFactory(); } catch (Exception e) { fail("Unexpected exception " + e.toString()); } } /** * @tests javax.net.ServerSocketFactory#createServerSocket() */ public final void test_createServerSocket() { ServerSocketFactory sf = new MyServerSocketFactory(); try { sf.createServerSocket(); fail("No expected SocketException"); } catch (SocketException e) { } catch (IOException e) { fail(e.toString()); } } /** * @tests javax.net.ServerSocketFactory#getDefault() */ public final void test_getDefault() { ServerSocketFactory sf = ServerSocketFactory.getDefault(); ServerSocket s; try { s = sf.createServerSocket(0); s.close(); } catch (IOException e) { } try { s = sf.createServerSocket(0, 50); s.close(); } catch (IOException e) { } try { s = sf.createServerSocket(0, 50, InetAddress.getLocalHost()); s.close(); } catch (IOException e) { } } } class MyServerSocketFactory extends ServerSocketFactory { public MyServerSocketFactory() { super(); } public ServerSocket createServerSocket(int port) throws IOException, UnknownHostException { throw new IOException(); } public ServerSocket createServerSocket(int port, int backlog) throws IOException, UnknownHostException { throw new IOException(); } public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { throw new IOException(); } }
sp3cialk/MU-S8EP2-Repack
GameServer/Source/ChaosMachineManager.cpp
#include "stdafx.h" #include "ChaosMachineManager.h" #include "..\pugixml\pugixml.hpp" #include "GameMain.h" #include "DSProtocol.h" #include "..\common\winutil.h" #include "ChaosBox.h" // ------------------------------------------------------------------------------- using namespace pugi; ChaosMachineManager g_ChaosMachineManager; // ------------------------------------------------------------------------------- ChaosRecipe::ChaosRecipe(short RecipeIndex) { this->RecipeIndex = RecipeIndex; } // ------------------------------------------------------------------------------- ChaosRecipe::~ChaosRecipe() { this->Init(); } // ------------------------------------------------------------------------------- void ChaosRecipe::Init() { this->Combinations.clear(); if (this->Combinations.capacity() > 0) { std::vector<ChaosCombination>().swap(this->Combinations); } this->RecipeIndex = -1; } // ------------------------------------------------------------------------------- bool ChaosRecipe::Read(LPSTR File) { xml_document Document; xml_parse_result Result = Document.load_file(File); if (Result.status != status_ok) { MsgBox("[ChaosRecipe] File %s not found!", File); return false; } xml_node Recipe = Document.child("recipe"); strncpy(this->Name, Recipe.attribute("name").as_string(), sizeof(this->Name)); for (xml_node CombinationNode = Recipe.child("combination"); CombinationNode; CombinationNode = CombinationNode.next_sibling()) { ChaosCombination lpCombination; strncpy(lpCombination.Name, CombinationNode.attribute("name").as_string(), sizeof(lpCombination.Name)); lpCombination.Money = CombinationNode.child("money").text().as_int(0); lpCombination.SuccessRate = CombinationNode.child("successrate").text().as_int(0); for (xml_node IngredientNode = CombinationNode.child("ingredients").child("item"); IngredientNode; IngredientNode = IngredientNode.next_sibling()) { ChaosIngredient lpIngredient = { 0 }; lpIngredient.TypeStart = IngredientNode.attribute("starttype").as_int(0); lpIngredient.IndexStart = IngredientNode.attribute("startindex").as_int(0); lpIngredient.TypeEnd = IngredientNode.attribute("endtype").as_int(0); lpIngredient.IndexEnd = IngredientNode.attribute("endindex").as_int(0); lpIngredient.LevelMin = (BYTE)IngredientNode.attribute("minlevel").as_int(0); lpIngredient.LevelMax = (BYTE)IngredientNode.attribute("maxlevel").as_int(0); lpIngredient.OptionMin = IngredientNode.attribute("minoption").as_int(0); lpIngredient.OptionMax = IngredientNode.attribute("maxoption").as_int(0); lpIngredient.DurabilityMin = IngredientNode.attribute("mindur").as_int(0); lpIngredient.DurabilityMax = IngredientNode.attribute("maxdur").as_int(0); lpIngredient.CountMin = IngredientNode.attribute("mincount").as_int(0); lpIngredient.CountMax = IngredientNode.attribute("maxcount").as_int(0); strncpy(lpIngredient.Tag, CombinationNode.attribute("tag").as_string(), sizeof(lpIngredient.Tag)); lpCombination.Ingredients.push_back(lpIngredient); } for (xml_node TalismanNode = CombinationNode.child("talismans").child("item"); TalismanNode; TalismanNode = TalismanNode.next_sibling()) { ChaosTalisman lpTalisman = { 0 }; lpTalisman.TypeStart = TalismanNode.attribute("starttype").as_int(0); lpTalisman.IndexStart = TalismanNode.attribute("startindex").as_int(0); lpTalisman.TypeEnd = TalismanNode.attribute("endtype").as_int(0); lpTalisman.IndexEnd = TalismanNode.attribute("endindex").as_int(0); lpTalisman.LevelMin = (BYTE)TalismanNode.attribute("minlevel").as_int(0); lpTalisman.LevelMax = (BYTE)TalismanNode.attribute("maxlevel").as_int(0); lpTalisman.OptionMin = TalismanNode.attribute("minoption").as_int(0); lpTalisman.OptionMax = TalismanNode.attribute("maxoption").as_int(0); lpTalisman.DurabilityMin = TalismanNode.attribute("mindur").as_int(0); lpTalisman.DurabilityMax = TalismanNode.attribute("maxdur").as_int(0); lpTalisman.AdditionalRate = TalismanNode.attribute("addrate").as_int(0); lpTalisman.CountMax = TalismanNode.attribute("countmax").as_int(0); lpCombination.Talismans.push_back(lpTalisman); } for (xml_node ProduceNode = CombinationNode.child("produces").child("item"); ProduceNode; ProduceNode = ProduceNode.next_sibling()) { ChaosProduce lpProduce = { 0 }; lpProduce.Type = ProduceNode.attribute("type").as_int(0); lpProduce.Index = ProduceNode.attribute("index").as_int(0); lpProduce.LevelMin = ProduceNode.attribute("minlevel").as_int(0); lpProduce.LevelMax = ProduceNode.attribute("maxlevel").as_int(0); lpProduce.OptionMin = ProduceNode.attribute("minoption").as_int(0); lpProduce.OptionMax = ProduceNode.attribute("maxoption").as_int(0); lpProduce.Skill = ProduceNode.attribute("skill").as_int(0); lpProduce.Luck = ProduceNode.attribute("luck").as_int(0); lpProduce.ExcellentMin = ProduceNode.attribute("excmin").as_int(0); lpProduce.ExcellentMax = ProduceNode.attribute("excmax").as_int(0); lpProduce.Ancient = ProduceNode.attribute("ancient").as_int(0); lpProduce.SocketMin = ProduceNode.attribute("sockmin").as_int(0); lpProduce.SocketMax = ProduceNode.attribute("sockmax").as_int(0); lpProduce.Durability = ProduceNode.attribute("dur").as_int(0); lpCombination.Produces.push_back(lpProduce); } this->Combinations.push_back(lpCombination); } return true; } // ------------------------------------------------------------------------------- void ChaosRecipe::ActStart(LPOBJ lpUser, ChaosRecipe* lpRecipe, ChaosCombination* lpCombination) { lpUser->ChaosSuccessRate += lpCombination->SuccessRate; int ProduceIndex = rand() % lpCombination->Produces.size(); ChaosProduce* lpProduce = &lpCombination->Produces[ProduceIndex]; if (lpProduce == NULL) { LogAddC(2, "[DEBUG] Produce not found"); return; } if (lpUser->Money < lpCombination->Money) { ChaosRecipe::ActFail(lpUser, lpRecipe, lpCombination, CB_NOT_ENOUGH_ZEN); return; } DWORD Random = rand() % 100; lpUser->ChaosLock = true; lpUser->Money -= lpCombination->Money; GCMoneySend(lpUser->m_Index, lpUser->Money); if (Random > lpUser->ChaosSuccessRate) { ChaosRecipe::ActFail(lpUser, lpRecipe, lpCombination); } else { ChaosRecipe::ActSuccess(lpUser, lpRecipe, lpCombination, lpProduce); } } // ------------------------------------------------------------------------------- bool ChaosRecipe::ActCheck(LPOBJ lpUser, ChaosRecipe* lpRecipe, ChaosCombination* lpCombination) { return false; } // ------------------------------------------------------------------------------- void ChaosRecipe::ActFail(LPOBJ lpUser, ChaosRecipe* lpRecipe, ChaosCombination* lpCombination, BYTE ErrorCode) { PMSG_CHAOSMIXRESULT lpResult; PHeadSetB((LPBYTE)&lpResult.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT)); lpResult.Result = ErrorCode; // ChaosBoxWingMixItemDown(lpObj); g_ChaosBox.ChaosBoxInit(lpUser); GCUserChaosBoxSend(lpUser, 0); DataSend(lpUser->m_Index, (LPBYTE)&lpResult, lpResult.h.size); lpUser->ChaosLock = false; LogAddTD("[ChaosRecipe] [%s] [%s] Combination has failed (Recipe: %s, Combination: %s, Rate: %d)", lpUser->AccountID, lpUser->Name, lpRecipe->Name, lpCombination->Name, lpUser->ChaosSuccessRate); } // ------------------------------------------------------------------------------- void ChaosRecipe::ActFail(LPOBJ lpUser, ChaosRecipe* lpRecipe, ChaosCombination* lpCombination) { ChaosRecipe::ActFail(lpUser, lpRecipe, lpCombination, CB_ERROR); } // ------------------------------------------------------------------------------- void ChaosRecipe::ActSuccess(LPOBJ lpUser, ChaosRecipe* lpRecipe, ChaosCombination* lpCombination, ChaosProduce* lpProduce) { BYTE Level = 0; BYTE Durability = 0; BYTE Option = 0; if (lpProduce->LevelMax == lpProduce->LevelMin) { Level = lpProduce->LevelMax; } else if (lpProduce->LevelMin < lpProduce->LevelMax) { int Sub = (lpProduce->LevelMax - lpProduce->LevelMin) + 1; Level = lpProduce->LevelMin + (rand() % Sub); } else { Level = lpProduce->LevelMin; LogAddTD("[ChaosRecipe] [%s] [%s] (Warning) Produce have wrong level (Recipe: %s, Combination: %s)", lpUser->AccountID, lpUser->Name, lpRecipe->Name, lpCombination->Name); } if (Level > 15) { Level = 15; } if (lpProduce->OptionMax == lpProduce->OptionMin ) { Option = lpProduce->OptionMax; } else if (lpProduce->OptionMin < lpProduce->OptionMax ) { int Sub = (lpProduce->OptionMax - lpProduce->OptionMin) + 1; Option = lpProduce->OptionMin + (rand() % Sub); } else { Durability = lpProduce->OptionMin; LogAddTD("[ChaosRecipe] [%s] [%s] (Warning) Produce have wrong option (Recipe: %s, Combination: %s)", lpUser->AccountID, lpUser->Name, lpRecipe->Name, lpCombination->Name); } if (Option > 7) { Option = 7; } ItemSerialCreateSend(lpUser->m_Index, 255, 0, 0, ITEMGET(lpProduce->Type, lpProduce->Index), Level, lpProduce->Durability, lpProduce->Skill, lpProduce->Luck, Option, -1, 0, 0); gObjInventoryCommit(lpUser->m_Index); LogAddTD("[ChaosRecipe] [%s] [%s] Combination has succeeded (Recipe: %s, Combination: %s, Rate: %d)", lpUser->AccountID, lpUser->Name, lpRecipe->Name, lpCombination->Name, lpUser->ChaosSuccessRate); } // ------------------------------------------------------------------------------- bool ChaosRecipe::CheckIngredient(LPOBJ lpUser, short ChaosPos, ChaosIngredient* Ingredient) { if (!lpUser->pChaosBox[ChaosPos].IsItem()) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Type < ITEMGET(Ingredient->TypeStart, Ingredient->IndexStart) || lpUser->pChaosBox[ChaosPos].m_Type > ITEMGET(Ingredient->TypeEnd, Ingredient->IndexEnd)) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Level < Ingredient->LevelMin && Ingredient->LevelMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Level > Ingredient->LevelMax && Ingredient->LevelMax != (BYTE)-1) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Option3 < Ingredient->OptionMin && Ingredient->OptionMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Option3 > Ingredient->OptionMax && Ingredient->OptionMax != (BYTE)-1) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Durability < Ingredient->DurabilityMin && Ingredient->DurabilityMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Durability > Ingredient->DurabilityMax && Ingredient->DurabilityMax != (BYTE)-1) { return false; } return true; } // ------------------------------------------------------------------------------- bool ChaosRecipe::CheckTalisman(LPOBJ lpUser, short ChaosPos, ChaosTalisman* lpTalisman) { if (!lpUser->pChaosBox[ChaosPos].IsItem()) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Type < ITEMGET(lpTalisman->TypeStart, lpTalisman->IndexStart) || lpUser->pChaosBox[ChaosPos].m_Type > ITEMGET(lpTalisman->TypeEnd, lpTalisman->IndexEnd)) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Level < lpTalisman->LevelMin && lpTalisman->LevelMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Level > lpTalisman->LevelMax && lpTalisman->LevelMax != (BYTE)-1) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Option3 < lpTalisman->OptionMin && lpTalisman->OptionMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Option3 > lpTalisman->OptionMax && lpTalisman->OptionMax != (BYTE)-1) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Durability < lpTalisman->DurabilityMin && lpTalisman->DurabilityMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Durability > lpTalisman->DurabilityMax && lpTalisman->DurabilityMax != (BYTE)-1) { return false; } return true; } // ------------------------------------------------------------------------------- bool ChaosRecipe::ApplyTalisman(LPOBJ lpUser, short ChaosPos, ChaosRecipe* lpRecipe, ChaosCombination* lpCombination, ChaosTalisman* lpTalisman) { if (!lpUser->pChaosBox[ChaosPos].IsItem()) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Type < ITEMGET(lpTalisman->TypeStart, lpTalisman->IndexStart) || lpUser->pChaosBox[ChaosPos].m_Type > ITEMGET(lpTalisman->TypeEnd, lpTalisman->IndexEnd)) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Level < lpTalisman->LevelMin && lpTalisman->LevelMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Level > lpTalisman->LevelMax && lpTalisman->LevelMax != (BYTE)-1) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Option3 < lpTalisman->OptionMin && lpTalisman->OptionMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Option3 > lpTalisman->OptionMax && lpTalisman->OptionMax != (BYTE)-1) { return false; } if (lpUser->pChaosBox[ChaosPos].m_Durability < lpTalisman->DurabilityMin && lpTalisman->DurabilityMin != (BYTE)-1 || lpUser->pChaosBox[ChaosPos].m_Durability > lpTalisman->DurabilityMax && lpTalisman->DurabilityMax != (BYTE)-1) { return false; } BYTE RateIncrease = 0; if (lpTalisman->AdditionalRate == (BYTE)-1) { RateIncrease += lpUser->pChaosBox[ChaosPos].m_Durability; } else { RateIncrease += lpTalisman->AdditionalRate; } lpUser->ChaosSuccessRate += RateIncrease; LogAddTD("[ChaosRecipe] [%s] [%s] Talisman has been applied (Recipe: %s, Combination: %s, Talisman: %d-%d, Increase: %d)", lpUser->AccountID, lpUser->Name, lpRecipe->Name, lpCombination->Name, lpUser->pChaosBox[ChaosPos].m_Type / 512, lpUser->pChaosBox[ChaosPos].m_Type % 512, RateIncrease); return true; } // ------------------------------------------------------------------------------- ChaosMachineManager::ChaosMachineManager() { } // ------------------------------------------------------------------------------- ChaosMachineManager::~ChaosMachineManager() { } // ------------------------------------------------------------------------------- void ChaosMachineManager::Init() { this->Recipes.clear(); if (this->Recipes.capacity() > 0) { std::vector<ChaosRecipe*>().swap(this->Recipes); } } // ------------------------------------------------------------------------------- void ChaosMachineManager::Load() { this->Init(); this->Read(gDirPath.GetNewPath(FILE_CHAOSMACHINE)); } // ------------------------------------------------------------------------------- void ChaosMachineManager::Read(LPSTR File) { xml_document Document; xml_parse_result Result = Document.load_file(File); if (Result.status != status_ok) { MsgBox("[ChaosMachineManager] File %s not found!", File); return; } xml_node Recipe = Document.child("chaosmachine"); for (xml_node CombinationNode = Recipe.child("mixlist").child("recipe"); CombinationNode; CombinationNode = CombinationNode.next_sibling()) { char FileName[MAX_PATH] = { 0 }; sprintf(FileName, "%s%s", gDirPath.GetNewPath(PATH_CHAOSMACHINE), CombinationNode.text().as_string()); ChaosRecipe* lpRecipe = new ChaosRecipe(CombinationNode.attribute("index").as_int(0)); if (!lpRecipe->Read(FileName)) { continue; } this->Recipes.push_back(lpRecipe); } } // ------------------------------------------------------------------------------- bool ChaosMachineManager::StartMix(LPOBJ lpUser, short RecipeIndex) { lpUser->ChaosSuccessRate = 0; for (int Recipe = 0; Recipe < this->Recipes.size(); Recipe++) { if (this->Recipes[Recipe]->RecipeIndex == RecipeIndex) { int ActiveCombination = -1; //Select active combination for (int Combination = 0; Combination < this->Recipes[Recipe]->Combinations.size(); Combination++) { BYTE ItemCounter[CHAOS_BOX_SIZE] = { 0 }; BYTE TalismanCounter[CHAOS_BOX_SIZE] = { 0 }; for (int Pos = 0; Pos < CHAOS_BOX_SIZE; Pos++) { if (!lpUser->pChaosBox[Pos].IsItem()) { continue; } for (int n = 0; n < this->Recipes[Recipe]->Combinations[Combination].Ingredients.size(); n++) { if (n >= CHAOS_BOX_SIZE-1) { break; } ChaosIngredient* lpIngredient = &this->Recipes[Recipe]->Combinations[Combination].Ingredients[n]; if (ChaosRecipe::CheckIngredient(lpUser, Pos, lpIngredient)) { ItemCounter[n]++; } } } bool CountRange = true; for (int n = 0; n < this->Recipes[Recipe]->Combinations[Combination].Ingredients.size(); n++) { if (ItemCounter[n] < this->Recipes[Recipe]->Combinations[Combination].Ingredients[n].CountMin || ItemCounter[n] > this->Recipes[Recipe]->Combinations[Combination].Ingredients[n].CountMax) { LogAddC(2, "[DEBUG] Wrong range (%d:%d, %d/%d:%d)", this->Recipes[Recipe]->Combinations[Combination].Ingredients[n].TypeStart, this->Recipes[Recipe]->Combinations[Combination].Ingredients[n].IndexStart, ItemCounter[n], this->Recipes[Recipe]->Combinations[Combination].Ingredients[n].CountMin, this->Recipes[Recipe]->Combinations[Combination].Ingredients[n].CountMax); CountRange = false; break; } } if (CountRange) { ActiveCombination = Combination; break; } } if (ActiveCombination == -1) { LogAddC(2, "[DEBUG] Combination not found"); return false; } ChaosCombination* lpCombination = &this->Recipes[Recipe]->Combinations[ActiveCombination]; if (lpCombination->Produces.size() <= 0) { LogAddC(2, "[DEBUG] Produces list not filled"); return false; } //Talisman effect apply BYTE TalismanCounter[CHAOS_BOX_SIZE] = { 0 }; for (int Pos = 0; Pos < CHAOS_BOX_SIZE; Pos++) { if (!lpUser->pChaosBox[Pos].IsItem()) { continue; } for (int n = 0; n < this->Recipes[Recipe]->Combinations[ActiveCombination].Talismans.size(); n++) { if (n >= CHAOS_BOX_SIZE-1) { break; } ChaosTalisman* lpTalisman = &this->Recipes[Recipe]->Combinations[ActiveCombination].Talismans[n]; if (ChaosRecipe::CheckTalisman(lpUser, Pos, lpTalisman)) { if (TalismanCounter[n] < lpTalisman->CountMax) { ChaosRecipe::ApplyTalisman(lpUser, Pos, this->Recipes[Recipe], &this->Recipes[Recipe]->Combinations[ActiveCombination], lpTalisman); TalismanCounter[n]++; } else { ChaosRecipe::ActFail(lpUser, this->Recipes[Recipe], &this->Recipes[Recipe]->Combinations[ActiveCombination], 0xF0); return 0; } } } } ChaosRecipe::ActStart(lpUser, this->Recipes[Recipe], lpCombination); return true; } } return false; } // -------------------------------------------------------------------------------
dwp/ClaimCapture
c3/app/models/yesNo/YesNoWithAddressAnd2TextOrTextWithYesNoAndText.scala
package models.yesNo import models.MultiLineAddress case class YesNoWithAddressAnd2TextOrTextWithYesNoAndText(answer: String = "", employerName:Option[String] = None, address: Option[MultiLineAddress] = None, postCode: Option[String] = None, text1a: Option[String] = None, text2a: Option[String] = None, answer2: Option[String] = None, text2b: Option[String] = None) object YesNoWithAddressAnd2TextOrTextWithYesNoAndText { def validateNameOnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.employerName.isDefined case _ => true } def validateAddressOnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.address.isDefined case _ => true } def validateAddressLine1OnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.address.isDefined && input.address.get.lineOne.isDefined case _ => true } def validateAddressLine2OnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.address.isDefined && input.address.get.lineTwo.isDefined case _ => true } def validatePostcodeOnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.postCode.isDefined case _ => true } def validateText2OnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.text2a.isDefined case _ => true } def validateAnswer2OnSpecifiedAnswer(input: YesNoWithAddressAnd2TextOrTextWithYesNoAndText, requiredAnswer: String): Boolean = input.answer match { case s if s == requiredAnswer => input.answer2.isDefined case _ => true } def validateAnswerNotEmpty(input: YesNoWithAddress): Boolean = input.answer.nonEmpty }
EPiCS/soundgates
software/editor/Soundgates.diagram/src/soundgates/diagram/soundcomponents/CompositeSoundComponentLibrary.java
<gh_stars>0 package soundgates.diagram.soundcomponents; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import org.eclipse.core.resources.IFolder; import org.eclipse.emf.ecore.util.EcoreUtil; import soundgates.AtomicSoundComponent; import soundgates.CompositeSoundComponent; import soundgates.SoundComponent; public class CompositeSoundComponentLibrary{ private static CompositeSoundComponentLibrary instance; private static TreeMap<String, CompositeSoundComponent> components; private static IFolder xmlfolder; private static HashMap<String,Integer> diagramToCounter = new HashMap<>(); public static final String defaultName="CompositeComponent"; public static CompositeSoundComponentLibrary getInstance() { if (instance == null) { instance = new CompositeSoundComponentLibrary(); String path = xmlfolder.getRawLocation().toString()+"/"; createFromXML(path); } return instance; } private CompositeSoundComponentLibrary() { components = new TreeMap<String, CompositeSoundComponent>(); } public static String getNumberedName(String fileName){ if(diagramToCounter.containsKey(fileName)){ int number = diagramToCounter.get(fileName); diagramToCounter.put(fileName, number+1); return defaultName + Integer.toString(number); } else{ diagramToCounter.put(fileName, 2); return defaultName+"1"; } } public void addComponent(CompositeSoundComponent component) { components.put(component.getName(), component); } public static CompositeSoundComponentLibrary createFromXML(String libraryPath) { // TODO check for compliance with XSD instance = new CompositeSoundComponentLibrary(); CompositeSoundComponentXMLHandler.readFromXML(instance, libraryPath); return instance; } public CompositeSoundComponent createCompositeSoundComponentInstance(String compositeSoundComponentName) { CompositeSoundComponent blueprint = components.get(compositeSoundComponentName); CompositeSoundComponent compositeSoundComponentCopy = EcoreUtil.copy(blueprint); //walkaround for(SoundComponent soundComponent : compositeSoundComponentCopy.getEmbeddedComponents()){ if(soundComponent instanceof AtomicSoundComponent){ AtomicSoundComponent atomicSoundComponent = (AtomicSoundComponent) soundComponent; atomicSoundComponent.setType(atomicSoundComponent.getStringProperties().get("Type")); atomicSoundComponent.getStringProperties().removeKey("Type"); } } return compositeSoundComponentCopy; } public List<String> getAvailableComponents() { ArrayList<String> list = new ArrayList<String>(); list.addAll(components.keySet()); return list; } /** * Set's the xml library to a given folder * This requires the library to be reconstructed, so the instance is dereferenced * @param folder */ public static void setXMLFolder(IFolder folder) { instance = null; xmlfolder = folder; } public static IFolder getXMLFolder() { return xmlfolder; } public static boolean compositeSoundComponentIsInLibrary(String name){ for(String libComponent : components.keySet()){ if(libComponent.equals(name)) return true; } return false; } public static boolean componentsFolderContaintsFile(String fileName){ File folder = new File(xmlfolder.getRawLocation().toString()); for(File file : folder.listFiles()){ if(file.getName().equals(fileName)) return true; } return false; } }
Shashi-rk/azure-sdk-for-java
sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapCloudForCustomerLinkedService.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.artifacts.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** Linked service for SAP Cloud for Customer. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("SapCloudForCustomer") @JsonFlatten @Fluent public class SapCloudForCustomerLinkedService extends LinkedService { /* * The URL of SAP Cloud for Customer OData API. For example, * '[https://[tenantname].crm.ondemand.com/sap/c4c/odata/v1]'. Type: string * (or Expression with resultType string). */ @JsonProperty(value = "typeProperties.url", required = true) private Object url; /* * The username for Basic authentication. Type: string (or Expression with * resultType string). */ @JsonProperty(value = "typeProperties.username") private Object username; /* * The password for Basic authentication. */ @JsonProperty(value = "typeProperties.password") private SecretBase password; /* * The encrypted credential used for authentication. Credentials are * encrypted using the integration runtime credential manager. Either * encryptedCredential or username/password must be provided. Type: string * (or Expression with resultType string). */ @JsonProperty(value = "typeProperties.encryptedCredential") private Object encryptedCredential; /** * Get the url property: The URL of SAP Cloud for Customer OData API. For example, * '[https://[tenantname].crm.ondemand.com/sap/c4c/odata/v1]'. Type: string (or Expression with resultType string). * * @return the url value. */ public Object getUrl() { return this.url; } /** * Set the url property: The URL of SAP Cloud for Customer OData API. For example, * '[https://[tenantname].crm.ondemand.com/sap/c4c/odata/v1]'. Type: string (or Expression with resultType string). * * @param url the url value to set. * @return the SapCloudForCustomerLinkedService object itself. */ public SapCloudForCustomerLinkedService setUrl(Object url) { this.url = url; return this; } /** * Get the username property: The username for Basic authentication. Type: string (or Expression with resultType * string). * * @return the username value. */ public Object getUsername() { return this.username; } /** * Set the username property: The username for Basic authentication. Type: string (or Expression with resultType * string). * * @param username the username value to set. * @return the SapCloudForCustomerLinkedService object itself. */ public SapCloudForCustomerLinkedService setUsername(Object username) { this.username = username; return this; } /** * Get the password property: The password for Basic authentication. * * @return the password value. */ public SecretBase getPassword() { return this.password; } /** * Set the password property: The password for Basic authentication. * * @param password the password value to set. * @return the SapCloudForCustomerLinkedService object itself. */ public SapCloudForCustomerLinkedService setPassword(SecretBase password) { this.password = password; return this; } /** * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Either encryptedCredential or username/password must be * provided. Type: string (or Expression with resultType string). * * @return the encryptedCredential value. */ public Object getEncryptedCredential() { return this.encryptedCredential; } /** * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Either encryptedCredential or username/password must be * provided. Type: string (or Expression with resultType string). * * @param encryptedCredential the encryptedCredential value to set. * @return the SapCloudForCustomerLinkedService object itself. */ public SapCloudForCustomerLinkedService setEncryptedCredential(Object encryptedCredential) { this.encryptedCredential = encryptedCredential; return this; } }
twtrubiks/leetcode-python
test_Rotate_Array_189.py
import unittest from Rotate_Array_189 import * ''' Given an array, rotate the array to the right by k steps, where k is non-negative. Follow up: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] ''' class Test_Case(unittest.TestCase): def test_answer_01(self): nums = [1,2,3,4,5,6,7] k = 3 result = [5,6,7,1,2,3,4] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_02(self): nums = [-1,-100,3,99] k = 2 result = [3,99,-1,-100] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_03(self): nums = [1,2,3,4,5,6,7] k = 3 result = [5,6,7,1,2,3,4] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_04(self): nums = [-1,-100,3,99] k = 2 result = [3,99,-1,-100] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_05(self): nums = [1] k = 0 result = [1] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_06(self): nums = [1,2] k = 3 result = [2,1] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_07(self): nums = [1,2,3] k = 1 result = [3,1,2] self.assertEqual(Solution().rotate(nums, k), result) def test_answer_08(self): nums = [1,2,3] k = 2 result = [2,3,1] self.assertEqual(Solution().rotate(nums, k), result) if __name__ == '__main__': unittest.main()
NaokiTakahashi12/mpc_ros
mpc_ros/src/MPC_Node.cpp
<reponame>NaokiTakahashi12/mpc_ros /* # Copyright 2018 HyphaROS Workshop. # Developer: HaoChih, LIN (<EMAIL>) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. */ #include <iostream> #include <map> #include <math.h> #include "ros/ros.h" #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Twist.h> #include <tf/transform_listener.h> // #include <tf/transform_datatypes.h> #include <nav_msgs/Path.h> #include <nav_msgs/Odometry.h> //#include <ackermann_msgs/AckermannDriveStamped.h> #include <visualization_msgs/Marker.h> #include "MPC.h" #include <Eigen/Core> #include <Eigen/QR> using namespace std; using namespace Eigen; /********************/ /* CLASS DEFINITION */ /********************/ class MPCNode { public: MPCNode(); int get_thread_numbers(); private: ros::NodeHandle _nh; ros::Subscriber _sub_odom, _sub_gen_path, _sub_path, _sub_goal, _sub_amcl; ros::Publisher _pub_globalpath,_pub_odompath, _pub_twist, _pub_mpctraj; ros::Publisher _pub_ackermann; ros::Timer _timer1; tf::TransformListener _tf_listener; geometry_msgs::Point _goal_pos; nav_msgs::Odometry _odom; nav_msgs::Path _odom_path, _mpc_traj; //ackermann_msgs::AckermannDriveStamped _ackermann_msg; geometry_msgs::Twist _twist_msg; string _globalPath_topic, _goal_topic; string _map_frame, _odom_frame, _car_frame; MPC _mpc; map<string, double> _mpc_params; double _mpc_steps, _ref_cte, _ref_etheta, _ref_vel, _w_cte, _w_etheta, _w_vel, _w_angvel, _w_accel, _w_angvel_d, _w_accel_d, _max_angvel, _max_throttle, _bound_value; //double _Lf; double _dt, _w, _throttle, _speed, _max_speed; double _pathLength, _goalRadius, _waypointsDist; int _controller_freq, _downSampling, _thread_numbers; bool _goal_received, _goal_reached, _path_computed, _pub_twist_flag, _debug_info, _delay_mode; double polyeval(Eigen::VectorXd coeffs, double x); Eigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals, int order); void odomCB(const nav_msgs::Odometry::ConstPtr& odomMsg); void pathCB(const nav_msgs::Path::ConstPtr& pathMsg); void desiredPathCB(const nav_msgs::Path::ConstPtr& pathMsg); void goalCB(const geometry_msgs::PoseStamped::ConstPtr& goalMsg); void amclCB(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& amclMsg); void controlLoopCB(const ros::TimerEvent&); void makeGlobalPath(const nav_msgs::Odometry odomMsg); //For making global planner nav_msgs::Path _gen_path; }; // end of class MPCNode::MPCNode() { //Private parameters handler ros::NodeHandle pn("~"); //Parameters for control loop pn.param("thread_numbers", _thread_numbers, 2); // number of threads for this ROS node pn.param("pub_twist_cmd", _pub_twist_flag, true); pn.param("debug_info", _debug_info, true); pn.param("delay_mode", _delay_mode, true); pn.param("max_speed", _max_speed, 0.50); // unit: m/s pn.param("waypoints_dist", _waypointsDist, -1.0); // unit: m pn.param("path_length", _pathLength, 8.0); // unit: m pn.param("goal_radius", _goalRadius, 0.5); // unit: m pn.param("controller_freq", _controller_freq, 10); //pn.param("vehicle_Lf", _Lf, 0.290); // distance between the front of the vehicle and its center of gravity _dt = double(1.0/_controller_freq); // time step duration dt in s //Parameter for MPC solver pn.param("mpc_steps", _mpc_steps, 20.0); pn.param("mpc_ref_cte", _ref_cte, 0.0); pn.param("mpc_ref_vel", _ref_vel, 1.0); pn.param("mpc_ref_etheta", _ref_etheta, 0.0); pn.param("mpc_w_cte", _w_cte, 5000.0); pn.param("mpc_w_etheta", _w_etheta, 5000.0); pn.param("mpc_w_vel", _w_vel, 1.0); pn.param("mpc_w_angvel", _w_angvel, 100.0); pn.param("mpc_w_angvel_d", _w_angvel_d, 10.0); pn.param("mpc_w_accel", _w_accel, 50.0); pn.param("mpc_w_accel_d", _w_accel_d, 10.0); pn.param("mpc_max_angvel", _max_angvel, 3.0); // Maximal angvel radian (~30 deg) pn.param("mpc_max_throttle", _max_throttle, 1.0); // Maximal throttle accel pn.param("mpc_bound_value", _bound_value, 1.0e3); // Bound value for other variables //Parameter for topics & Frame name pn.param<std::string>("global_path_topic", _globalPath_topic, "/move_base/TrajectoryPlannerROS/global_plan" ); pn.param<std::string>("goal_topic", _goal_topic, "/move_base_simple/goal" ); pn.param<std::string>("map_frame", _map_frame, "map" ); //*****for mpc, "odom" pn.param<std::string>("odom_frame", _odom_frame, "odom"); pn.param<std::string>("car_frame", _car_frame, "base_footprint" ); //Display the parameters cout << "\n===== Parameters =====" << endl; cout << "pub_twist_cmd: " << _pub_twist_flag << endl; cout << "debug_info: " << _debug_info << endl; cout << "delay_mode: " << _delay_mode << endl; //cout << "vehicle_Lf: " << _Lf << endl; cout << "frequency: " << _dt << endl; cout << "mpc_steps: " << _mpc_steps << endl; cout << "mpc_ref_vel: " << _ref_vel << endl; cout << "mpc_w_cte: " << _w_cte << endl; cout << "mpc_w_etheta: " << _w_etheta << endl; cout << "mpc_max_angvel: " << _max_angvel << endl; //Publishers and Subscribers _sub_odom = _nh.subscribe("/odom", 1, &MPCNode::odomCB, this); _sub_path = _nh.subscribe( _globalPath_topic, 1, &MPCNode::pathCB, this); _sub_gen_path = _nh.subscribe( "desired_path", 1, &MPCNode::desiredPathCB, this); _sub_goal = _nh.subscribe( _goal_topic, 1, &MPCNode::goalCB, this); _sub_amcl = _nh.subscribe("/amcl_pose", 5, &MPCNode::amclCB, this); _pub_globalpath = _nh.advertise<nav_msgs::Path>("/global_path", 1); // Global path generated from another source _pub_odompath = _nh.advertise<nav_msgs::Path>("/mpc_reference", 1); // reference path for MPC ///mpc_reference _pub_mpctraj = _nh.advertise<nav_msgs::Path>("/mpc_trajectory", 1);// MPC trajectory output //_pub_ackermann = _nh.advertise<ackermann_msgs::AckermannDriveStamped>("/ackermann_cmd", 1); if(_pub_twist_flag) _pub_twist = _nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1); //for stage (Ackermann msg non-supported) //Timer _timer1 = _nh.createTimer(ros::Duration((1.0)/_controller_freq), &MPCNode::controlLoopCB, this); // 10Hz //*****mpc //Init variables _goal_received = false; _goal_reached = false; _path_computed = false; _throttle = 0.0; _w = 0.0; _speed = 0.0; //_ackermann_msg = ackermann_msgs::AckermannDriveStamped(); _twist_msg = geometry_msgs::Twist(); _mpc_traj = nav_msgs::Path(); //Init parameters for MPC object _mpc_params["DT"] = _dt; //_mpc_params["LF"] = _Lf; _mpc_params["STEPS"] = _mpc_steps; _mpc_params["REF_CTE"] = _ref_cte; _mpc_params["REF_ETHETA"] = _ref_etheta; _mpc_params["REF_V"] = _ref_vel; _mpc_params["W_CTE"] = _w_cte; _mpc_params["W_EPSI"] = _w_etheta; _mpc_params["W_V"] = _w_vel; _mpc_params["W_ANGVEL"] = _w_angvel; _mpc_params["W_A"] = _w_accel; _mpc_params["W_DANGVEL"] = _w_angvel_d; _mpc_params["W_DA"] = _w_accel_d; _mpc_params["ANGVEL"] = _max_angvel; _mpc_params["MAXTHR"] = _max_throttle; _mpc_params["BOUND"] = _bound_value; _mpc.LoadParams(_mpc_params); } // Public: return _thread_numbers int MPCNode::get_thread_numbers() { return _thread_numbers; } // Evaluate a polynomial. double MPCNode::polyeval(Eigen::VectorXd coeffs, double x) { double result = 0.0; for (int i = 0; i < coeffs.size(); i++) { result += coeffs[i] * pow(x, i); } return result; } // Fit a polynomial. // Adapted from // https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716 Eigen::VectorXd MPCNode::polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals, int order) { assert(xvals.size() == yvals.size()); assert(order >= 1 && order <= xvals.size() - 1); Eigen::MatrixXd A(xvals.size(), order + 1); for (int i = 0; i < xvals.size(); i++) A(i, 0) = 1.0; for (int j = 0; j < xvals.size(); j++) { for (int i = 0; i < order; i++) A(j, i + 1) = A(j, i) * xvals(j); } auto Q = A.householderQr(); auto result = Q.solve(yvals); return result; } // CallBack: Update odometry void MPCNode::odomCB(const nav_msgs::Odometry::ConstPtr& odomMsg) { _odom = *odomMsg; } void MPCNode::makeGlobalPath(const nav_msgs::Odometry odomMsg) { /* nav_msgs::Path global_path = nav_msgs::Path(); geometry_msgs::PoseStamped startPose; geometry_msgs::PoseStamped tempPose; nav_msgs::Odometry odom = odomMsg; //Calculate the waypoint distance double gap_x = _gen_path.poses[1].pose.position.x - _gen_path.poses[0].pose.position.x; double gap_y = _gen_path.poses[1].pose.position.y - _gen_path.poses[0].pose.position.y; _waypointsDist = sqrt(gap_x*gap_x + gap_y*gap_y); static double pre_odom_x = odom.pose.pose.position.x; static double pre_odom_y = odom.pose.pose.position.y; static double odom_diff = 0; static int n_waypointMove = 0; int N = _gen_path.poses.size(); // Number of waypoints try { double total_length = 0.0; startPose.header.stamp = ros::Time::now(); startPose.header.frame_id = _odom_frame; startPose.pose = odom.pose.pose; global_path.poses.push_back(startPose); // copy current odom position to the start position // Calculate the difference and save the odom x,y odom_diff = sqrt((odom.pose.pose.position.x - pre_odom_x)*(odom.pose.pose.position.x - pre_odom_x) + (odom.pose.pose.position.y-pre_odom_y)*(odom.pose.pose.position.y-pre_odom_y)); pre_odom_x = odom.pose.pose.position.x; pre_odom_y = odom.pose.pose.position.y; n_waypointMove += (int)(odom_diff / _waypointsDist); cout << "n_waypointMove: " << n_waypointMove << endl; if(n_waypointMove > N) { n_waypointMove = 0; } // Append the part of the generated path for(int i = n_waypointMove; i < N ; i++) { _tf_listener.transformPose(_odom_frame, ros::Time(0) , _gen_path.poses[i], _map_frame, tempPose); global_path.poses.push_back(tempPose); total_length = total_length + _waypointsDist; } // publish global_path global_path.header.frame_id = _odom_frame; global_path.header.stamp = ros::Time::now(); _pub_globalpath.publish(global_path); //desiredPathCB(global_path); // for cutting and down sampling } catch(tf::TransformException &ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); } */ } // CallBack: Update generated path (conversion to odom frame) void MPCNode::desiredPathCB(const nav_msgs::Path::ConstPtr& totalPathMsg) { /* _gen_path = *totalPathMsg; //For plan the global path about desired path makeGlobalPath(_odom); _goal_received = true; _goal_reached = false; nav_msgs::Path mpc_path = nav_msgs::Path(); // For generating mpc reference path geometry_msgs::PoseStamped tempPose; nav_msgs::Odometry odom = _odom; try { double total_length = 0.0; _pathLength = 6; //find waypoints distance if(_waypointsDist <= 0.0) { double gap_x = totalPathMsg->poses[1].pose.position.x - totalPathMsg->poses[0].pose.position.x; double gap_y = totalPathMsg->poses[1].pose.position.y - totalPathMsg->poses[0].pose.position.y; _waypointsDist = sqrt(gap_x*gap_x + gap_y*gap_y); } // Find the nearst point for robot position int min_idx = 0; int min_val = 100; // why double is wrong? int N = totalPathMsg->poses.size(); // Number of waypoints const double px = odom.pose.pose.position.x; //pose: odom frame const double py = odom.pose.pose.position.y; const double ptheta = odom.pose.pose.position.y; double dx, dy; // difference distance double pre_yaw = 0; double roll, pitch, yaw = 0; for(int i = 0; i < N; i++) { dx = totalPathMsg->poses[i].pose.position.x - px; dy = totalPathMsg->poses[i].pose.position.y - py; tf::Quaternion q( totalPathMsg->poses[i].pose.orientation.x, totalPathMsg->poses[i].pose.orientation.y, totalPathMsg->poses[i].pose.orientation.z, totalPathMsg->poses[i].pose.orientation.w); tf::Matrix3x3 m(q); m.getRPY(roll, pitch, yaw); if(abs(pre_yaw - yaw) > 5) { cout << "abs(pre_yaw - yaw)" << abs(pre_yaw - yaw) << endl; pre_yaw = yaw; } if(min_val > sqrt(dx*dx + dy*dy)) { min_val = sqrt(dx*dx + dy*dy); min_idx = i; if(i < N * 0.02) min_idx = N - 100; //for smoothing about init position } } for(int i = min_idx; i < N ; i++) { if(total_length > _pathLength) break; _tf_listener.transformPose(_odom_frame, ros::Time(0) , totalPathMsg->poses[i], _map_frame, tempPose); mpc_path.poses.push_back(tempPose); total_length = total_length + _waypointsDist; } // Connect the end of path to the front if(total_length < _pathLength ) { for(int i = 0; i < N ; i++) { if(total_length > _pathLength) break; _tf_listener.transformPose(_odom_frame, ros::Time(0) , totalPathMsg->poses[i], _map_frame, tempPose); mpc_path.poses.push_back(tempPose); total_length = total_length + _waypointsDist; } } if(mpc_path.poses.size() >= _pathLength ) { _odom_path = mpc_path; // Path waypoints in odom frame _path_computed = true; // publish odom path mpc_path.header.frame_id = _odom_frame; mpc_path.header.stamp = ros::Time::now(); _pub_odompath.publish(mpc_path); } else { cout << "Failed to path generation" << endl; _waypointsDist = -1; } } catch(tf::TransformException &ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); } */ } // CallBack: Update path waypoints (conversion to odom frame) void MPCNode::pathCB(const nav_msgs::Path::ConstPtr& pathMsg) { if(_goal_received && !_goal_reached) { cout << "PathCB condition" << endl; nav_msgs::Path odom_path = nav_msgs::Path(); try { double total_length = 0.0; int sampling = _downSampling; //find waypoints distance if(_waypointsDist <=0.0) { double dx = pathMsg->poses[1].pose.position.x - pathMsg->poses[0].pose.position.x; double dy = pathMsg->poses[1].pose.position.y - pathMsg->poses[0].pose.position.y; _waypointsDist = sqrt(dx*dx + dy*dy); _downSampling = int(_pathLength/10.0/_waypointsDist); } // Cut and downsampling the path for(int i =0; i< pathMsg->poses.size(); i++) { if(total_length > _pathLength) break; if(sampling == _downSampling) { geometry_msgs::PoseStamped tempPose; _tf_listener.transformPose(_odom_frame, ros::Time(0) , pathMsg->poses[i], _map_frame, tempPose); odom_path.poses.push_back(tempPose); sampling = 0; } total_length = total_length + _waypointsDist; sampling = sampling + 1; } if(odom_path.poses.size() >= 6 ) { _odom_path = odom_path; // Path waypoints in odom frame _path_computed = true; // publish odom path odom_path.header.frame_id = _odom_frame; odom_path.header.stamp = ros::Time::now(); _pub_odompath.publish(odom_path); } else { cout << "Failed to path generation" << endl; _waypointsDist = -1; } //DEBUG //cout << endl << "N: " << odom_path.poses.size() << endl //<< "Car path[0]: " << odom_path.poses[0]; // << ", path[N]: " << _odom_path.poses[_odom_path.poses.size()-1] << endl; } catch(tf::TransformException &ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); } } } // CallBack: Update goal status void MPCNode::goalCB(const geometry_msgs::PoseStamped::ConstPtr& goalMsg) { _goal_pos = goalMsg->pose.position; _goal_received = true; _goal_reached = false; ROS_INFO("Goal Received :goalCB!"); } // Callback: Check if the car is inside the goal area or not void MPCNode::amclCB(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& amclMsg) { if(_goal_received) { double car2goal_x = _goal_pos.x - amclMsg->pose.pose.position.x; double car2goal_y = _goal_pos.y - amclMsg->pose.pose.position.y; double dist2goal = sqrt(car2goal_x*car2goal_x + car2goal_y*car2goal_y); if(dist2goal < _goalRadius) { _goal_received = false; _goal_reached = true; _path_computed = false; ROS_INFO("Goal Reached !"); } } } // Timer: Control Loop (closed loop nonlinear MPC) void MPCNode::controlLoopCB(const ros::TimerEvent&) { if(_goal_received && !_goal_reached && _path_computed ) //received goal & goal not reached { nav_msgs::Odometry odom = _odom; nav_msgs::Path odom_path = _odom_path; // Update system states: X=[x, y, theta, v] const double px = odom.pose.pose.position.x; //pose: odom frame const double py = odom.pose.pose.position.y; tf::Pose pose; tf::poseMsgToTF(odom.pose.pose, pose); const double theta = tf::getYaw(pose.getRotation()); const double v = odom.twist.twist.linear.x; //twist: body fixed frame // Update system inputs: U=[w, throttle] const double w = _w; // steering -> w //const double steering = _steering; // radian const double throttle = _throttle; // accel: >0; brake: <0 const double dt = _dt; //const double Lf = _Lf; // Waypoints related parameters const int N = odom_path.poses.size(); // Number of waypoints const double costheta = cos(theta); const double sintheta = sin(theta); // Convert to the vehicle coordinate system VectorXd x_veh(N); VectorXd y_veh(N); for(int i = 0; i < N; i++) { const double dx = odom_path.poses[i].pose.position.x - px; const double dy = odom_path.poses[i].pose.position.y - py; x_veh[i] = dx * costheta + dy * sintheta; y_veh[i] = dy * costheta - dx * sintheta; } // Fit waypoints auto coeffs = polyfit(x_veh, y_veh, 3); const double cte = polyeval(coeffs, 0.0); const double etheta = atan(coeffs[1]); VectorXd state(6); if(_delay_mode) { // Kinematic model is used to predict vehicle state at the actual moment of control (current time + delay dt) const double px_act = v * dt; const double py_act = 0; const double theta_act = w * dt; //(steering) theta_act = v * steering * dt / Lf; const double v_act = v + throttle * dt; //v = v + a * dt const double cte_act = cte + v * sin(etheta) * dt; const double etheta_act = etheta - theta_act; state << px_act, py_act, theta_act, v_act, cte_act, etheta_act; } else { state << 0, 0, 0, v, cte, etheta; } // Solve MPC Problem vector<double> mpc_results = _mpc.Solve(state, coeffs); // MPC result (all described in car frame), output = (acceleration, w) _w = mpc_results[0]; // radian/sec, angular velocity _throttle = mpc_results[1]; // acceleration _speed = v + _throttle*dt; // speed if (_speed >= _max_speed) _speed = _max_speed; if(_speed <= 0.0) _speed = 0.0; if(_debug_info) { cout << "\n\nDEBUG" << endl; cout << "theta: " << theta << endl; cout << "V: " << v << endl; //cout << "odom_path: \n" << odom_path << endl; //cout << "x_points: \n" << x_veh << endl; //cout << "y_points: \n" << y_veh << endl; cout << "coeffs: \n" << coeffs << endl; cout << "_w: \n" << _w << endl; cout << "_throttle: \n" << _throttle << endl; cout << "_speed: \n" << _speed << endl; } // Display the MPC predicted trajectory _mpc_traj = nav_msgs::Path(); _mpc_traj.header.frame_id = _car_frame; // points in car coordinate _mpc_traj.header.stamp = ros::Time::now(); for(int i=0; i<_mpc.mpc_x.size(); i++) { geometry_msgs::PoseStamped tempPose; tempPose.header = _mpc_traj.header; tempPose.pose.position.x = _mpc.mpc_x[i]; tempPose.pose.position.y = _mpc.mpc_y[i]; tempPose.pose.orientation.w = 1.0; _mpc_traj.poses.push_back(tempPose); } // publish the mpc trajectory _pub_mpctraj.publish(_mpc_traj); } else { _throttle = 0.0; _speed = 0.0; _w = 0; if(_goal_reached && _goal_received) cout << "Goal Reached: control loop !" << endl; } // publish ankermann cmd_vel /* _ackermann_msg.header.frame_id = _car_frame; _ackermann_msg.header.stamp = ros::Time::now(); _ackermann_msg.drive.steering_angle = _steering; _ackermann_msg.drive.speed = _speed; _ackermann_msg.drive.acceleration = _throttle; _pub_ackermann.publish(_ackermann_msg); */ // publish general cmd_vel if(_pub_twist_flag) { _twist_msg.linear.x = _speed; _twist_msg.angular.z = _w; _pub_twist.publish(_twist_msg); } } /*****************/ /* MAIN FUNCTION */ /*****************/ int main(int argc, char **argv) { //Initiate ROS ros::init(argc, argv, "MPC_Node"); MPCNode mpc_node; ROS_INFO("Waiting for global path msgs ~"); ros::AsyncSpinner spinner(mpc_node.get_thread_numbers()); // Use multi threads spinner.start(); ros::waitForShutdown(); return 0; }
mdavic0/algo3tp2
src/main/java/edu/fiuba/algo3/modelo/policia/rangos/Sargento.java
<reponame>mdavic0/algo3tp2 package edu.fiuba.algo3.modelo.policia.rangos; import java.util.SplittableRandom; import edu.fiuba.algo3.modelo.dificultad.Dificil; import edu.fiuba.algo3.modelo.robo.artefacto.valor.MuyValioso; import edu.fiuba.algo3.modelo.robo.artefacto.valor.Valioso; import edu.fiuba.algo3.modelo.robo.artefacto.valor.Valor; public class Sargento extends Rango { static int VELOCIDAD = 1500; static int PROBABILIDAD = 90; public Sargento(){ this.velocidadKmh = VELOCIDAD; this.IDificultad = new Dificil(); } @Override public Rango subirRango(int cantidadDeArrestos) { return this; } @Override public Valor generarValorDeArtefacto() { SplittableRandom aleatorio = new SplittableRandom(); if(aleatorio.nextInt(1, 101) <= PROBABILIDAD) //probabilidad 90% de que genere un valor MuyValioso return new MuyValioso(); return new Valioso(); // ==> 10% de que genere un valor Valioso } }
pierre42100/ComunicAndroid
app/src/main/java/org/communiquons/android/comunic/client/ui/listeners/OnOpenPageListener.java
package org.communiquons.android.comunic.client.ui.listeners; /** * Implement this interface on activities that can open group and user pages * * @author <NAME> */ public interface OnOpenPageListener extends OnOpenGroupListener, onOpenUsersPageListener { }
bidhata/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/unittest/__main__.py
<reponame>bidhata/EquationGroupLeaks<filename>Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/unittest/__main__.py # uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: __main__.py """Main entry point""" import sys if sys.argv[0].endswith('__main__.py'): sys.argv[0] = 'python -m unittest' __unittest = True from .main import main, TestProgram, USAGE_AS_MAIN TestProgram.USAGE = USAGE_AS_MAIN main(module=None)
zhuxiaod/ZZT
ZiZaiTianProject/ZiZaiTianProject/classes/Other/Tools/NetWorkManager.h
<reponame>zhuxiaod/ZZT // // NetWorkTool.h // kuaikanCartoon // // Created by dengchen on 16/5/2. // Copyright © 2016年 name. All rights reserved. // #import <AFNetworking.h> /*网络相关 {result:ok, data:data} {result:error,message:""} {result:invalidatetoken, message:"token失效"} */ static NSString * const NetCode = @"code"; static NSString * const NetOk = @"OK"; static NSString * const NetData = @"data"; static NSString * const NetMessage = @"message"; static NSString * const HTTPSchema = @"http:"; static NSString * const HTTPGET = @"GET"; static NSString * const HTTPPOST = @"POST"; static NSString * const HTTPDELETE = @"DELETE"; @interface NetWorkManager : AFHTTPSessionManager @property (nonatomic,readonly) BOOL hasNetWork; + (instancetype)share; - (NSURLSessionDataTask *)requestWithMethod:(NSString *)method url:(NSString *)url parameters:(id)parameters complish:(void (^)(id res,NSError *error))complish; @end
Gavinzx/edu
roncoo-education-system/roncoo-education-system-service/src/main/java/com/roncoo/education/system/feign/biz/FeignMsgTemplateBiz.java
package com.roncoo.education.system.feign.biz; import com.roncoo.education.common.core.base.Page; import com.roncoo.education.common.core.base.PageUtil; import com.roncoo.education.common.core.tools.BeanUtil; import com.roncoo.education.system.dao.MsgTemplateDao; import com.roncoo.education.system.dao.impl.mapper.entity.MsgTemplate; import com.roncoo.education.system.dao.impl.mapper.entity.MsgTemplateExample; import com.roncoo.education.system.feign.interfaces.qo.MsgTemplateQO; import com.roncoo.education.system.feign.interfaces.vo.MsgTemplateVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 消息模板 * * @author wuyun */ @Component public class FeignMsgTemplateBiz { @Autowired private MsgTemplateDao dao; public Page<MsgTemplateVO> listForPage(MsgTemplateQO qo) { MsgTemplateExample example = new MsgTemplateExample(); example.setOrderByClause(" status_id desc, sort desc, id desc "); Page<MsgTemplate> page = dao.listForPage(qo.getPageCurrent(), qo.getPageSize(), example); return PageUtil.transform(page, MsgTemplateVO.class); } public int save(MsgTemplateQO qo) { MsgTemplate record = BeanUtil.copyProperties(qo, MsgTemplate.class); return dao.save(record); } public int deleteById(Long id) { return dao.deleteById(id); } public MsgTemplateVO getById(Long id) { MsgTemplate record = dao.getById(id); return BeanUtil.copyProperties(record, MsgTemplateVO.class); } public int updateById(MsgTemplateQO qo) { MsgTemplate record = BeanUtil.copyProperties(qo, MsgTemplate.class); return dao.updateById(record); } }
Doom306/plenary-bot
Pro/ProData.java
<reponame>Doom306/plenary-bot<filename>Pro/ProData.java package com.general_hello.commands.commands.Pro; import net.dv8tion.jda.api.entities.User; import java.util.HashMap; public class ProData { public static HashMap<User, Boolean> isPro = new HashMap<>(); }
leonardoraele/pgm-editor
PGMEditor/src/aac/gui/AlgorithmSelector.java
<filename>PGMEditor/src/aac/gui/AlgorithmSelector.java package aac.gui; import javax.swing.JComponent; import aac.PGM; public interface AlgorithmSelector<T> { public default void initialize(PGM image) {}; public JComponent getComponent(); public T getAlgorithm(); public String getName(); }
bjadamson/BoomHS
include/boomhs/camera.hpp
<reponame>bjadamson/BoomHS<gh_stars>1-10 #pragma once #include <boomhs/frame.hpp> #include <boomhs/mouse.hpp> #include <boomhs/spherical.hpp> #include <boomhs/world_object.hpp> #include <boomhs/math.hpp> #include <common/log.hpp> #include <common/type_macros.hpp> // TODO #include <iostream> namespace gl_sdl { class SDLWindow; } // namespace gl_sdl namespace boomhs { class FrameTime; struct ScreenSize; class Viewport; class AspectRatio { std::array<float, 2> nd_; public: explicit constexpr AspectRatio(float const np, float const dp) : nd_({np, dp}) { } float constexpr compute() const { return nd_[0] / nd_[1]; } float* data() { return nd_.data(); } float const* data() const { return nd_.data(); } }; struct ViewSettings { AspectRatio aspect_ratio; float field_of_view; }; class CameraTarget { WorldObject* wo_; // methods void validate() const; friend class Camera; public: CameraTarget() = default; WorldObject& get() { validate(); return *wo_; } WorldObject const& get() const { validate(); return *wo_; } void set(WorldObject& wo) { wo_ = &wo; } }; struct CameraState { DeviceSensitivity sensitivity; bool rotation_lock; bool flip_y = false; bool flip_x = false; }; #define CAMERA_TARGET_BODY_IMPL assert(target_); return *target_; #define CAMERA_CLASS_TARGET_IMPL \ auto& target() { CAMERA_TARGET_BODY_IMPL } \ auto const& target() const { CAMERA_TARGET_BODY_IMPL } using CameraPosition = glm::vec3; using CameraCenter = glm::vec3; using CameraForward = glm::vec3; using CameraUp = glm::vec3; /* * Explicit copy method. * * Rationale: It is easy to accidentally take a reference to a copy of an instance of this class. * To make it more unlikely, force the user to call clone(). */ #define CLONE_CAMERA_IMPL \ auto clone() const { return *this; } class CameraFPS { float xrot_, yrot_; WorldOrientation orientation_; CameraTarget* target_; CAMERA_CLASS_TARGET_IMPL auto& transform() { return target().get().transform(); } auto const& transform() const { return target().get().transform(); } auto eye_forward() const { return orientation_.forward * transform().rotation; } auto const& eye_up() const { return orientation_.up; } friend class Camera; COPY_DEFAULT(CameraFPS); public: CameraFPS(WorldOrientation const&); MOVE_DEFAULT(CameraFPS); // fields CameraState cs; // methods CameraFPS& rotate_radians(float, float, FrameTime const&); glm::vec3 position() const; CameraMatrices calc_cm(ViewSettings const&, Frustum const&, glm::vec3 const&) const; CLONE_CAMERA_IMPL }; class CameraORTHO { WorldOrientation orientation_; glm::vec2 zoom_; void zoom(glm::vec2 const&, FrameTime const&); COPY_DEFAULT(CameraORTHO); friend class Camera; public: CameraORTHO(WorldOrientation const&, glm::vec3 const&); MOVE_DEFAULT(CameraORTHO); // fields glm::vec3 position; bool flip_rightv = false; // methods CameraMatrices calc_cm(Frustum const&, ScreenSize const&) const; auto const& eye_forward() const { return orientation_.forward; } auto const& eye_up() const { return orientation_.up; } void zoom_in(glm::vec2 const&, FrameTime const&); void zoom_out(glm::vec2 const&, FrameTime const&); void scroll(glm::vec2 const&); auto const& zoom() const { return zoom_; } // Compute the projection-matrix. static glm::mat4 compute_pm(Frustum const&, ScreenSize const&, CameraPosition const&, glm::ivec2 const&); // Compute the view-matrix. static glm::mat4 compute_vm(CameraPosition const&, CameraCenter const&, CameraUp const&, bool); }; class CameraArcball { CameraTarget* target_; SphericalCoordinates coordinates_; bool up_inverted_; glm::vec3 world_up_; // methods void zoom(float, FrameTime const&); glm::vec3 local_position() const; auto eye_forward() const { return glm::normalize(position() - target_position()); } auto eye_up() const { return up_inverted_ ? -world_up_ : world_up_; } CAMERA_CLASS_TARGET_IMPL #undef CAMERA_CLASS_TARGET_IMPL #undef CAMERA_TARGET_BODY_IMPL friend class Camera; COPY_DEFAULT(CameraArcball); public: CameraArcball(glm::vec3 const&); MOVE_DEFAULT(CameraArcball); // fields CameraState cs; // methods SphericalCoordinates spherical_coordinates() const { return coordinates_; } void set_coordinates(SphericalCoordinates const& sc) { coordinates_ = sc; } void zoom_out(float, FrameTime const&); void zoom_in(float, FrameTime const&); CameraArcball& rotate_radians(float, float, FrameTime const&); glm::vec3 position() const; glm::vec3 target_position() const; CameraMatrices calc_cm(ViewSettings const&, Frustum const&, glm::vec3 const&) const; CLONE_CAMERA_IMPL }; class Camera { CameraTarget target_; ViewSettings view_settings_; CameraMode mode_; COPY_DEFAULT(Camera); public: MOVE_DEFAULT(Camera); Camera(CameraMode, ViewSettings&&, CameraArcball&&, CameraFPS&&, CameraORTHO&&); // public fields CameraArcball arcball; CameraFPS fps; CameraORTHO ortho; WorldObject& get_target(); WorldObject const& get_target() const; auto mode() const { return mode_; } void set_mode(CameraMode); void next_mode(); bool is_firstperson() const { return CameraMode::FPS == mode(); } bool is_thirdperson() const { return CameraMode::ThirdPerson == mode(); } void toggle_rotation_lock(); glm::vec3 eye_forward() const; glm::vec3 eye_backward() const { return -eye_forward(); } glm::vec3 eye_up() const; glm::vec3 eye_left() const { return -eye_right(); } glm::vec3 eye_right() const { return glm::normalize(glm::cross(eye_forward(), eye_up())); } glm::vec3 position() const; auto const& view_settings_ref() const { return view_settings_; } auto& view_settings_ref() { return view_settings_; } Camera& rotate_radians(float, float, FrameTime const&); void set_target(WorldObject&); CameraMatrices calc_cm(ViewSettings const&, Frustum const&, ScreenSize const&, glm::vec3 const&) const; void zoom_out(float, FrameTime const&); void zoom_in(float, FrameTime const&); CLONE_CAMERA_IMPL // static fns static Camera make_default(CameraMode, WorldOrientation const&, WorldOrientation const&); }; #undef CLONE_CAMERA_IMPL } // namespace boomhs
kostergroup/Excimontec
docs/search/classes_3.js
<gh_stars>10-100 var searchData= [ ['hop',['Hop',['../class_excimontec_1_1_exciton_1_1_hop.html',1,'Excimontec::Exciton::Hop'],['../class_excimontec_1_1_polaron_1_1_hop.html',1,'Excimontec::Polaron::Hop']]] ];
haroldl/rest.li
r2-core/src/main/java/com/linkedin/r2/util/ServerRetryTracker.java
/* Copyright (c) 2020 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.linkedin.r2.util; import com.linkedin.util.clock.Clock; import java.util.LinkedList; import org.checkerframework.checker.lock.qual.GuardedBy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Stores the number of requests categorized by number of retry attempts. It uses the information to estimate * a ratio of how many requests are being retried in the cluster. The ratio is then compared with * {@link ServerRetryTracker#_maxRequestRetryRatio} to make a decision on whether or not to retry in the * next interval. When calculating the ratio, it looks at the last {@link ServerRetryTracker#_aggregatedIntervalNum} * intervals by aggregating the recorded requests. */ public class ServerRetryTracker { private static final Logger LOG = LoggerFactory.getLogger(ServerRetryTracker.class); private final int _retryLimit; private final int _aggregatedIntervalNum; private final double _maxRequestRetryRatio; private final long _updateIntervalMs; private final Clock _clock; private final Object _counterLock = new Object(); private final Object _updateLock = new Object(); @GuardedBy("_updateLock") private volatile long _lastRollOverTime; private boolean _isBelowRetryRatio; @GuardedBy("_counterLock") private final LinkedList<int[]> _retryAttemptsCounter; private final int[] _aggregatedRetryAttemptsCounter; public ServerRetryTracker(int retryLimit, int aggregatedIntervalNum, double maxRequestRetryRatio, long updateIntervalMs, Clock clock) { _retryLimit = retryLimit; _aggregatedIntervalNum = aggregatedIntervalNum; _maxRequestRetryRatio = maxRequestRetryRatio; _updateIntervalMs = updateIntervalMs; _clock = clock; _lastRollOverTime = clock.currentTimeMillis(); _isBelowRetryRatio = true; _aggregatedRetryAttemptsCounter = new int[_retryLimit + 1]; _retryAttemptsCounter = new LinkedList<>(); _retryAttemptsCounter.add(new int[_retryLimit + 1]); } public void add(int numberOfRetryAttempts) { if (numberOfRetryAttempts > _retryLimit) { LOG.warn("Unexpected number of retry attempts: " + numberOfRetryAttempts + ", current retry limit: " + _retryLimit); numberOfRetryAttempts = _retryLimit; } synchronized (_counterLock) { _retryAttemptsCounter.getLast()[numberOfRetryAttempts] += 1; } updateRetryDecision(); } public boolean isBelowRetryRatio() { return _isBelowRetryRatio; } private void rollOverStats() { // rollover the current interval to the aggregated counter synchronized (_counterLock) { int[] intervalToAggregate = _retryAttemptsCounter.getLast(); for (int i = 0; i <= _retryLimit; i++) { _aggregatedRetryAttemptsCounter[i] += intervalToAggregate[i]; } if (_retryAttemptsCounter.size() > _aggregatedIntervalNum) { // discard the oldest interval int[] intervalToDiscard = _retryAttemptsCounter.removeFirst(); for (int i = 0; i <= _retryLimit; i++) { _aggregatedRetryAttemptsCounter[i] -= intervalToDiscard[i]; } } // append a new interval _retryAttemptsCounter.addLast(new int[_retryLimit + 1]); } } void updateRetryDecision() { long currentTime = _clock.currentTimeMillis(); synchronized (_updateLock) { // Check if the current interval is stale if (currentTime >= _lastRollOverTime + _updateIntervalMs) { // Rollover stale intervals until the current interval is reached for (long time = currentTime; time >= _lastRollOverTime + _updateIntervalMs; time -= _updateIntervalMs) { rollOverStats(); } _isBelowRetryRatio = getRetryRatio() <= _maxRequestRetryRatio; _lastRollOverTime = currentTime; } } } double getRetryRatio() { double retryRatioSum = 0.0; int i; for (i = 1; i <= _retryLimit; i++) { if (_aggregatedRetryAttemptsCounter[i] == 0 || _aggregatedRetryAttemptsCounter[i - 1] == 0) { break; } double ratio = (double) _aggregatedRetryAttemptsCounter[i] / _aggregatedRetryAttemptsCounter[i - 1]; // We put more weights to the retry requests with larger number of attempts double adjustedRatio = Double.min(ratio * i, 1.0); retryRatioSum += adjustedRatio; } return i > 1 ? retryRatioSum / (i - 1) : 0.0; } }
unimauro/eden
languages/en-gb.py
# coding: utf8 { ' Assessment Series Details': ' Assessment Series Details', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '# of International Staff': '# of International Staff', '# of National Staff': '# of National Staff', '# of Vehicles': '# of Vehicles', '%(module)s not installed': '%(module)s not installed', '%(system_name)s - Verify Email': '%(system_name)s - Verify Email', '%.1f km': '%.1f km', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s rows deleted', '%s rows updated': '%s rows updated', '& then click on the map below to adjust the Lat/Lon fields': '& then click on the map below to adjust the Lat/Lon fields', "'Cancel' will indicate an asset log entry did not occur": "'Cancel' will indicate an asset log entry did not occur", '* Required Fields': '* Required Fields', '0-15 minutes': '0-15 minutes', '1 Assessment': '1 Assessment', '1 location, shorter time, can contain multiple Tasks': '1 location, shorter time, can contain multiple Tasks', '1-3 days': '1-3 days', '15-30 minutes': '15-30 minutes', '2 different options are provided here currently:': '2 different options are provided here currently:', '2x4 Car': '2x4 Car', '30-60 minutes': '30-60 minutes', '4-7 days': '4-7 days', '4x4 Car': '4x4 Car', '8-14 days': '8-14 days', 'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.': 'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.', 'A Reference Document such as a file, URL or contact person to verify this data.': 'A Reference Document such as a file, URL or contact person to verify this data.', 'A brief description of the group (optional)': 'A brief description of the group (optional)', 'A catalog of different Assessment Templates including summary information': 'A catalogue of different Assessment Templates including summary information', 'A file in GPX format taken from a GPS.': 'A file in GPX format taken from a GPS.', 'A library of digital resources, such as photos, documents and reports': 'A library of digital resources, such as photos, documents and reports', 'A location group can be used to define the extent of an affected area, if it does not fall within one administrative region.': 'A location group can be used to define the extent of an affected area, if it does not fall within one administrative region.', 'A location group is a set of locations (often, a set of administrative regions representing a combined area).': 'A location group is a set of locations (often, a set of administrative regions representing a combined area).', 'A location group must have at least one member.': 'A location group must have at least one member.', "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.", 'A portal for volunteers allowing them to amend their own data & view assigned tasks.': 'A portal for volunteers allowing them to amend their own data & view assigned tasks.', 'A task is a piece of work that an individual or team can do in 1-2 days': 'A task is a piece of work that an individual or team can do in 1-2 days', 'ABOUT THIS MODULE': 'ABOUT THIS MODULE', 'ACCESS DATA': 'ACCESS DATA', 'ANY': 'ANY', 'API Key': 'API Key', 'API is documented here': 'API is documented here', 'ATC-20 Rapid Evaluation modified for New Zealand': 'ATC-20 Rapid Evaluation modified for New Zealand', 'Abbreviation': 'Abbreviation', 'Ability to customize the list of details tracked at a Shelter': 'Ability to customize the list of details tracked at a Shelter', 'Ability to customize the list of human resource tracked at a Shelter': 'Ability to customize the list of human resource tracked at a Shelter', 'Ability to customize the list of important facilities needed at a Shelter': 'Ability to customize the list of important facilities needed at a Shelter', 'About': 'About', 'Accept Push': 'Accept Push', 'Accept Pushes': 'Accept Pushes', 'Access denied': 'Access denied', 'Access to Shelter': 'Access to Shelter', 'Access to education services': 'Access to education services', 'Accessibility of Affected Location': 'Accessibility of Affected Location', 'Accompanying Relative': 'Accompanying Relative', 'Account Registered - Please Check Your Email': 'Account Registered - Please Check Your Email', 'Acronym': 'Acronym', "Acronym of the organization's name, eg. IFRC.": "Acronym of the organisation's name, eg. IFRC.", 'Actionable by all targeted recipients': 'Actionable by all targeted recipients', 'Actionable only by designated exercise participants; exercise identifier SHOULD appear in <note>': 'Actionable only by designated exercise participants; exercise identifier SHOULD appear in <note>', 'Actioned?': 'Actioned?', 'Actions': 'Actions', 'Actions taken as a result of this request.': 'Actions taken as a result of this request.', 'Activate Events from Scenario templates for allocation of appropriate Resources (Human, Assets & Facilities).': 'Activate Events from Scenario templates for allocation of appropriate Resources (Human, Assets & Facilities).', 'Active': 'Active', 'Active Problems': 'Active Problems', 'Activities': 'Activities', 'Activities matching Assessments:': 'Activities matching Assessments:', 'Activities of boys 13-17yrs before disaster': 'Activities of boys 13-17yrs before disaster', 'Activities of boys 13-17yrs now': 'Activities of boys 13-17yrs now', 'Activities of boys <12yrs before disaster': 'Activities of boys <12yrs before disaster', 'Activities of boys <12yrs now': 'Activities of boys <12yrs now', 'Activities of children': 'Activities of children', 'Activities of girls 13-17yrs before disaster': 'Activities of girls 13-17yrs before disaster', 'Activities of girls 13-17yrs now': 'Activities of girls 13-17yrs now', 'Activities of girls <12yrs before disaster': 'Activities of girls <12yrs before disaster', 'Activities of girls <12yrs now': 'Activities of girls <12yrs now', 'Activities:': 'Activities:', 'Activity': 'Activity', 'Activity Added': 'Activity Added', 'Activity Deleted': 'Activity Deleted', 'Activity Details': 'Activity Details', 'Activity Report': 'Activity Report', 'Activity Reports': 'Activity Reports', 'Activity Type': 'Activity Type', 'Activity Types': 'Activity Types', 'Activity Updated': 'Activity Updated', 'Activity added': 'Activity added', 'Activity removed': 'Activity removed', 'Activity updated': 'Activity updated', 'Add': 'Add', 'Add Activity': 'Add Activity', 'Add Activity Report': 'Add Activity Report', 'Add Activity Type': 'Add Activity Type', 'Add Address': 'Add Address', 'Add Alternative Item': 'Add Alternative Item', 'Add Assessment': 'Add Assessment', 'Add Assessment Answer': 'Add Assessment Answer', 'Add Assessment Series': 'Add Assessment Series', 'Add Assessment Summary': 'Add Assessment Summary', 'Add Assessment Template': 'Add Assessment Template', 'Add Asset': 'Add Asset', 'Add Asset Log Entry - Change Label': 'Add Asset Log Entry - Change Label', 'Add Availability': 'Add Availability', 'Add Baseline': 'Add Baseline', 'Add Baseline Type': 'Add Baseline Type', 'Add Bed Type': 'Add Bed Type', 'Add Brand': 'Add Brand', 'Add Budget': 'Add Budget', 'Add Bundle': 'Add Bundle', 'Add Camp': 'Add Camp', 'Add Camp Service': 'Add Camp Service', 'Add Camp Type': 'Add Camp Type', 'Add Catalog': 'Add Catalogue', 'Add Catalog Item': 'Add Catalogue Item', 'Add Certificate': 'Add Certificate', 'Add Certification': 'Add Certification', 'Add Cholera Treatment Capability Information': 'Add Cholera Treatment Capability Information', 'Add Cluster': 'Add Cluster', 'Add Cluster Subsector': 'Add Cluster Subsector', 'Add Competency Rating': 'Add Competency Rating', 'Add Contact': 'Add Contact', 'Add Contact Information': 'Add Contact Information', 'Add Course': 'Add Course', 'Add Course Certificate': 'Add Course Certificate', 'Add Credential': 'Add Credential', 'Add Credentials': 'Add Credentials', 'Add Dead Body Report': 'Add Dead Body Report', 'Add Disaster Victims': 'Add Disaster Victims', 'Add Distribution.': 'Add Distribution.', 'Add Document': 'Add Document', 'Add Donor': 'Add Donor', 'Add Facility': 'Add Facility', 'Add Feature Class': 'Add Feature Class', 'Add Feature Layer': 'Add Feature Layer', 'Add Flood Report': 'Add Flood Report', 'Add GPS data': 'Add GPS data', 'Add Group': 'Add Group', 'Add Group Member': 'Add Group Member', 'Add Home Address': 'Add Home Address', 'Add Hospital': 'Add Hospital', 'Add Human Resource': 'Add Human Resource', 'Add Identification Report': 'Add Identification Report', 'Add Identity': 'Add Identity', 'Add Image': 'Add Image', 'Add Impact': 'Add Impact', 'Add Impact Type': 'Add Impact Type', 'Add Incident': 'Add Incident', 'Add Incident Report': 'Add Incident Report', 'Add Item': 'Add Item', 'Add Item Category': 'Add Item Category', 'Add Item Pack': 'Add Item Pack', 'Add Item to Catalog': 'Add Item to Catalogue', 'Add Item to Commitment': 'Add Item to Commitment', 'Add Item to Inventory': 'Add Item to Inventory', 'Add Item to Order': 'Add Item to Order', 'Add Item to Request': 'Add Item to Request', 'Add Item to Shipment': 'Add Item to Shipment', 'Add Job': 'Add Job', 'Add Job Role': 'Add Job Role', 'Add Kit': 'Add Kit', 'Add Layer': 'Add Layer', 'Add Level 1 Assessment': 'Add Level 1 Assessment', 'Add Level 2 Assessment': 'Add Level 2 Assessment', 'Add Location': 'Add Location', 'Add Log Entry': 'Add Log Entry', 'Add Map Configuration': 'Add Map Configuration', 'Add Marker': 'Add Marker', 'Add Member': 'Add Member', 'Add Membership': 'Add Membership', 'Add Message': 'Add Message', 'Add Mission': 'Add Mission', 'Add Need': 'Add Need', 'Add Need Type': 'Add Need Type', 'Add New': 'Add New', 'Add New Activity': 'Add New Activity', 'Add New Activity Type': 'Add New Activity Type', 'Add New Address': 'Add New Address', 'Add New Alternative Item': 'Add New Alternative Item', 'Add New Assessment': 'Add New Assessment', 'Add New Assessment Summary': 'Add New Assessment Summary', 'Add New Asset': 'Add New Asset', 'Add New Baseline': 'Add New Baseline', 'Add New Baseline Type': 'Add New Baseline Type', 'Add New Brand': 'Add New Brand', 'Add New Budget': 'Add New Budget', 'Add New Bundle': 'Add New Bundle', 'Add New Camp': 'Add New Camp', 'Add New Camp Service': 'Add New Camp Service', 'Add New Camp Type': 'Add New Camp Type', 'Add New Catalog': 'Add New Catalogue', 'Add New Cluster': 'Add New Cluster', 'Add New Cluster Subsector': 'Add New Cluster Subsector', 'Add New Commitment Item': 'Add New Commitment Item', 'Add New Contact': 'Add New Contact', 'Add New Credential': 'Add New Credential', 'Add New Document': 'Add New Document', 'Add New Donor': 'Add New Donor', 'Add New Entry': 'Add New Entry', 'Add New Event': 'Add New Event', 'Add New Facility': 'Add New Facility', 'Add New Feature Class': 'Add New Feature Class', 'Add New Feature Layer': 'Add New Feature Layer', 'Add New Flood Report': 'Add New Flood Report', 'Add New Group': 'Add New Group', 'Add New Home': 'Add New Home', 'Add New Hospital': 'Add New Hospital', 'Add New Human Resource': 'Add New Human Resource', 'Add New Identity': 'Add New Identity', 'Add New Image': 'Add New Image', 'Add New Impact': 'Add New Impact', 'Add New Impact Type': 'Add New Impact Type', 'Add New Incident': 'Add New Incident', 'Add New Incident Report': 'Add New Incident Report', 'Add New Item': 'Add New Item', 'Add New Item Category': 'Add New Item Category', 'Add New Item Pack': 'Add New Item Pack', 'Add New Item to Kit': 'Add New Item to Kit', 'Add New Item to Order': 'Add New Item to Order', 'Add New Kit': 'Add New Kit', 'Add New Layer': 'Add New Layer', 'Add New Level 1 Assessment': 'Add New Level 1 Assessment', 'Add New Level 2 Assessment': 'Add New Level 2 Assessment', 'Add New Location': 'Add New Location', 'Add New Log Entry': 'Add New Log Entry', 'Add New Map Configuration': 'Add New Map Configuration', 'Add New Marker': 'Add New Marker', 'Add New Member': 'Add New Member', 'Add New Membership': 'Add New Membership', 'Add New Need': 'Add New Need', 'Add New Need Type': 'Add New Need Type', 'Add New Office': 'Add New Office', 'Add New Order': 'Add New Order', 'Add New Organization': 'Add New Organisation', 'Add New Organization Domain': 'Add New Organisation Domain', 'Add New Patient': 'Add New Patient', 'Add New Person to Commitment': 'Add New Person to Commitment', 'Add New Photo': 'Add New Photo', 'Add New Population Statistic': 'Add New Population Statistic', 'Add New Problem': 'Add New Problem', 'Add New Project': 'Add New Project', 'Add New Project Site': 'Add New Project Site', 'Add New Projection': 'Add New Projection', 'Add New Rapid Assessment': 'Add New Rapid Assessment', 'Add New Received Item': 'Add New Received Item', 'Add New Record': 'Add New Record', 'Add New Relative': 'Add New Relative', 'Add New Report': 'Add New Report', 'Add New Request': 'Add New Request', 'Add New Request Item': 'Add New Request Item', 'Add New Resource': 'Add New Resource', 'Add New River': 'Add New River', 'Add New Role': 'Add New Role', 'Add New Role to User': 'Add New Role to User', 'Add New Room': 'Add New Room', 'Add New Scenario': 'Add New Scenario', 'Add New Sector': 'Add New Sector', 'Add New Sent Item': 'Add New Sent Item', 'Add New Setting': 'Add New Setting', 'Add New Shelter': 'Add New Shelter', 'Add New Shelter Service': 'Add New Shelter Service', 'Add New Shelter Type': 'Add New Shelter Type', 'Add New Skill': 'Add New Skill', 'Add New Solution': 'Add New Solution', 'Add New Staff Member': 'Add New Staff Member', 'Add New Staff Type': 'Add New Staff Type', 'Add New Subsector': 'Add New Subsector', 'Add New Task': 'Add New Task', 'Add New Team': 'Add New Team', 'Add New Theme': 'Add New Theme', 'Add New Ticket': 'Add New Ticket', 'Add New User': 'Add New User', 'Add New User to Role': 'Add New User to Role', 'Add New Vehicle': 'Add New Vehicle', 'Add New Volunteer': 'Add New Volunteer', 'Add New Warehouse': 'Add New Warehouse', 'Add Office': 'Add Office', 'Add Order': 'Add Order', 'Add Organization': 'Add Organisation', 'Add Organization Domain': 'Add Organisation Domain', 'Add Organization to Project': 'Add Organisation to Project', 'Add Person': 'Add Person', 'Add Person to Commitment': 'Add Person to Commitment', 'Add Personal Effects': 'Add Personal Effects', 'Add Photo': 'Add Photo', 'Add Point': 'Add Point', 'Add Polygon': 'Add Polygon', 'Add Population Statistic': 'Add Population Statistic', 'Add Position': 'Add Position', 'Add Problem': 'Add Problem', 'Add Project': 'Add Project', 'Add Project Site': 'Add Project Site', 'Add Projection': 'Add Projection', 'Add Question Meta-Data': 'Add Question Meta-Data', 'Add Rapid Assessment': 'Add Rapid Assessment', 'Add Record': 'Add Record', 'Add Reference Document': 'Add Reference Document', 'Add Report': 'Add Report', 'Add Repository': 'Add Repository', 'Add Request': 'Add Request', 'Add Resource': 'Add Resource', 'Add River': 'Add River', 'Add Role': 'Add Role', 'Add Room': 'Add Room', 'Add Saved Search': 'Add Saved Search', 'Add Section': 'Add Section', 'Add Sector': 'Add Sector', 'Add Service Profile': 'Add Service Profile', 'Add Setting': 'Add Setting', 'Add Shelter': 'Add Shelter', 'Add Shelter Service': 'Add Shelter Service', 'Add Shelter Type': 'Add Shelter Type', 'Add Skill': 'Add Skill', 'Add Skill Equivalence': 'Add Skill Equivalence', 'Add Skill Provision': 'Add Skill Provision', 'Add Skill Type': 'Add Skill Type', 'Add Skill to Request': 'Add Skill to Request', 'Add Solution': 'Add Solution', 'Add Staff Member': 'Add Staff Member', 'Add Staff Type': 'Add Staff Type', 'Add Status': 'Add Status', 'Add Subscription': 'Add Subscription', 'Add Subsector': 'Add Subsector', 'Add Task': 'Add Task', 'Add Team': 'Add Team', 'Add Template Section': 'Add Template Section', 'Add Theme': 'Add Theme', 'Add Ticket': 'Add Ticket', 'Add Training': 'Add Training', 'Add Unit': 'Add Unit', 'Add User': 'Add User', 'Add Vehicle': 'Add Vehicle', 'Add Vehicle Detail': 'Add Vehicle Detail', 'Add Vehicle Details': 'Add Vehicle Details', 'Add Volunteer': 'Add Volunteer', 'Add Volunteer Availability': 'Add Volunteer Availability', 'Add Warehouse': 'Add Warehouse', 'Add a Person': 'Add a Person', 'Add a Reference Document such as a file, URL or contact person to verify this data. If you do not enter a Reference Document, your email will be displayed instead.': 'Add a Reference Document such as a file, URL or contact person to verify this data. If you do not enter a Reference Document, your email will be displayed instead.', 'Add a new Assessment Answer': 'Add a new Assessment Answer', 'Add a new Assessment Question': 'Add a new Assessment Question', 'Add a new Assessment Series': 'Add a new Assessment Series', 'Add a new Assessment Template': 'Add a new Assessment Template', 'Add a new Completed Assessment': 'Add a new Completed Assessment', 'Add a new Template Section': 'Add a new Template Section', 'Add a new certificate to the catalog.': 'Add a new certificate to the catalogue.', 'Add a new competency rating to the catalog.': 'Add a new competency rating to the catalogue.', 'Add a new job role to the catalog.': 'Add a new job role to the catalogue.', 'Add a new skill provision to the catalog.': 'Add a new skill provision to the catalogue.', 'Add a new skill type to the catalog.': 'Add a new skill type to the catalogue.', 'Add all organizations which are involved in different roles in this project': 'Add all organisations which are involved in different roles in this project', 'Add an Assessment Question': 'Add an Assessment Question', 'Add new Group': 'Add new Group', 'Add new Individual': 'Add new Individual', 'Add new Patient': 'Add new Patient', 'Add new Question Meta-Data': 'Add new Question Meta-Data', 'Add new project.': 'Add new project.', 'Add staff members': 'Add staff members', 'Add to Bundle': 'Add to Bundle', 'Add to budget': 'Add to budget', 'Add volunteers': 'Add volunteers', 'Add/Edit/Remove Layers': 'Add/Edit/Remove Layers', 'Additional Beds / 24hrs': 'Additional Beds / 24hrs', 'Address': 'Address', 'Address Details': 'Address Details', 'Address Type': 'Address Type', 'Address added': 'Address added', 'Address deleted': 'Address deleted', 'Address updated': 'Address updated', 'Addresses': 'Addresses', 'Adequate': 'Adequate', 'Adequate food and water available': 'Adequate food and water available', 'Admin Email': 'Admin Email', 'Admin Name': '<NAME>', 'Admin Tel': 'Admin Tel', 'Administration': 'Administration', 'Admissions/24hrs': 'Admissions/24hrs', 'Adolescent (12-20)': 'Adolescent (12-20)', 'Adolescent participating in coping activities': 'Adolescent participating in coping activities', 'Adult (21-50)': 'Adult (21-50)', 'Adult ICU': 'Adult ICU', 'Adult Psychiatric': 'Adult Psychiatric', 'Adult female': 'Adult female', 'Adult male': 'Adult male', 'Adults in prisons': 'Adults in prisons', 'Advanced:': 'Advanced:', 'Advisory': 'Advisory', 'After clicking on the button, a set of paired items will be shown one by one. Please select the one solution from each pair that you prefer over the other.': 'After clicking on the button, a set of paired items will be shown one by one. Please select the one solution from each pair that you prefer over the other.', 'Age Group': 'Age Group', 'Age group': 'Age group', 'Age group does not match actual age.': 'Age group does not match actual age.', 'Aggravating factors': 'Aggravating factors', 'Agriculture': 'Agriculture', 'Air Transport Service': 'Air Transport Service', 'Air tajin': 'Air tajin', 'Aircraft Crash': 'Aircraft Crash', 'Aircraft Hijacking': 'Aircraft Hijacking', 'Airport Closure': 'Airport Closure', 'Airspace Closure': 'Airspace Closure', 'Alcohol': 'Alcohol', 'Alert': 'Alert', 'All': 'All', 'All Inbound & Outbound Messages are stored here': 'All Inbound & Outbound Messages are stored here', 'All Resources': 'All Resources', 'All data provided by the Sahana Software Foundation from this site is licensed under a Creative Commons Attribution license. However, not all data originates here. Please consult the source field of each entry.': 'All data provided by the Sahana Software Foundation from this site is licensed under a Creative Commons Attribution license. However, not all data originates here. Please consult the source field of each entry.', 'Allows a Budget to be drawn up': 'Allows a Budget to be drawn up', 'Alternative Item': 'Alternative Item', 'Alternative Item Details': 'Alternative Item Details', 'Alternative Item added': 'Alternative Item added', 'Alternative Item deleted': 'Alternative Item deleted', 'Alternative Item updated': 'Alternative Item updated', 'Alternative Items': 'Alternative Items', 'Alternative places for studying': 'Alternative places for studying', 'Ambulance Service': 'Ambulance Service', 'An Assessment Template can be selected to create an Event Assessment. Within an Event Assessment responses can be collected and results can analyzed as tables, charts and maps': 'An Assessment Template can be selected to create an Event Assessment. Within an Event Assessment responses can be collected and results can analysed as tables, charts and maps', 'An item which can be used in place of another item': 'An item which can be used in place of another item', 'Analysis': 'Analysis', 'Analysis of assessments': 'Analysis of assessments', 'Animal Die Off': 'Animal Die Off', 'Animal Feed': 'Animal Feed', 'Answer': 'Answer', 'Anthropolgy': 'Anthropolgy', 'Antibiotics available': 'Antibiotics available', 'Antibiotics needed per 24h': 'Antibiotics needed per 24h', 'Apparent Age': 'Apparent Age', 'Apparent Gender': 'Apparent Gender', 'Application Deadline': 'Application Deadline', 'Approve': 'Approve', 'Approved': 'Approved', 'Approved By': 'Approved By', 'Approver': 'Approver', 'Arabic': 'Arabic', 'Arctic Outflow': 'Arctic Outflow', 'Are you sure you want to delete this record?': 'Are you sure you want to delete this record?', 'Areas inspected': 'Areas inspected', 'As of yet, no completed surveys have been added to this series.': 'As of yet, no completed surveys have been added to this series.', 'As of yet, no sections have been added to this template.': 'As of yet, no sections have been added to this template.', 'Assessment': 'Assessment', 'Assessment Answer': 'Assessment Answer', 'Assessment Answer Details': 'Assessment Answer Details', 'Assessment Answer added': 'Assessment Answer added', 'Assessment Answer deleted': 'Assessment Answer deleted', 'Assessment Answer updated': 'Assessment Answer updated', 'Assessment Details': 'Assessment Details', 'Assessment Question Details': 'Assessment Question Details', 'Assessment Question added': 'Assessment Question added', 'Assessment Question deleted': 'Assessment Question deleted', 'Assessment Question updated': 'Assessment Question updated', 'Assessment Reported': 'Assessment Reported', 'Assessment Series': 'Assessment Series', 'Assessment Series added': 'Assessment Series added', 'Assessment Series deleted': 'Assessment Series deleted', 'Assessment Series updated': 'Assessment Series updated', 'Assessment Summaries': 'Assessment Summaries', 'Assessment Summary Details': 'Assessment Summary Details', 'Assessment Summary added': 'Assessment Summary added', 'Assessment Summary deleted': 'Assessment Summary deleted', 'Assessment Summary updated': 'Assessment Summary updated', 'Assessment Template Details': 'Assessment Template Details', 'Assessment Template added': 'Assessment Template added', 'Assessment Template deleted': 'Assessment Template deleted', 'Assessment Template updated': 'Assessment Template updated', 'Assessment Templates': 'Assessment Templates', 'Assessment added': 'Assessment added', 'Assessment admin level': 'Assessment admin level', 'Assessment deleted': 'Assessment deleted', 'Assessment timeline': 'Assessment timeline', 'Assessment updated': 'Assessment updated', 'Assessments': 'Assessments', 'Assessments Needs vs. Activities': 'Assessments Needs vs. Activities', 'Assessments and Activities': 'Assessments and Activities', 'Assessments:': 'Assessments:', 'Assessor': 'Assessor', 'Asset': 'Asset', 'Asset Details': 'Asset Details', 'Asset Log': 'Asset Log', 'Asset Log Details': 'Asset Log Details', 'Asset Log Empty': 'Asset Log Empty', 'Asset Log Entry Added - Change Label': 'Asset Log Entry Added - Change Label', 'Asset Log Entry deleted': 'Asset Log Entry deleted', 'Asset Log Entry updated': 'Asset Log Entry updated', 'Asset Management': 'Asset Management', 'Asset Number': 'Asset Number', 'Asset added': 'Asset added', 'Asset deleted': 'Asset deleted', 'Asset removed': 'Asset removed', 'Asset updated': 'Asset updated', 'Assets': 'Assets', 'Assets are resources which are not consumable but are expected back, so they need tracking.': 'Assets are resources which are not consumable but are expected back, so they need tracking.', 'Assign': 'Assign', 'Assign to Org.': 'Assign to Org.', 'Assign to Organization': 'Assign to Organisation', 'Assign to Person': 'Assign to Person', 'Assign to Site': 'Assign to Site', 'Assigned': 'Assigned', 'Assigned By': 'Assigned By', 'Assigned To': 'Assigned To', 'Assigned to Organization': 'Assigned to Organisation', 'Assigned to Person': 'Assigned to Person', 'Assigned to Site': 'Assigned to Site', 'Assignment': 'Assignment', 'Assignments': 'Assignments', 'At/Visited Location (not virtual)': 'At/Visited Location (not virtual)', 'Attend to information sources as described in <instruction>': 'Attend to information sources as described in <instruction>', 'Attribution': 'Attribution', "Authenticate system's Twitter account": "Authenticate system's Twitter account", 'Author': 'Author', 'Available Alternative Inventories': 'Available Alternative Inventories', 'Available Beds': 'Available Beds', 'Available Forms': 'Available Forms', 'Available Inventories': 'Available Inventories', 'Available Messages': 'Available Messages', 'Available Records': 'Available Records', 'Available databases and tables': 'Available databases and tables', 'Available for Location': 'Available for Location', 'Available from': 'Available from', 'Available in Viewer?': 'Available in Viewer?', 'Available until': 'Available until', 'Avalanche': 'Avalanche', 'Avoid the subject event as per the <instruction>': 'Avoid the subject event as per the <instruction>', 'Background Color': 'Background Colour', 'Background Color for Text blocks': 'Background Colour for Text blocks', 'Bahai': 'Bahai', 'Baldness': 'Baldness', 'Banana': 'Banana', 'Bank/micro finance': 'Bank/micro finance', 'Barricades are needed': 'Barricades are needed', 'Base Layer?': 'Base Layer?', 'Base Layers': 'Base Layers', 'Base Location': 'Base Location', 'Base Site Set': 'Base Site Set', 'Base URL of the remote Sahana-Eden site': 'Base URL of the remote Sahana-Eden site', 'Baseline Data': 'Baseline Data', 'Baseline Number of Beds': 'Baseline Number of Beds', 'Baseline Type': 'Baseline Type', 'Baseline Type Details': 'Baseline Type Details', 'Baseline Type added': 'Baseline Type added', 'Baseline Type deleted': 'Baseline Type deleted', 'Baseline Type updated': 'Baseline Type updated', 'Baseline Types': 'Baseline Types', 'Baseline added': 'Baseline added', 'Baseline deleted': 'Baseline deleted', 'Baseline number of beds of that type in this unit.': 'Baseline number of beds of that type in this unit.', 'Baseline updated': 'Baseline updated', 'Baselines': 'Baselines', 'Baselines Details': 'Baselines Details', 'Basic Assessment': 'Basic Assessment', 'Basic Assessment Reported': 'Basic Assessment Reported', 'Basic Details': 'Basic Details', 'Basic reports on the Shelter and drill-down by region': 'Basic reports on the Shelter and drill-down by region', 'Baud': 'Baud', 'Baud rate to use for your modem - The default is safe for most cases': 'Baud rate to use for your modem - The default is safe for most cases', 'Beam': 'Beam', 'Bed Capacity': 'Bed Capacity', 'Bed Capacity per Unit': 'Bed Capacity per Unit', 'Bed Type': 'Bed Type', 'Bed type already registered': 'Bed type already registered', 'Below ground level': 'Below ground level', 'Beneficiary Type': 'Beneficiary Type', "Bing Layers cannot be displayed if there isn't a valid API Key": "Bing Layers cannot be displayed if there isn't a valid API Key", 'Biological Hazard': 'Biological Hazard', 'Biscuits': 'Biscuits', 'Blizzard': 'Blizzard', 'Blood Type (AB0)': 'Blood Type (AB0)', 'Blowing Snow': 'Blowing Snow', 'Boat': 'Boat', 'Bodies': 'Bodies', 'Bodies found': 'Bodies found', 'Bodies recovered': 'Bodies recovered', 'Body': 'Body', 'Body Recovery': 'Body Recovery', 'Body Recovery Request': 'Body Recovery Request', 'Body Recovery Requests': 'Body Recovery Requests', 'Bomb': 'Bomb', 'Bomb Explosion': 'Bomb Explosion', 'Bomb Threat': 'Bomb Threat', 'Border Color for Text blocks': 'Border Colour for Text blocks', 'Brand': 'Brand', 'Brand Details': 'Brand Details', 'Brand added': 'Brand added', 'Brand deleted': 'Brand deleted', 'Brand updated': 'Brand updated', 'Brands': 'Brands', 'Bricks': 'Bricks', 'Bridge Closed': 'Bridge Closed', 'Bucket': 'Bucket', 'Buddhist': 'Buddhist', 'Budget': 'Budget', 'Budget Details': 'Budget Details', 'Budget Updated': 'Budget Updated', 'Budget added': 'Budget added', 'Budget deleted': 'Budget deleted', 'Budget updated': 'Budget updated', 'Budgeting Module': 'Budgeting Module', 'Budgets': 'Budgets', 'Buffer': 'Buffer', 'Bug': 'Bug', 'Building Assessments': 'Building Assessments', 'Building Collapsed': 'Building Collapsed', 'Building Name': 'Building Name', 'Building Safety Assessments': 'Building Safety Assessments', 'Building Short Name/Business Name': 'Building Short Name/Business Name', 'Building or storey leaning': 'Building or storey leaning', 'Built using the Template agreed by a group of NGOs working together as the': 'Built using the Template agreed by a group of NGOs working together as the', 'Bulk Uploader': 'Bulk Uploader', 'Bundle': 'Bundle', 'Bundle Contents': 'Bundle Contents', 'Bundle Details': 'Bundle Details', 'Bundle Updated': 'Bundle Updated', 'Bundle added': 'Bundle added', 'Bundle deleted': 'Bundle deleted', 'Bundle updated': 'Bundle updated', 'Bundles': 'Bundles', 'Burn': 'Burn', 'Burn ICU': 'Burn ICU', 'Burned/charred': 'Burned/charred', 'By Facility': 'By Facility', 'By Inventory': 'By Inventory', 'CBA Women': 'CBA Women', 'CLOSED': 'CLOSED', 'CN': 'CN', 'CSS file %s not writable - unable to apply theme!': 'CSS file %s not writable - unable to apply theme!', 'Calculate': 'Calculate', 'Camp': 'Camp', 'Camp Coordination/Management': 'Camp Coordination/Management', 'Camp Details': 'Camp Details', 'Camp Service': 'Camp Service', 'Camp Service Details': 'Camp Service Details', 'Camp Service added': 'Camp Service added', 'Camp Service deleted': 'Camp Service deleted', 'Camp Service updated': 'Camp Service updated', 'Camp Services': 'Camp Services', 'Camp Type': 'Camp Type', 'Camp Type Details': 'Camp Type Details', 'Camp Type added': 'Camp Type added', 'Camp Type deleted': 'Camp Type deleted', 'Camp Type updated': 'Camp Type updated', 'Camp Types': 'Camp Types', 'Camp Types and Services': 'Camp Types and Services', 'Camp added': 'Camp added', 'Camp deleted': 'Camp deleted', 'Camp updated': 'Camp updated', 'Camps': 'Camps', 'Can only approve 1 record at a time!': 'Can only approve 1 record at a time!', 'Can only disable 1 record at a time!': 'Can only disable 1 record at a time!', 'Can only enable 1 record at a time!': 'Can only enable 1 record at a time!', "Can't import tweepy": "Can't import tweepy", 'Cancel': 'Cancel', 'Cancel Log Entry': 'Cancel Log Entry', 'Cancel Shipment': 'Cancel Shipment', 'Canceled': 'Canceled', 'Candidate Matches for Body %s': 'Candidate Matches for Body %s', 'Canned Fish': 'Canned Fish', 'Cannot be empty': 'Cannot be empty', 'Cannot disable your own account!': 'Cannot disable your own account!', 'Capacity (Max Persons)': 'Capacity (Max Persons)', 'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)': 'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)', 'Capture Information on each disaster victim': 'Capture Information on each disaster victim', 'Capturing the projects each organization is providing and where': 'Capturing the projects each organisation is providing and where', 'Cardiology': 'Cardiology', 'Cassava': 'Cassava', 'Casual Labor': 'Casual Labor', 'Casualties': 'Casualties', 'Catalog': 'Catalogue', 'Catalog Details': 'Catalogue Details', 'Catalog Item added': 'Catalogue Item added', 'Catalog Item deleted': 'Catalogue Item deleted', 'Catalog Item updated': 'Catalogue Item updated', 'Catalog Items': 'Catalogue Items', 'Catalog added': 'Catalogue added', 'Catalog deleted': 'Catalogue deleted', 'Catalog updated': 'Catalogue updated', 'Catalogs': 'Catalogues', 'Categories': 'Categories', 'Category': 'Category', "Caution: doesn't respect the framework rules!": "Caution: doesn't respect the framework rules!", 'Ceilings, light fixtures': 'Ceilings, light fixtures', 'Cell Phone': 'Cell Phone', 'Central point to record details on People': 'Central point to record details on People', 'Certificate': 'Certificate', 'Certificate Catalog': 'Certificate Catalogue', 'Certificate Details': 'Certificate Details', 'Certificate Status': 'Certificate Status', 'Certificate added': 'Certificate added', 'Certificate deleted': 'Certificate deleted', 'Certificate updated': 'Certificate updated', 'Certificates': 'Certificates', 'Certification': 'Certification', 'Certification Details': 'Certification Details', 'Certification added': 'Certification added', 'Certification deleted': 'Certification deleted', 'Certification updated': 'Certification updated', 'Certifications': 'Certifications', 'Certifying Organization': 'Certifying Organisation', 'Change Password': '<PASSWORD> Password', 'Check': 'Check', 'Check Request': 'Check Request', 'Check for errors in the URL, maybe the address was mistyped.': 'Check for errors in the URL, maybe the address was mistyped.', 'Check if the URL is pointing to a directory instead of a webpage.': 'Check if the URL is pointing to a directory instead of a webpage.', 'Check outbox for the message status': 'Check outbox for the message status', 'Check to delete': 'Check to delete', 'Check to delete:': 'Check to delete:', 'Check-in at Facility': 'Check-in at Facility', 'Checked': 'Checked', 'Checklist': 'Checklist', 'Checklist created': 'Checklist created', 'Checklist deleted': 'Checklist deleted', 'Checklist of Operations': 'Checklist of Operations', 'Checklist updated': 'Checklist updated', 'Chemical Hazard': 'Chemical Hazard', 'Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack': 'Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack', 'Chicken': 'Chicken', 'Child': 'Child', 'Child (2-11)': 'Child (2-11)', 'Child (< 18 yrs)': 'Child (< 18 yrs)', 'Child Abduction Emergency': 'Child Abduction Emergency', 'Child headed households (<18 yrs)': 'Child headed households (<18 yrs)', 'Children (2-5 years)': 'Children (2-5 years)', 'Children (5-15 years)': 'Children (5-15 years)', 'Children (< 2 years)': 'Children (< 2 years)', 'Children in adult prisons': 'Children in adult prisons', 'Children in boarding schools': 'Children in boarding schools', 'Children in homes for disabled children': 'Children in homes for disabled children', 'Children in juvenile detention': 'Children in juvenile detention', 'Children in orphanages': 'Children in orphanages', 'Children living on their own (without adults)': 'Children living on their own (without adults)', 'Children not enrolled in new school': 'Children not enrolled in new school', 'Children orphaned by the disaster': 'Children orphaned by the disaster', 'Children separated from their parents/caregivers': 'Children separated from their parents/caregivers', 'Children that have been sent to safe places': 'Children that have been sent to safe places', 'Children who have disappeared since the disaster': 'Children who have disappeared since the disaster', 'Chinese (Simplified)': 'Chinese (Simplified)', 'Chinese (Traditional)': 'Chinese (Traditional)', 'Cholera Treatment': 'Cholera Treatment', 'Cholera Treatment Capability': 'Cholera Treatment Capability', 'Cholera Treatment Center': 'Cholera Treatment Center', 'Cholera-Treatment-Center': 'Cholera-Treatment-Center', 'Choose a new posting based on the new evaluation and team judgement. Severe conditions affecting the whole building are grounds for an UNSAFE posting. Localised Severe and overall Moderate conditions may require a RESTRICTED USE. Place INSPECTED placard at main entrance. Post all other placards at every significant entrance.': 'Choose a new posting based on the new evaluation and team judgement. Severe conditions affecting the whole building are grounds for an UNSAFE posting. Localised Severe and overall Moderate conditions may require a RESTRICTED USE. Place INSPECTED placard at main entrance. Post all other placards at every significant entrance.', 'Christian': 'Christian', 'Church': 'Church', 'City': 'City', 'Civil Emergency': 'Civil Emergency', 'Cladding, glazing': 'Cladding, glazing', 'Click on the link': 'Click on the link', 'Client IP': 'Client IP', 'Climate': 'Climate', 'Clinical Laboratory': 'Clinical Laboratory', 'Clinical Operations': 'Clinical Operations', 'Clinical Status': 'Clinical Status', 'Close map': 'Close map', 'Closed': 'Closed', 'Clothing': 'Clothing', 'Cluster': 'Cluster', 'Cluster Details': 'Cluster Details', 'Cluster Distance': 'Cluster Distance', 'Cluster Subsector': 'Cluster Subsector', 'Cluster Subsector Details': 'Cluster Subsector Details', 'Cluster Subsector added': 'Cluster Subsector added', 'Cluster Subsector deleted': 'Cluster Subsector deleted', 'Cluster Subsector updated': 'Cluster Subsector updated', 'Cluster Subsectors': 'Cluster Subsectors', 'Cluster Threshold': 'Cluster Threshold', 'Cluster added': 'Cluster added', 'Cluster deleted': 'Cluster deleted', 'Cluster updated': 'Cluster updated', 'Cluster(s)': 'Cluster(s)', 'Clusters': 'Clusters', 'Code': 'Code', 'Cold Wave': 'Cold Wave', 'Collapse, partial collapse, off foundation': 'Collapse, partial collapse, off foundation', 'Collective center': 'Collective center', 'Color for Underline of Subheadings': 'Colour for Underline of Subheadings', 'Color of Buttons when hovering': 'Colour of Buttons when hovering', 'Color of bottom of Buttons when not pressed': 'Colour of bottom of Buttons when not pressed', 'Color of bottom of Buttons when pressed': 'Colour of bottom of Buttons when pressed', 'Color of dropdown menus': 'Colour of dropdown menus', 'Color of selected Input fields': 'Colour of selected Input fields', 'Color of selected menu items': 'Colour of selected menu items', 'Columns, pilasters, corbels': 'Columns, pilasters, corbels', 'Combined Method': 'Combined Method', 'Come back later.': 'Come back later.', 'Come back later. Everyone visiting this site is probably experiencing the same problem as you.': 'Come back later. Everyone visiting this site is probably experiencing the same problem as you.', 'Comments': 'Comments', 'Commercial/Offices': 'Commercial/Offices', 'Commit': 'Commit', 'Commit Date': 'Commit Date', 'Commit from %s': 'Commit from %s', 'Commit. Status': 'Commit. Status', 'Commiting a changed spreadsheet to the database': 'Commiting a changed spreadsheet to the database', 'Commitment': 'Commitment', 'Commitment Added': 'Commitment Added', 'Commitment Canceled': 'Commitment Canceled', 'Commitment Details': 'Commitment Details', 'Commitment Item Details': 'Commitment Item Details', 'Commitment Item added': 'Commitment Item added', 'Commitment Item deleted': 'Commitment Item deleted', 'Commitment Item updated': 'Commitment Item updated', 'Commitment Items': 'Commitment Items', 'Commitment Status': 'Commitment Status', 'Commitment Updated': 'Commitment Updated', 'Commitments': 'Commitments', 'Committed': 'Committed', 'Committed By': 'Committed By', 'Committed People': 'Committed People', 'Committed Person Details': 'Committed Person Details', 'Committed Person updated': 'Committed Person updated', 'Committing Inventory': 'Committing Inventory', 'Committing Organization': 'Committing Organisation', 'Committing Person': 'Committing Person', 'Communication problems': 'Communication problems', 'Community Centre': 'Community Centre', 'Community Health Center': 'Community Health Center', 'Community Member': 'Community Member', 'Competency': 'Competency', 'Competency Rating Catalog': 'Competency Rating Catalogue', 'Competency Rating Details': 'Competency Rating Details', 'Competency Rating added': 'Competency Rating added', 'Competency Rating deleted': 'Competency Rating deleted', 'Competency Rating updated': 'Competency Rating updated', 'Competency Ratings': 'Competency Ratings', 'Complete': 'Complete', 'Complete a new Assessment': 'Complete a new Assessment', 'Completed': 'Completed', 'Completed Assessment': 'Completed Assessment', 'Completed Assessment Details': 'Completed Assessment Details', 'Completed Assessment added': 'Completed Assessment added', 'Completed Assessment deleted': 'Completed Assessment deleted', 'Completed Assessment updated': 'Completed Assessment updated', 'Completed Assessments': 'Completed Assessments', 'Completed surveys of this Series:': 'Completed surveys of this Series:', 'Complexion': 'Complexion', 'Compose': 'Compose', 'Compromised': 'Compromised', 'Concrete frame': 'Concrete frame', 'Concrete shear wall': 'Concrete shear wall', 'Condition': 'Condition', 'Configuration': 'Configuration', 'Configurations': 'Configurations', 'Configure Run-time Settings': 'Configure Run-time Settings', 'Configure connection details and authentication': 'Configure connection details and authentication', 'Configure resources to synchronize, update methods and policies': 'Configure resources to synchronise, update methods and policies', 'Configure the default proxy server to connect to remote repositories': 'Configure the default proxy server to connect to remote repositories', 'Confirm Shipment Received': 'Confirm Shipment Received', 'Confirmed': 'Confirmed', 'Confirming Organization': 'Confirming Organisation', 'Conflict Policy': 'Conflict Policy', 'Conflict policy': 'Conflict policy', 'Conflicts': 'Conflicts', 'Consignment Note': 'Consignment Note', 'Constraints Only': 'Constraints Only', 'Consumable': 'Consumable', 'Contact': 'Contact', 'Contact Data': 'Contact Data', 'Contact Details': 'Contact Details', 'Contact Info': 'Contact Info', 'Contact Information': 'Contact Information', 'Contact Information Added': 'Contact Information Added', 'Contact Information Deleted': 'Contact Information Deleted', 'Contact Information Updated': 'Contact Information Updated', 'Contact Method': 'Contact Method', 'Contact Name': 'Contact Name', 'Contact Person': 'Contact Person', 'Contact Phone': 'Contact Phone', 'Contact information added': 'Contact information added', 'Contact information deleted': 'Contact information deleted', 'Contact information updated': 'Contact information updated', 'Contact us': 'Contact us', 'Contacts': 'Contacts', 'Contents': 'Contents', 'Contributor': 'Contributor', 'Conversion Tool': 'Conversion Tool', 'Cooking NFIs': 'Cooking NFIs', 'Cooking Oil': 'Cooking Oil', 'Coordinate Conversion': 'Coordinate Conversion', 'Coping Activities': 'Coping Activities', 'Copy': 'Copy', 'Corn': 'Corn', 'Cost Type': 'Cost Type', 'Cost per Megabyte': 'Cost per Megabyte', 'Cost per Minute': 'Cost per Minute', 'Country': 'Country', 'Country is required!': 'Country is required!', 'Country of Residence': 'Country of Residence', 'County': 'County', 'Course': 'Course', 'Course Catalog': 'Course Catalogue', 'Course Certificate Details': 'Course Certificate Details', 'Course Certificate added': 'Course Certificate added', 'Course Certificate deleted': 'Course Certificate deleted', 'Course Certificate updated': 'Course Certificate updated', 'Course Certificates': 'Course Certificates', 'Course Details': 'Course Details', 'Course added': 'Course added', 'Course deleted': 'Course deleted', 'Course updated': 'Course updated', 'Courses': 'Courses', 'Create & manage Distribution groups to receive Alerts': 'Create & manage Distribution groups to receive Alerts', 'Create Checklist': 'Create Checklist', 'Create Group Entry': 'Create Group Entry', 'Create Impact Assessment': 'Create Impact Assessment', 'Create Mobile Impact Assessment': 'Create Mobile Impact Assessment', 'Create New Asset': 'Create New Asset', 'Create New Catalog': 'Create New Catalogue', 'Create New Catalog Item': 'Create New Catalogue Item', 'Create New Event': 'Create New Event', 'Create New Item': 'Create New Item', 'Create New Item Category': 'Create New Item Category', 'Create New Location': 'Create New Location', 'Create New Request': 'Create New Request', 'Create New Scenario': 'Create New Scenario', 'Create New Vehicle': 'Create New Vehicle', 'Create Rapid Assessment': 'Create Rapid Assessment', 'Create Request': 'Create Request', 'Create Task': 'Create Task', 'Create a group entry in the registry.': 'Create a group entry in the registry.', 'Create new Office': 'Create new Office', 'Create new Organization': 'Create new Organisation', 'Create, enter, and manage surveys.': 'Create, enter, and manage surveys.', 'Creation of assessments': 'Creation of assessments', 'Credential Details': 'Credential Details', 'Credential added': 'Credential added', 'Credential deleted': 'Credential deleted', 'Credential updated': 'Credential updated', 'Credentialling Organization': 'Credentialling Organisation', 'Credentials': 'Credentials', 'Credit Card': 'Credit Card', 'Crime': 'Crime', 'Criteria': 'Criteria', 'Currency': 'Currency', 'Current Entries': 'Current Entries', 'Current Group Members': 'Current Group Members', 'Current Identities': 'Current Identities', 'Current Location': 'Current Location', 'Current Location Country': 'Current Location Country', 'Current Location Phone Number': 'Current Location Phone Number', 'Current Location Treating Hospital': 'Current Location Treating Hospital', 'Current Log Entries': 'Current Log Entries', 'Current Memberships': 'Current Memberships', 'Current Mileage': 'Current Mileage', 'Current Records': 'Current Records', 'Current Registrations': 'Current Registrations', 'Current Status': 'Current Status', 'Current Team Members': 'Current Team Members', 'Current Twitter account': 'Current Twitter account', 'Current community priorities': 'Current community priorities', 'Current general needs': 'Current general needs', 'Current greatest needs of vulnerable groups': 'Current greatest needs of vulnerable groups', 'Current health problems': 'Current health problems', 'Current number of patients': 'Current number of patients', 'Current problems, categories': 'Current problems, categories', 'Current problems, details': 'Current problems, details', 'Current request': 'Current request', 'Current response': 'Current response', 'Current session': 'Current session', 'Currently Configured Jobs': 'Currently Configured Jobs', 'Currently Configured Repositories': 'Currently Configured Repositories', 'Currently Configured Resources': 'Currently Configured Resources', 'Currently no Certifications registered': 'Currently no Certifications registered', 'Currently no Course Certificates registered': 'Currently no Course Certificates registered', 'Currently no Credentials registered': 'Currently no Credentials registered', 'Currently no Missions registered': 'Currently no Missions registered', 'Currently no Skill Equivalences registered': 'Currently no Skill Equivalences registered', 'Currently no Skills registered': 'Currently no Skills registered', 'Currently no Trainings registered': 'Currently no Trainings registered', 'Currently no entries in the catalog': 'Currently no entries in the catalogue', 'DC': 'DC', 'DNA Profile': 'DNA Profile', 'DNA Profiling': 'DNA Profiling', 'DVI Navigator': 'DVI Navigator', 'Dam Overflow': 'Dam Overflow', 'Damage': 'Damage', 'Dangerous Person': 'Dangerous Person', 'Dashboard': 'Dashboard', 'Data': 'Data', 'Data uploaded': 'Data uploaded', 'Database': 'Database', 'Date': 'Date', 'Date & Time': 'Date & Time', 'Date Available': 'Date Available', 'Date Delivered': 'Date Delivered', 'Date Expected': 'Date Expected', 'Date Received': 'Date Received', 'Date Requested': 'Date Requested', 'Date Required': 'Date Required', 'Date Required Until': 'Date Required Until', 'Date Sent': 'Date Sent', 'Date Until': 'Date Until', 'Date and Time': 'Date and Time', 'Date and time this report relates to.': 'Date and time this report relates to.', 'Date of Birth': 'Date of Birth', 'Date of Latest Information on Beneficiaries Reached': 'Date of Latest Information on Beneficiaries Reached', 'Date of Report': 'Date of Report', 'Date of Treatment': 'Date of Treatment', 'Date/Time': 'Date/Time', 'Date/Time of Find': 'Date/Time of Find', 'Date/Time when found': 'Date/Time when found', 'Date/Time when last seen': 'Date/Time when last seen', 'De-duplicator': 'De-duplicator', 'Dead Bodies': 'Dead Bodies', 'Dead Body': 'Dead Body', 'Dead Body Details': 'Dead Body Details', 'Dead Body Reports': 'Dead Body Reports', 'Dead body report added': 'Dead body report added', 'Dead body report deleted': 'Dead body report deleted', 'Dead body report updated': 'Dead body report updated', 'Deaths in the past 24h': 'Deaths in the past 24h', 'Deaths/24hrs': 'Deaths/24hrs', 'Decimal Degrees': 'Decimal Degrees', 'Decomposed': 'Decomposed', 'Default Height of the map window.': 'Default Height of the map window.', 'Default Location': 'Default Location', 'Default Map': 'Default Map', 'Default Marker': 'Default Marker', 'Default Width of the map window.': 'Default Width of the map window.', 'Defecation area for animals': 'Defecation area for animals', 'Define Scenarios for allocation of appropriate Resources (Human, Assets & Facilities).': 'Define Scenarios for allocation of appropriate Resources (Human, Assets & Facilities).', 'Defines the icon used for display of features on handheld GPS.': 'Defines the icon used for display of features on handheld GPS.', 'Defines the icon used for display of features on interactive map & KML exports.': 'Defines the icon used for display of features on interactive map & KML exports.', 'Defines the marker used for display & the attributes visible in the popup.': 'Defines the marker used for display & the attributes visible in the popup.', 'Degrees must be a number between -180 and 180': 'Degrees must be a number between -180 and 180', 'Dehydration': 'Dehydration', 'Delete': 'Delete', 'Delete Alternative Item': 'Delete Alternative Item', 'Delete Assessment': 'Delete Assessment', 'Delete Assessment Summary': 'Delete Assessment Summary', 'Delete Asset': 'Delete Asset', 'Delete Asset Log Entry': 'Delete Asset Log Entry', 'Delete Baseline': 'Delete Baseline', 'Delete Baseline Type': 'Delete Baseline Type', 'Delete Brand': 'Delete Brand', 'Delete Budget': 'Delete Budget', 'Delete Bundle': 'Delete Bundle', 'Delete Catalog': 'Delete Catalogue', 'Delete Catalog Item': 'Delete Catalogue Item', 'Delete Certificate': 'Delete Certificate', 'Delete Certification': 'Delete Certification', 'Delete Cluster': 'Delete Cluster', 'Delete Cluster Subsector': 'Delete Cluster Subsector', 'Delete Commitment': 'Delete Commitment', 'Delete Commitment Item': 'Delete Commitment Item', 'Delete Competency Rating': 'Delete Competency Rating', 'Delete Contact Information': 'Delete Contact Information', 'Delete Course': 'Delete Course', 'Delete Course Certificate': 'Delete Course Certificate', 'Delete Credential': 'Delete Credential', 'Delete Document': 'Delete Document', 'Delete Donor': 'Delete Donor', 'Delete Event': 'Delete Event', 'Delete Feature Class': 'Delete Feature Class', 'Delete Feature Layer': 'Delete Feature Layer', 'Delete GPS data': 'Delete GPS data', 'Delete Group': 'Delete Group', 'Delete Home': 'Delete Home', 'Delete Hospital': 'Delete Hospital', 'Delete Image': 'Delete Image', 'Delete Impact': 'Delete Impact', 'Delete Impact Type': 'Delete Impact Type', 'Delete Incident Report': 'Delete Incident Report', 'Delete Item': 'Delete Item', 'Delete Item Category': 'Delete Item Category', 'Delete Item Pack': 'Delete Item Pack', 'Delete Job Role': 'Delete Job Role', 'Delete Kit': 'Delete Kit', 'Delete Layer': 'Delete Layer', 'Delete Level 1 Assessment': 'Delete Level 1 Assessment', 'Delete Level 2 Assessment': 'Delete Level 2 Assessment', 'Delete Location': 'Delete Location', 'Delete Map Configuration': 'Delete Map Configuration', 'Delete Marker': 'Delete Marker', 'Delete Membership': 'Delete Membership', 'Delete Message': 'Delete Message', 'Delete Mission': 'Delete Mission', 'Delete Need': 'Delete Need', 'Delete Need Type': 'Delete Need Type', 'Delete Office': 'Delete Office', 'Delete Order': 'Delete Order', 'Delete Organization': 'Delete Organisation', 'Delete Organization Domain': 'Delete Organisation Domain', 'Delete Patient': 'Delete Patient', 'Delete Person': 'Delete Person', 'Delete Photo': 'Delete Photo', 'Delete Population Statistic': 'Delete Population Statistic', 'Delete Position': 'Delete Position', 'Delete Project': 'Delete Project', 'Delete Projection': 'Delete Projection', 'Delete Rapid Assessment': 'Delete Rapid Assessment', 'Delete Received Shipment': 'Delete Received Shipment', 'Delete Record': 'Delete Record', 'Delete Relative': 'Delete Relative', 'Delete Report': 'Delete Report', 'Delete Request': 'Delete Request', 'Delete Request Item': 'Delete Request Item', 'Delete Request for Donations': 'Delete Request for Donations', 'Delete Request for Volunteers': 'Delete Request for Volunteers', 'Delete Resource': 'Delete Resource', 'Delete Room': 'Delete Room', 'Delete Saved Search': 'Delete Saved Search', 'Delete Scenario': 'Delete Scenario', 'Delete Section': 'Delete Section', 'Delete Sector': 'Delete Sector', 'Delete Sent Item': 'Delete Sent Item', 'Delete Sent Shipment': 'Delete Sent Shipment', 'Delete Service Profile': 'Delete Service Profile', 'Delete Skill': 'Delete Skill', 'Delete Skill Equivalence': 'Delete Skill Equivalence', 'Delete Skill Provision': 'Delete Skill Provision', 'Delete Skill Type': 'Delete Skill Type', 'Delete Staff Type': 'Delete Staff Type', 'Delete Status': 'Delete Status', 'Delete Subscription': 'Delete Subscription', 'Delete Subsector': 'Delete Subsector', 'Delete Training': 'Delete Training', 'Delete Unit': 'Delete Unit', 'Delete User': 'Delete User', 'Delete Vehicle': 'Delete Vehicle', 'Delete Vehicle Details': 'Delete Vehicle Details', 'Delete Warehouse': 'Delete Warehouse', 'Delete from Server?': 'Delete from Server?', 'Delete this Assessment Answer': 'Delete this Assessment Answer', 'Delete this Assessment Question': 'Delete this Assessment Question', 'Delete this Assessment Series': 'Delete this Assessment Series', 'Delete this Assessment Template': 'Delete this Assessment Template', 'Delete this Completed Assessment': 'Delete this Completed Assessment', 'Delete this Question Meta-Data': 'Delete this Question Meta-Data', 'Delete this Template Section': 'Delete this Template Section', 'Deliver To': 'Deliver To', 'Delivered To': 'Delivered To', 'Delphi Decision Maker': 'Delphi Decision Maker', 'Demographic': 'Demographic', 'Demonstrations': 'Demonstrations', 'Dental Examination': 'Dental Examination', 'Dental Profile': 'Dental Profile', 'Deployment Location': 'Deployment Location', 'Describe the condition of the roads to your hospital.': 'Describe the condition of the roads to your hospital.', 'Describe the procedure which this record relates to (e.g. "medical examination")': 'Describe the procedure which this record relates to (e.g. "medical examination")', 'Description': 'Description', 'Description of Contacts': 'Description of Contacts', 'Description of defecation area': 'Description of defecation area', 'Description of drinking water source': 'Description of drinking water source', 'Description of sanitary water source': 'Description of sanitary water source', 'Description of water source before the disaster': 'Description of water source before the disaster', 'Design, deploy & analyze surveys.': 'Design, deploy & analyse surveys.', 'Desire to remain with family': 'Desire to remain with family', 'Destination': 'Destination', 'Destroyed': 'Destroyed', 'Details': 'Details', 'Details field is required!': 'Details field is required!', 'Dialysis': 'Dialysis', 'Diaphragms, horizontal bracing': 'Diaphragms, horizontal bracing', 'Diarrhea': 'Diarrhea', 'Dignitary Visit': 'Dignitary Visit', 'Direction': 'Direction', 'Disable': 'Disable', 'Disabled': 'Disabled', 'Disabled participating in coping activities': 'Disabled participating in coping activities', 'Disabled?': 'Disabled?', 'Disaster Victim Identification': 'Disaster Victim Identification', 'Disaster Victim Registry': 'Disaster Victim Registry', 'Disaster clean-up/repairs': 'Disaster clean-up/repairs', 'Discharge (cusecs)': 'Discharge (cusecs)', 'Discharges/24hrs': 'Discharges/24hrs', 'Discussion Forum': 'Discussion Forum', 'Discussion Forum on item': 'Discussion Forum on item', 'Disease vectors': 'Disease vectors', 'Dispensary': 'Dispensary', 'Displaced': 'Displaced', 'Displaced Populations': 'Displaced Populations', 'Display': 'Display', 'Display Polygons?': 'Display Polygons?', 'Display Routes?': 'Display Routes?', 'Display Tracks?': 'Display Tracks?', 'Display Waypoints?': 'Display Waypoints?', 'Distance between defecation area and water source': 'Distance between defecation area and water source', 'Distance from %s:': 'Distance from %s:', 'Distance(Kms)': 'Distance(Kms)', 'Distribution': 'Distribution', 'Distribution groups': 'Distribution groups', 'District': 'District', 'Do you really want to delete these records?': 'Do you really want to delete these records?', 'Do you want to cancel this received shipment? The items will be removed from the Inventory. This action CANNOT be undone!': 'Do you want to cancel this received shipment? The items will be removed from the Inventory. This action CANNOT be undone!', 'Do you want to cancel this sent shipment? The items will be returned to the Inventory. This action CANNOT be undone!': 'Do you want to cancel this sent shipment? The items will be returned to the Inventory. This action CANNOT be undone!', 'Do you want to receive this shipment?': 'Do you want to receive this shipment?', 'Do you want to send these Committed items?': 'Do you want to send these Committed items?', 'Do you want to send this shipment?': 'Do you want to send this shipment?', 'Document Details': 'Document Details', 'Document Scan': 'Document Scan', 'Document added': 'Document added', 'Document deleted': 'Document deleted', 'Document removed': 'Document removed', 'Document updated': 'Document updated', 'Documents': 'Documents', 'Documents and Photos': 'Documents and Photos', 'Does this facility provide a cholera treatment center?': 'Does this facility provide a cholera treatment center?', 'Doing nothing (no structured activity)': 'Doing nothing (no structured activity)', 'Domain': 'Domain', 'Domestic chores': 'Domestic chores', 'Donated': 'Donated', 'Donation Certificate': 'Donation Certificate', 'Donation Phone #': 'Donation Phone #', 'Donations': 'Donations', 'Donor': 'Donor', 'Donor Details': 'Donor Details', 'Donor added': 'Donor added', 'Donor deleted': 'Donor deleted', 'Donor updated': 'Donor updated', 'Donors': 'Donors', 'Donors Report': 'Donors Report', 'Door frame': 'Door frame', 'Download OCR-able PDF Form': 'Download OCR-able PDF Form', 'Download Template': 'Download Template', 'Download last build': 'Download last build', 'Draft': 'Draft', 'Draft Features': 'Draft Features', 'Drainage': 'Drainage', 'Drawing up a Budget for Staff & Equipment across various Locations.': 'Drawing up a Budget for Staff & Equipment across various Locations.', 'Drill Down by Group': 'Drill Down by Group', 'Drill Down by Incident': 'Drill Down by Incident', 'Drill Down by Shelter': 'Drill Down by Shelter', 'Driving License': 'Driving License', 'Drought': 'Drought', 'Drugs': 'Drugs', 'Dug Well': 'Dug Well', 'Dummy': 'Dummy', 'Duplicate?': 'Duplicate?', 'Duration': 'Duration', 'Dust Storm': 'Dust Storm', 'Dwelling': 'Dwelling', 'E-mail': 'E-mail', 'EMS Reason': 'EMS Reason', 'EMS Status': 'EMS Status', 'ER Status': 'ER Status', 'ER Status Reason': 'ER Status Reason', 'EXERCISE': 'EXERCISE', 'Early Recovery': 'Early Recovery', 'Earth Enabled?': 'Earth Enabled?', 'Earthquake': 'Earthquake', 'Edit': 'Edit', 'Edit Activity': 'Edit Activity', 'Edit Address': 'Edit Address', 'Edit Alternative Item': 'Edit Alternative Item', 'Edit Application': 'Edit Application', 'Edit Assessment': 'Edit Assessment', 'Edit Assessment Answer': 'Edit Assessment Answer', 'Edit Assessment Question': 'Edit Assessment Question', 'Edit Assessment Series': 'Edit Assessment Series', 'Edit Assessment Summary': 'Edit Assessment Summary', 'Edit Assessment Template': 'Edit Assessment Template', 'Edit Asset': 'Edit Asset', 'Edit Asset Log Entry': 'Edit Asset Log Entry', 'Edit Baseline': 'Edit Baseline', 'Edit Baseline Type': 'Edit Baseline Type', 'Edit Brand': 'Edit Brand', 'Edit Budget': 'Edit Budget', 'Edit Bundle': 'Edit Bundle', 'Edit Camp': 'Edit Camp', 'Edit Camp Service': 'Edit Camp Service', 'Edit Camp Type': 'Edit Camp Type', 'Edit Catalog': 'Edit Catalogue', 'Edit Catalog Item': 'Edit Catalogue Item', 'Edit Certificate': 'Edit Certificate', 'Edit Certification': 'Edit Certification', 'Edit Cluster': 'Edit Cluster', 'Edit Cluster Subsector': 'Edit Cluster Subsector', 'Edit Commitment': 'Edit Commitment', 'Edit Commitment Item': 'Edit Commitment Item', 'Edit Committed Person': 'Edit Committed Person', 'Edit Competency Rating': 'Edit Competency Rating', 'Edit Completed Assessment': 'Edit Completed Assessment', 'Edit Contact': 'Edit Contact', 'Edit Contact Information': 'Edit Contact Information', 'Edit Contents': 'Edit Contents', 'Edit Course': 'Edit Course', 'Edit Course Certificate': 'Edit Course Certificate', 'Edit Credential': 'Edit Credential', 'Edit Dead Body Details': 'Edit Dead Body Details', 'Edit Description': 'Edit Description', 'Edit Details': 'Edit Details', 'Edit Disaster Victims': 'Edit Disaster Victims', 'Edit Document': 'Edit Document', 'Edit Donor': 'Edit Donor', 'Edit Email Settings': 'Edit Email Settings', 'Edit Entry': 'Edit Entry', 'Edit Event': 'Edit Event', 'Edit Facility': 'Edit Facility', 'Edit Feature Class': 'Edit Feature Class', 'Edit Feature Layer': 'Edit Feature Layer', 'Edit Flood Report': 'Edit Flood Report', 'Edit GPS data': 'Edit GPS data', 'Edit Group': 'Edit Group', 'Edit Home': 'Edit Home', 'Edit Home Address': 'Edit Home Address', 'Edit Hospital': 'Edit Hospital', 'Edit Human Resource': 'Edit Human Resource', 'Edit Identification Report': 'Edit Identification Report', 'Edit Identity': 'Edit Identity', 'Edit Image Details': 'Edit Image Details', 'Edit Impact': 'Edit Impact', 'Edit Impact Type': 'Edit Impact Type', 'Edit Import File': 'Edit Import File', 'Edit Incident': 'Edit Incident', 'Edit Incident Report': 'Edit Incident Report', 'Edit Inventory Item': 'Edit Inventory Item', 'Edit Item': 'Edit Item', 'Edit Item Category': 'Edit Item Category', 'Edit Item Pack': 'Edit Item Pack', 'Edit Job': 'Edit Job', 'Edit Job Role': 'Edit Job Role', 'Edit Kit': 'Edit Kit', 'Edit Layer': 'Edit Layer', 'Edit Level %d Locations?': 'Edit Level %d Locations?', 'Edit Level 1 Assessment': 'Edit Level 1 Assessment', 'Edit Level 2 Assessment': 'Edit Level 2 Assessment', 'Edit Location': 'Edit Location', 'Edit Location Details': 'Edit Location Details', 'Edit Log Entry': 'Edit Log Entry', 'Edit Map Configuration': 'Edit Map Configuration', 'Edit Marker': 'Edit Marker', 'Edit Membership': 'Edit Membership', 'Edit Message': 'Edit Message', 'Edit Mission': 'Edit Mission', 'Edit Modem Settings': 'Edit Modem Settings', 'Edit Need': 'Edit Need', 'Edit Need Type': 'Edit Need Type', 'Edit Office': 'Edit Office', 'Edit Options': 'Edit Options', 'Edit Order': 'Edit Order', 'Edit Order Item': 'Edit Order Item', 'Edit Organization': 'Edit Organisation', 'Edit Organization Domain': 'Edit Organisation Domain', 'Edit Parameters': 'Edit Parameters', 'Edit Patient': 'Edit Patient', 'Edit Person Details': 'Edit Person Details', 'Edit Personal Effects Details': 'Edit Personal Effects Details', 'Edit Photo': 'Edit Photo', 'Edit Population Statistic': 'Edit Population Statistic', 'Edit Position': 'Edit Position', 'Edit Problem': 'Edit Problem', 'Edit Project': 'Edit Project', 'Edit Project Organization': 'Edit Project Organization', 'Edit Projection': 'Edit Projection', 'Edit Question Meta-Data': 'Edit Question Meta-Data', 'Edit Rapid Assessment': 'Edit Rapid Assessment', 'Edit Received Item': 'Edit Received Item', 'Edit Received Shipment': 'Edit Received Shipment', 'Edit Record': 'Edit Record', 'Edit Registration': 'Edit Registration', 'Edit Relative': 'Edit Relative', 'Edit Repository Configuration': 'Edit Repository Configuration', 'Edit Request': 'Edit Request', 'Edit Request Item': 'Edit Request Item', 'Edit Request for Donations': 'Edit Request for Donations', 'Edit Request for Volunteers': 'Edit Request for Volunteers', 'Edit Requested Skill': 'Edit Requested Skill', 'Edit Resource': 'Edit Resource', 'Edit Resource Configuration': 'Edit Resource Configuration', 'Edit River': 'Edit River', 'Edit Role': 'Edit Role', 'Edit Room': 'Edit Room', 'Edit SMS Settings': 'Edit SMS Settings', 'Edit SMTP to SMS Settings': 'Edit SMTP to SMS Settings', 'Edit Saved Search': 'Edit Saved Search', 'Edit Scenario': 'Edit Scenario', 'Edit Sector': 'Edit Sector', 'Edit Sent Item': 'Edit Sent Item', 'Edit Setting': 'Edit Setting', 'Edit Settings': 'Edit Settings', 'Edit Shelter': 'Edit Shelter', 'Edit Shelter Service': 'Edit Shelter Service', 'Edit Shelter Type': 'Edit Shelter Type', 'Edit Skill': 'Edit Skill', 'Edit Skill Equivalence': 'Edit Skill Equivalence', 'Edit Skill Provision': 'Edit Skill Provision', 'Edit Skill Type': 'Edit Skill Type', 'Edit Solution': 'Edit Solution', 'Edit Staff Type': 'Edit Staff Type', 'Edit Subscription': 'Edit Subscription', 'Edit Subsector': 'Edit Subsector', 'Edit Synchronization Settings': 'Edit Synchronisation Settings', 'Edit Task': 'Edit Task', 'Edit Team': 'Edit Team', 'Edit Template Section': 'Edit Template Section', 'Edit Theme': 'Edit Theme', 'Edit Themes': 'Edit Themes', 'Edit Ticket': 'Edit Ticket', 'Edit Training': 'Edit Training', 'Edit Tropo Settings': 'Edit Tropo Settings', 'Edit User': 'Edit User', 'Edit Vehicle': 'Edit Vehicle', 'Edit Vehicle Details': 'Edit Vehicle Details', 'Edit Volunteer Availability': 'Edit Volunteer Availability', 'Edit Warehouse': 'Edit Warehouse', 'Edit Web API Settings': 'Edit Web API Settings', 'Edit current record': 'Edit current record', 'Edit message': 'Edit message', 'Edit the OpenStreetMap data for this area': 'Edit the OpenStreetMap data for this area', 'Editable?': 'Editable?', 'Education': 'Education', 'Education materials received': 'Education materials received', 'Education materials, source': 'Education materials, source', 'Effects Inventory': 'Effects Inventory', 'Eggs': 'Eggs', 'Either a shelter or a location must be specified': 'Either a shelter or a location must be specified', 'Either file upload or document URL required.': 'Either file upload or document URL required.', 'Either file upload or image URL required.': 'Either file upload or image URL required.', 'Elderly person headed households (>60 yrs)': 'Elderly person headed households (>60 yrs)', 'Electrical': 'Electrical', 'Electrical, gas, sewerage, water, hazmats': 'Electrical, gas, sewerage, water, hazmats', 'Elevated': 'Elevated', 'Elevators': 'Elevators', 'Email': 'Email', 'Email Address to which to send SMS messages. Assumes sending to phonenumber@address': 'Email Address to which to send SMS messages. Assumes sending to phonenumber@address', 'Email Settings': 'Email Settings', 'Email and SMS': 'Email and SMS', 'Email settings updated': 'Email settings updated', 'Embalming': 'Embalming', 'Embassy': 'Embassy', 'Emergency Capacity Building project': 'Emergency Capacity Building project', 'Emergency Department': 'Emergency Department', 'Emergency Shelter': 'Emergency Shelter', 'Emergency Support Facility': 'Emergency Support Facility', 'Emergency Support Service': 'Emergency Support Service', 'Emergency Telecommunications': 'Emergency Telecommunications', 'Enable': 'Enable', 'Enable/Disable Layers': 'Enable/Disable Layers', 'Enabled': 'Enabled', 'Enabled?': 'Enabled?', 'Enabling MapMaker layers disables the StreetView functionality': 'Enabling MapMaker layers disables the StreetView functionality', 'End Date': 'End Date', 'End date': 'End date', 'End date should be after start date': 'End date should be after start date', 'English': 'English', 'Enter Coordinates:': 'Enter Coordinates:', 'Enter a GPS Coord': 'Enter a GPS Coord', 'Enter a name for the spreadsheet you are uploading.': 'Enter a name for the spreadsheet you are uploading.', 'Enter a new support request.': 'Enter a new support request.', 'Enter a unique label!': 'Enter a unique label!', 'Enter a valid date before': 'Enter a valid date before', 'Enter a valid email': 'Enter a valid email', 'Enter a valid future date': 'Enter a valid future date', 'Enter a valid past date': 'Enter a valid past date', 'Enter some characters to bring up a list of possible matches': 'Enter some characters to bring up a list of possible matches', 'Enter some characters to bring up a list of possible matches.': 'Enter some characters to bring up a list of possible matches.', 'Enter tags separated by commas.': 'Enter tags separated by commas.', 'Enter the data for an assessment': 'Enter the data for an assessment', 'Enter the same password as above': 'Enter the same password as above', 'Enter your firstname': 'Enter your firstname', 'Enter your organization': 'Enter your organisation', 'Entered': 'Entered', 'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.': 'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.', 'Environment': 'Environment', 'Equipment': 'Equipment', 'Error encountered while applying the theme.': 'Error encountered while applying the theme.', 'Error in message': 'Error in message', 'Error logs for "%(app)s"': 'Error logs for "%(app)s"', 'Est. Delivery Date': 'Est. Delivery Date', 'Estimated # of households who are affected by the emergency': 'Estimated # of households who are affected by the emergency', 'Estimated # of people who are affected by the emergency': 'Estimated # of people who are affected by the emergency', 'Estimated Overall Building Damage': 'Estimated Overall Building Damage', 'Estimated total number of people in institutions': 'Estimated total number of people in institutions', 'Euros': 'Euros', 'Evacuating': 'Evacuating', 'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)': 'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)', 'Event': 'Event', 'Event Details': 'Event Details', 'Event added': 'Event added', 'Event deleted': 'Event deleted', 'Event updated': 'Event updated', 'Events': 'Events', 'Example': 'Example', 'Exceeded': 'Exceeded', 'Excel': 'Excel', 'Excellent': 'Excellent', 'Exclude contents': 'Exclude contents', 'Excreta disposal': 'Excreta disposal', 'Execute a pre-planned activity identified in <instruction>': 'Execute a pre-planned activity identified in <instruction>', 'Exercise': 'Exercise', 'Exercise?': 'Exercise?', 'Exercises mean all screens have a watermark & all notifications have a prefix.': 'Exercises mean all screens have a watermark & all notifications have a prefix.', 'Existing Placard Type': 'Existing Placard Type', 'Existing Sections': 'Existing Sections', 'Existing food stocks': 'Existing food stocks', 'Existing location cannot be converted into a group.': 'Existing location cannot be converted into a group.', 'Exits': 'Exits', 'Expected Return Home': 'Expected Return Home', 'Experience': 'Experience', 'Expiry Date': 'Expiry Date', 'Explosive Hazard': 'Explosive Hazard', 'Export': 'Export', 'Export Data': 'Export Data', 'Export Database as CSV': 'Export Database as CSV', 'Export in GPX format': 'Export in GPX format', 'Export in KML format': 'Export in KML format', 'Export in OSM format': 'Export in OSM format', 'Export in PDF format': 'Export in PDF format', 'Export in RSS format': 'Export in RSS format', 'Export in XLS format': 'Export in XLS format', 'Exterior Only': 'Exterior Only', 'Exterior and Interior': 'Exterior and Interior', 'Eye Color': 'Eye Colour', 'Facial hair, color': 'Facial hair, colour', 'Facial hair, type': 'Facial hair, type', 'Facial hear, length': 'Facial hear, length', 'Facilities': 'Facilities', 'Facility': 'Facility', 'Facility Details': 'Facility Details', 'Facility Operations': 'Facility Operations', 'Facility Status': 'Facility Status', 'Facility Type': 'Facility Type', 'Facility added': 'Facility added', 'Facility or Location': 'Facility or Location', 'Facility removed': 'Facility removed', 'Facility updated': 'Facility updated', 'Fail': 'Fail', 'Failed!': 'Failed!', 'Fair': 'Fair', 'Falling Object Hazard': 'Falling Object Hazard', 'Families/HH': 'Families/HH', 'Family': 'Family', 'Family tarpaulins received': 'Family tarpaulins received', 'Family tarpaulins, source': 'Family tarpaulins, source', 'Family/friends': 'Family/friends', 'Farmland/fishing material assistance, Rank': 'Farmland/fishing material assistance, Rank', 'Fatalities': 'Fatalities', 'Fax': 'Fax', 'Feature Class': 'Feature Class', 'Feature Class Details': 'Feature Class Details', 'Feature Class added': 'Feature Class added', 'Feature Class deleted': 'Feature Class deleted', 'Feature Class updated': 'Feature Class updated', 'Feature Classes': 'Feature Classes', 'Feature Classes are collections of Locations (Features) of the same type': 'Feature Classes are collections of Locations (Features) of the same type', 'Feature Layer Details': 'Feature Layer Details', 'Feature Layer added': 'Feature Layer added', 'Feature Layer deleted': 'Feature Layer deleted', 'Feature Layer updated': 'Feature Layer updated', 'Feature Layers': 'Feature Layers', 'Feature Namespace': 'Feature Namespace', 'Feature Request': 'Feature Request', 'Feature Type': 'Feature Type', 'Features Include': 'Features Include', 'Female': 'Female', 'Female headed households': 'Female headed households', 'Few': 'Few', 'Field': 'Field', 'Field Hospital': 'Field Hospital', 'File': 'File', 'File Imported': 'File Imported', 'File Importer': 'File Importer', 'File name': 'File name', 'Fill in Latitude': 'Fill in Latitude', 'Fill in Longitude': 'Fill in Longitude', 'Filter': 'Filter', 'Filter Field': 'Filter Field', 'Filter Value': 'Filter Value', 'Find': 'Find', 'Find Dead Body Report': 'Find Dead Body Report', 'Find Hospital': 'Find Hospital', 'Find Person Record': 'Find Person Record', 'Find a Person Record': 'Find a Person Record', 'Finder': 'Finder', 'Fingerprint': 'Fingerprint', 'Fingerprinting': 'Fingerprinting', 'Fingerprints': 'Fingerprints', 'Fire': 'Fire', 'Fire suppression and rescue': 'Fire suppression and rescue', 'First Name': 'First Name', 'First name': 'First name', 'Fishing': 'Fishing', 'Flash Flood': 'Flash Flood', 'Flash Freeze': 'Flash Freeze', 'Flexible Impact Assessments': 'Flexible Impact Assessments', 'Flood': 'Flood', 'Flood Alerts': 'Flood Alerts', 'Flood Alerts show water levels in various parts of the country': 'Flood Alerts show water levels in various parts of the country', 'Flood Report': 'Flood Report', 'Flood Report Details': 'Flood Report Details', 'Flood Report added': 'Flood Report added', 'Flood Report deleted': 'Flood Report deleted', 'Flood Report updated': 'Flood Report updated', 'Flood Reports': 'Flood Reports', 'Flow Status': 'Flow Status', 'Fog': 'Fog', 'Food': 'Food', 'Food Supply': 'Food Supply', 'Food assistance': 'Food assistance', 'Footer': 'Footer', 'Footer file %s missing!': 'Footer file %s missing!', 'For': 'For', 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).': 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).', 'For a country this would be the ISO2 code, for a Town, it would be the Airport Locode.': 'For a country this would be the ISO2 code, for a Town, it would be the Airport Locode.', 'For messages that support alert network internal functions': 'For messages that support alert network internal functions', 'Forest Fire': 'Forest Fire', 'Formal camp': 'Formal camp', 'Format': 'Format', "Format the list of attribute values & the RGB value to use for these as a JSON object, e.g.: {Red: '#FF0000', Green: '#00FF00', Yellow: '#FFFF00'}": "Format the list of attribute values & the RGB value to use for these as a JSON object, e.g.: {Red: '#FF0000', Green: '#00FF00', Yellow: '#FFFF00'}", 'Forms': 'Forms', 'Found': 'Found', 'Foundations': 'Foundations', 'Freezing Drizzle': 'Freezing Drizzle', 'Freezing Rain': 'Freezing Rain', 'Freezing Spray': 'Freezing Spray', 'French': 'French', 'Friday': 'Friday', 'From': 'From', 'From Facility': 'From Facility', 'From Inventory': 'From Inventory', 'From Location': 'From Location', 'From Organization': 'From Organisation', 'Frost': 'Frost', 'Fulfil. Status': 'Fulfil. Status', 'Fulfillment Status': 'Fulfillment Status', 'Full': 'Full', 'Full beard': 'Full beard', 'Fullscreen Map': 'Fullscreen Map', 'Functions available': 'Functions available', 'Funding Organization': 'Funding Organisation', 'Funds Contributed by this Organization': 'Funds Contributed by this Organisation', 'Funeral': 'Funeral', 'Further Action Recommended': 'Further Action Recommended', 'GIS Reports of Shelter': 'GIS Reports of Shelter', 'GIS integration to view location details of the Shelter': 'GIS integration to view location details of the Shelter', 'GPS': 'GPS', 'GPS Data': 'GPS Data', 'GPS ID': 'GPS ID', 'GPS Marker': 'GPS Marker', 'GPS Track': 'GPS Track', 'GPS Track File': 'GPS Track File', 'GPS data': 'GPS data', 'GPS data added': 'GPS data added', 'GPS data deleted': 'GPS data deleted', 'GPS data updated': 'GPS data updated', 'GRN': 'GRN', 'GRN Status': 'GRN Status', 'Gale Wind': 'Gale Wind', 'Gap Analysis': 'Gap Analysis', 'Gap Analysis Map': 'Gap Analysis Map', 'Gap Analysis Report': 'Gap Analysis Report', 'Gender': 'Gender', 'General Comment': 'General Comment', 'General Medical/Surgical': 'General Medical/Surgical', 'General emergency and public safety': 'General emergency and public safety', 'General information on demographics': 'General information on demographics', 'Generate portable application': 'Generate portable application', 'Generator': 'Generator', 'Geocode': 'Geocode', 'Geocoder Selection': 'Geocoder Selection', 'Geometry Name': 'Geometry Name', 'Geonames.org search requires Internet connectivity!': 'Geonames.org search requires Internet connectivity!', 'Geophysical (inc. landslide)': 'Geophysical (inc. landslide)', 'Geotechnical': 'Geotechnical', 'Geotechnical Hazards': 'Geotech<NAME>', 'German': 'German', 'Get incoming recovery requests as RSS feed': 'Get incoming recovery requests as RSS feed', 'Give a brief description of the image, e.g. what can be seen where on the picture (optional).': 'Give a brief description of the image, e.g. what can be seen where on the picture (optional).', 'Give information about where and when you have seen them': 'Give information about where and when you have seen them', 'Go to Request': 'Go to Request', 'Goatee': 'Goatee', 'Good': 'Good', 'Good Condition': 'Good Condition', 'Goods Received Note': 'Goods Received Note', "Google Layers cannot be displayed if there isn't a valid API Key": "Google Layers cannot be displayed if there isn't a valid API Key", 'Government': 'Government', 'Government UID': 'Government UID', 'Government building': 'Government building', 'Grade': 'Grade', 'Great British Pounds': 'Great British Pounds', 'Greater than 10 matches. Please refine search further': 'Greater than 10 matches. Please refine search further', 'Greek': 'Greek', 'Green': 'Green', 'Ground movement, fissures': 'Ground movement, fissures', 'Ground movement, settlement, slips': 'Ground movement, settlement, slips', 'Group': 'Group', 'Group Description': 'Group Description', 'Group Details': 'Group Details', 'Group ID': 'Group ID', 'Group Member added': 'Group Member added', 'Group Members': 'Group Members', 'Group Memberships': 'Group Memberships', 'Group Name': 'Group Name', 'Group Title': 'Group Title', 'Group Type': 'Group Type', 'Group added': 'Group added', 'Group deleted': 'Group deleted', 'Group description': 'Group description', 'Group updated': 'Group updated', 'Groups': 'Groups', 'Groups removed': 'Groups removed', 'Guest': 'Guest', 'HFA Priorities': 'HFA Priorities', 'Hail': 'Hail', 'Hair Color': 'Hair Colour', 'Hair Length': 'Hair Length', 'Hair Style': 'Hair Style', 'Has data from this Reference Document been entered into Sahana?': 'Has data from this Reference Document been entered into Sahana?', 'Has the Certificate for receipt of the shipment been given to the sender?': 'Has the Certificate for receipt of the shipment been given to the sender?', 'Has the GRN (Goods Received Note) been completed?': 'Has the GRN (Goods Received Note) been completed?', 'Hazard Pay': 'Hazard Pay', 'Hazardous Material': 'Hazardous Material', 'Hazardous Road Conditions': 'Hazardous Road Conditions', 'Hazards': 'Hazards', 'Header Background': 'Header Background', 'Header background file %s missing!': 'Header background file %s missing!', 'Headquarters': 'Headquarters', 'Health': 'Health', 'Health care assistance, Rank': 'Health care assistance, Rank', 'Health center': 'Health center', 'Health center with beds': 'Health center with beds', 'Health center without beds': 'Health center without beds', 'Health services status': 'Health services status', 'Healthcare Worker': 'Healthcare Worker', 'Heat Wave': 'Heat Wave', 'Heat and Humidity': 'Heat and Humidity', 'Height': 'Height', 'Height (cm)': 'Height (cm)', 'Height (m)': 'Height (m)', 'Help': 'Help', 'Helps to monitor status of hospitals': 'Helps to monitor status of hospitals', 'Helps to report and search for missing persons': 'Helps to report and search for missing persons', 'Here are the solution items related to the problem.': 'Here are the solution items related to the problem.', 'Heritage Listed': 'Heritage Listed', 'Hierarchy Level 0 Name (i.e. Country)': 'Hierarchy Level 0 Name (i.e. Country)', 'Hierarchy Level 1 Name (e.g. State or Province)': 'Hierarchy Level 1 Name (e.g. State or Province)', 'Hierarchy Level 2 Name (e.g. District or County)': 'Hierarchy Level 2 Name (e.g. District or County)', 'Hierarchy Level 3 Name (e.g. City / Town / Village)': 'Hierarchy Level 3 Name (e.g. City / Town / Village)', 'Hierarchy Level 4 Name (e.g. Neighbourhood)': 'Hierarchy Level 4 Name (e.g. Neighbourhood)', 'Hierarchy Level 5 Name': 'Hierarchy Level 5 Name', 'High': 'High', 'High Water': 'High Water', 'Hindu': 'Hindu', 'Hit the back button on your browser to try again.': 'Hit the back button on your browser to try again.', 'Holiday Address': 'Holiday Address', 'Home': 'Home', 'Home Address': 'Home Address', 'Home City': 'Home City', 'Home Country': 'Home Country', 'Home Crime': 'Home Crime', 'Home Details': 'Home Details', 'Home Phone Number': 'Home Phone Number', 'Home Relative': 'Home Relative', 'Home added': 'Home added', 'Home deleted': 'Home deleted', 'Home updated': 'Home updated', 'Homes': 'Homes', 'Hospital': 'Hospital', 'Hospital Details': 'Hospital Details', 'Hospital Status Report': 'Hospital Status Report', 'Hospital information added': 'Hospital information added', 'Hospital information deleted': 'Hospital information deleted', 'Hospital information updated': 'Hospital information updated', 'Hospital status assessment.': 'Hospital status assessment.', 'Hospitals': 'Hospitals', 'Host National Society': 'Host National Society', 'Hot Spot': 'Hot Spot', 'Hour': 'Hour', 'Hours': 'Hours', 'Household kits received': 'Household kits received', 'Household kits, source': 'Household kits, source', 'How data shall be transferred': 'How data shall be transferred', 'How is this person affected by the disaster? (Select all that apply)': 'How is this person affected by the disaster? (Select all that apply)', 'How local records shall be updated': 'How local records shall be updated', 'How long will the food last?': 'How long will the food last?', 'How many Boys (0-17 yrs) are Dead due to the crisis': 'How many Boys (0-17 yrs) are Dead due to the crisis', 'How many Boys (0-17 yrs) are Injured due to the crisis': 'How many Boys (0-17 yrs) are Injured due to the crisis', 'How many Boys (0-17 yrs) are Missing due to the crisis': 'How many Boys (0-17 yrs) are Missing due to the crisis', 'How many Girls (0-17 yrs) are Dead due to the crisis': 'How many Girls (0-17 yrs) are Dead due to the crisis', 'How many Girls (0-17 yrs) are Injured due to the crisis': 'How many Girls (0-17 yrs) are Injured due to the crisis', 'How many Girls (0-17 yrs) are Missing due to the crisis': 'How many Girls (0-17 yrs) are Missing due to the crisis', 'How many Men (18 yrs+) are Dead due to the crisis': 'How many Men (18 yrs+) are Dead due to the crisis', 'How many Men (18 yrs+) are Injured due to the crisis': 'How many Men (18 yrs+) are Injured due to the crisis', 'How many Men (18 yrs+) are Missing due to the crisis': 'How many Men (18 yrs+) are Missing due to the crisis', 'How many Women (18 yrs+) are Dead due to the crisis': 'How many Women (18 yrs+) are Dead due to the crisis', 'How many Women (18 yrs+) are Injured due to the crisis': 'How many Women (18 yrs+) are Injured due to the crisis', 'How many Women (18 yrs+) are Missing due to the crisis': 'How many Women (18 yrs+) are Missing due to the crisis', 'How many days will the supplies last?': 'How many days will the supplies last?', 'How many new cases have been admitted to this facility in the past 24h?': 'How many new cases have been admitted to this facility in the past 24h?', 'How many of the patients with the disease died in the past 24h at this facility?': 'How many of the patients with the disease died in the past 24h at this facility?', 'How many patients with the disease are currently hospitalized at this facility?': 'How many patients with the disease are currently hospitalized at this facility?', 'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.': 'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.', 'Human Resource': 'Human Resource', 'Human Resource Details': 'Human Resource Details', 'Human Resource Management': 'Human Resource Management', 'Human Resource added': 'Human Resource added', 'Human Resource removed': 'Human Resource removed', 'Human Resource updated': 'Human Resource updated', 'Human Resources': 'Human Resources', 'Human Resources Management': 'Human Resources Management', 'Humanitarian NGO': 'Humanitarian NGO', 'Hurricane': 'Hurricane', 'Hurricane Force Wind': 'Hurricane Force Wind', 'Hybrid Layer': 'Hybrid Layer', 'Hygiene': 'Hygiene', 'Hygiene NFIs': 'Hygiene NFIs', 'Hygiene kits received': 'Hygiene kits received', 'Hygiene kits, source': 'Hygiene kits, source', 'Hygiene practice': 'Hygiene practice', 'Hygiene problems': 'Hygiene problems', 'I accept. Create my account.': 'I accept. Create my account.', 'ID Tag': 'ID Tag', 'ID Tag Number': 'ID Tag Number', 'ID type': 'ID type', 'Ice Pressure': 'Ice Pressure', 'Iceberg': 'Iceberg', 'Identification': 'Identification', 'Identification Report': 'Identification Report', 'Identification Reports': 'Identification Reports', 'Identification Status': 'Identification Status', 'Identified as': 'Identified as', 'Identified by': 'Identified by', 'Identifier which the repository identifies itself with when sending synchronization requests.': 'Identifier which the repository identifies itself with when sending synchronisation requests.', 'Identity': 'Identity', 'Identity Details': 'Identity Details', 'Identity added': 'Identity added', 'Identity deleted': 'Identity deleted', 'Identity updated': 'Identity updated', 'If a ticket was issued then please provide the Ticket ID.': 'If a ticket was issued then please provide the Ticket ID.', 'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.': 'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.', 'If it is a URL leading to HTML, then this will downloaded.': 'If it is a URL leading to HTML, then this will downloaded.', 'If neither are defined, then the Default Marker is used.': 'If neither are defined, then the Default Marker is used.', 'If no marker defined then the system default marker is used': 'If no marker defined then the system default marker is used', 'If no, specify why': 'If no, specify why', 'If none are selected, then all are searched.': 'If none are selected, then all are searched.', 'If not found, you can have a new location created.': 'If not found, you can have a new location created.', "If selected, then this Asset's Location will be updated whenever the Person's Location is updated.": "If selected, then this Asset's Location will be updated whenever the Person's Location is updated.", 'If the location is a geographic area, then state at what level here.': 'If the location is a geographic area, then state at what level here.', 'If the request is for %s, please enter the details on the next screen.': 'If the request is for %s, please enter the details on the next screen.', 'If the request type is "Other", please enter request details here.': 'If the request type is "Other", please enter request details here.', "If this configuration represents a region for the Regions menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.": "If this configuration represents a region for the Regions menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.", "If this field is populated then a user who specifies this Organization when signing up will be assigned as a Staff of this Organization unless their domain doesn't match the domain field.": "If this field is populated then a user who specifies this Organisation when signing up will be assigned as a Staff of this Organisation unless their domain doesn't match the domain field.", 'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organization': 'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organisation', 'If this is set to True then mails will be deleted from the server after downloading.': 'If this is set to True then mails will be deleted from the server after downloading.', 'If this record should be restricted then select which role is required to access the record here.': 'If this record should be restricted then select which role is required to access the record here.', 'If this record should be restricted then select which role(s) are permitted to access the record here.': 'If this record should be restricted then select which role(s) are permitted to access the record here.', 'If yes, specify what and by whom': 'If yes, specify what and by whom', 'If yes, which and how': 'If yes, which and how', 'If you do not enter a Reference Document, your email will be displayed to allow this data to be verified.': 'If you do not enter a Reference Document, your email will be displayed to allow this data to be verified.', "If you don't see the Hospital in the list, you can add a new one by clicking link 'Add Hospital'.": "If you don't see the Hospital in the list, you can add a new one by clicking link 'Add Hospital'.", "If you don't see the Office in the list, you can add a new one by clicking link 'Add Office'.": "If you don't see the Office in the list, you can add a new one by clicking link 'Add Office'.", "If you don't see the Organization in the list, you can add a new one by clicking link 'Add Organization'.": "If you don't see the Organisation in the list, you can add a new one by clicking link 'Add Organisation'.", "If you don't see the site in the list, you can add a new one by clicking link 'Add Project Site'.": "If you don't see the site in the list, you can add a new one by clicking link 'Add Project Site'.", 'If you have any questions or need support, please see': 'If you have any questions or need support, please see', 'If you know what the Geonames ID of this location is then you can enter it here.': 'If you know what the Geonames ID of this location is then you can enter it here.', 'If you know what the OSM ID of this location is then you can enter it here.': 'If you know what the OSM ID of this location is then you can enter it here.', 'If you need to add a new document then you can click here to attach one.': 'If you need to add a new document then you can click here to attach one.', 'If you want several values, then separate with': 'If you want several values, then separate with', 'If you would like to help, then please': 'If you would like to help, then please', 'Illegal Immigrant': 'Illegal Immigrant', 'Image': 'Image', 'Image Details': 'Image Details', 'Image File(s), one image per page': 'Image File(s), one image per page', 'Image Tags': 'Image Tags', 'Image Type': 'Image Type', 'Image Upload': 'Image Upload', 'Image added': 'Image added', 'Image deleted': 'Image deleted', 'Image updated': 'Image updated', 'Imagery': 'Imagery', 'Images': 'Images', 'Impact Assessments': 'Impact Assessments', 'Impact Details': 'Impact Details', 'Impact Type': 'Impact Type', 'Impact Type Details': 'Impact Type Details', 'Impact Type added': 'Impact Type added', 'Impact Type deleted': 'Impact Type deleted', 'Impact Type updated': 'Impact Type updated', 'Impact Types': 'Impact Types', 'Impact added': 'Impact added', 'Impact deleted': 'Impact deleted', 'Impact updated': 'Impact updated', 'Impacts': 'Impacts', 'Import': 'Import', 'Import Completed Responses': 'Import Completed Responses', 'Import Data': 'Import Data', 'Import File': 'Import File', 'Import File Details': 'Import File Details', 'Import File deleted': 'Import File deleted', 'Import Files': 'Import Files', 'Import Job Count': 'Import Job Count', 'Import Jobs': 'Import Jobs', 'Import New File': 'Import New File', 'Import Offices': 'Import Offices', 'Import Organizations': 'Import Organisations', 'Import Project Organizations': 'Import Project Organisations', 'Import Questions': 'Import Questions', 'Import Staff & Volunteers': 'Import Staff & Volunteers', 'Import Templates': 'Import Templates', 'Import from Ushahidi Instance': 'Import from Ushahidi Instance', 'Import multiple tables as CSV': 'Import multiple tables as CSV', 'Import/Export': 'Import/Export', 'Importantly where there are no aid services being provided': 'Importantly where there are no aid services being provided', 'Imported': 'Imported', 'Importing data from spreadsheets': 'Importing data from spreadsheets', 'Improper decontamination': 'Improper decontamination', 'Improper handling of dead bodies': 'Improper handling of dead bodies', 'In Catalogs': 'In Catalogues', 'In Inventories': 'In Inventories', 'In Process': 'In Process', 'In Progress': 'In Progress', 'In Window layout the map maximises to fill the window, so no need to set a large value here.': 'In Window layout the map maximises to fill the window, so no need to set a large value here.', 'Inbound Mail Settings': 'Inbound Mail Settings', 'Incident': 'Incident', 'Incident Categories': 'Incident Categories', 'Incident Details': 'Incident Details', 'Incident Report': 'Incident Report', 'Incident Report Details': 'Incident Report Details', 'Incident Report added': 'Incident Report added', 'Incident Report deleted': 'Incident Report deleted', 'Incident Report updated': 'Incident Report updated', 'Incident Reporting': 'Incident Reporting', 'Incident Reporting System': 'Incident Reporting System', 'Incident Reports': 'Incident Reports', 'Incident added': 'Incident added', 'Incident removed': 'Incident removed', 'Incident updated': 'Incident updated', 'Incidents': 'Incidents', 'Include any special requirements such as equipment which they need to bring.': 'Include any special requirements such as equipment which they need to bring.', 'Incoming': 'Incoming', 'Incoming Shipment canceled': 'Incoming Shipment canceled', 'Incoming Shipment updated': 'Incoming Shipment updated', 'Incomplete': 'Incomplete', 'Individuals': 'Individuals', 'Industrial': 'Industrial', 'Industrial Crime': 'Industrial Crime', 'Industry Fire': 'Industry Fire', 'Infant (0-1)': 'Infant (0-1)', 'Infectious Disease': 'Infectious Disease', 'Infectious Disease (Hazardous Material)': 'Infectious Disease (Hazardous Material)', 'Infectious Diseases': 'Infectious Diseases', 'Infestation': 'Infestation', 'Informal Leader': 'Informal Leader', 'Informal camp': 'Informal camp', 'Information gaps': 'Information gaps', 'Infusion catheters available': 'Infusion catheters available', 'Infusion catheters need per 24h': 'Infusion catheters need per 24h', 'Infusion catheters needed per 24h': 'Infusion catheters needed per 24h', 'Infusions available': 'Infusions available', 'Infusions needed per 24h': 'Infusions needed per 24h', 'Inspected': 'Inspected', 'Inspection Date': 'Inspection Date', 'Inspection date and time': 'Inspection date and time', 'Inspection time': 'Inspection time', 'Inspector ID': 'Inspector ID', 'Instant Porridge': 'Instant Porridge', 'Institution': 'Institution', 'Insufficient': 'Insufficient', 'Insufficient privileges': 'Insufficient privileges', 'Insufficient vars: Need module, resource, jresource, instance': 'Insufficient vars: Need module, resource, jresource, instance', 'Insurance Renewal Due': 'Insurance Renewal Due', 'Intergovernmental Organization': 'Intergovernmental Organisation', 'Interior walls, partitions': 'Interior walls, partitions', 'Internal State': 'Internal State', 'International NGO': 'International NGO', 'International Organization': 'International Organisation', 'Interview taking place at': 'Interview taking place at', 'Invalid': 'Invalid', 'Invalid Query': 'Invalid Query', 'Invalid email': 'Invalid email', 'Invalid phone number': 'Invalid phone number', 'Invalid phone number!': 'Invalid phone number!', 'Invalid request!': 'Invalid request!', 'Invalid ticket': 'Invalid ticket', 'Inventories': 'Inventories', 'Inventory': 'Inventory', 'Inventory Item': 'Inventory Item', 'Inventory Item Details': 'Inventory Item Details', 'Inventory Item updated': 'Inventory Item updated', 'Inventory Items': 'Inventory Items', 'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.': 'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.', 'Inventory Management': 'Inventory Management', 'Inventory Stock Position': 'Inventory Stock Position', 'Inventory functionality is available for': 'Inventory functionality is available for', 'Inventory of Effects': 'Inventory of Effects', 'Is editing level L%d locations allowed?': 'Is editing level L%d locations allowed?', 'Is it safe to collect water?': 'Is it safe to collect water?', 'Is this a strict hierarchy?': 'Is this a strict hierarchy?', 'Issuing Authority': 'Issuing Authority', 'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.', 'Italian': 'Italian', 'Item': 'Item', 'Item Added to Shipment': 'Item Added to Shipment', 'Item Catalog Details': 'Item Catalogue Details', 'Item Catalogs': 'Item Catalogues', 'Item Categories': 'Item Categories', 'Item Category': 'Item Category', 'Item Category Details': 'Item Category Details', 'Item Category added': 'Item Category added', 'Item Category deleted': 'Item Category deleted', 'Item Category updated': 'Item Category updated', 'Item Details': 'Item Details', 'Item Pack Details': 'Item Pack Details', 'Item Pack added': 'Item Pack added', 'Item Pack deleted': 'Item Pack deleted', 'Item Pack updated': 'Item Pack updated', 'Item Packs': 'Item Packs', 'Item added': 'Item added', 'Item added to Inventory': 'Item added to Inventory', 'Item added to order': 'Item added to order', 'Item added to shipment': 'Item added to shipment', 'Item already in Bundle!': 'Item already in Bundle!', 'Item already in Kit!': 'Item already in Kit!', 'Item already in budget!': 'Item already in budget!', 'Item deleted': 'Item deleted', 'Item removed from Inventory': 'Item removed from Inventory', 'Item removed from order': 'Item removed from order', 'Item removed from shipment': 'Item removed from shipment', 'Item updated': 'Item updated', 'Items': 'Items', 'Items in Category can be Assets': 'Items in Category can be Assets', 'Japanese': 'Japanese', 'Jerry can': 'Jerry can', 'Jew': 'Jew', 'Job Role': 'Job Role', 'Job Role Catalog': 'Job Role Catalogue', 'Job Role Details': 'Job Role Details', 'Job Role added': 'Job Role added', 'Job Role deleted': 'Job Role deleted', 'Job Role updated': 'Job Role updated', 'Job Roles': 'Job Roles', 'Job Title': 'Job Title', 'Job added': 'Job added', 'Job deleted': 'Job deleted', 'Job updated updated': 'Job updated updated', 'Journal': 'Journal', 'Journal Entry Details': 'Journal Entry Details', 'Journal entry added': 'Journal entry added', 'Journal entry deleted': 'Journal entry deleted', 'Journal entry updated': 'Journal entry updated', 'Kit': 'Kit', 'Kit Contents': 'Kit Contents', 'Kit Details': 'Kit Details', 'Kit Updated': 'Kit Updated', 'Kit added': 'Kit added', 'Kit deleted': 'Kit deleted', 'Kit updated': 'Kit updated', 'Kits': 'Kits', 'Known Identities': 'Known Identities', 'Known incidents of violence against women/girls': 'Known incidents of violence against women/girls', 'Known incidents of violence since disaster': 'Known incidents of violence since disaster', 'Korean': 'Korean', 'LICENSE': 'LICENSE', 'Label Question:': 'Label Question:', 'Lack of material': 'Lack of material', 'Lack of school uniform': 'Lack of school uniform', 'Lack of supplies at school': 'Lack of supplies at school', 'Lack of transport to school': 'Lack of transport to school', 'Lactating women': 'Lactating women', 'Lahar': 'Lahar', 'Landslide': 'Landslide', 'Language': 'Language', 'Last Name': 'Last Name', 'Last Synchronization': 'Last Synchronisation', 'Last known location': 'Last known location', 'Last name': 'Last name', 'Last status': 'Last status', 'Last synchronized on': 'Last synchronised on', 'Last updated ': 'Last updated ', 'Last updated by': 'Last updated by', 'Last updated on': 'Last updated on', 'Latitude': 'Latitude', 'Latitude & Longitude': 'Latitude & Longitude', 'Latitude is North-South (Up-Down).': 'Latitude is North-South (Up-Down).', 'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.', 'Latitude of Map Center': 'Latitude of Map Center', 'Latitude of far northern end of the region of interest.': 'Latitude of far northern end of the region of interest.', 'Latitude of far southern end of the region of interest.': 'Latitude of far southern end of the region of interest.', 'Latitude should be between': 'Latitude should be between', 'Latrines': 'Latrines', 'Law enforcement, military, homeland and local/private security': 'Law enforcement, military, homeland and local/private security', 'Layer Details': 'Layer Details', 'Layer ID': 'Layer ID', 'Layer Name': 'Layer Name', 'Layer Type': 'Layer Type', 'Layer added': 'Layer added', 'Layer deleted': 'Layer deleted', 'Layer has been Disabled': 'Layer has been Disabled', 'Layer has been Enabled': 'Layer has been Enabled', 'Layer updated': 'Layer updated', 'Layers': 'Layers', 'Layers updated': 'Layers updated', 'Leader': 'Leader', 'Leave blank to request an unskilled person': 'Leave blank to request an unskilled person', 'Legend Format': 'Legend Format', 'Length (m)': 'Length (m)', 'Level': 'Level', 'Level 1': 'Level 1', 'Level 1 Assessment Details': 'Level 1 Assessment Details', 'Level 1 Assessment added': 'Level 1 Assessment added', 'Level 1 Assessment deleted': 'Level 1 Assessment deleted', 'Level 1 Assessment updated': 'Level 1 Assessment updated', 'Level 1 Assessments': 'Level 1 Assessments', 'Level 2': 'Level 2', 'Level 2 Assessment Details': 'Level 2 Assessment Details', 'Level 2 Assessment added': 'Level 2 Assessment added', 'Level 2 Assessment deleted': 'Level 2 Assessment deleted', 'Level 2 Assessment updated': 'Level 2 Assessment updated', 'Level 2 Assessments': 'Level 2 Assessments', 'Level 2 or detailed engineering evaluation recommended': 'Level 2 or detailed engineering evaluation recommended', "Level is higher than parent's": "Level is higher than parent's", 'Library support not available for OpenID': 'Library support not available for OpenID', 'License Number': 'License Number', 'License Plate': 'License Plate', 'LineString': 'LineString', 'List': 'List', 'List / Add Baseline Types': 'List / Add Baseline Types', 'List / Add Impact Types': 'List / Add Impact Types', 'List / Add Services': 'List / Add Services', 'List / Add Types': 'List / Add Types', 'List Activities': 'List Activities', 'List All': 'List All', 'List All Activity Types': 'List All Activity Types', 'List All Assets': 'List All Assets', 'List All Catalog Items': 'List All Catalogue Items', 'List All Catalogs & Add Items to Catalogs': 'List All Catalogues & Add Items to Catalogues', 'List All Commitments': 'List All Commitments', 'List All Entries': 'List All Entries', 'List All Item Categories': 'List All Item Categories', 'List All Items': 'List All Items', 'List All Memberships': 'List All Memberships', 'List All Orders': 'List All Orders', 'List All Project Sites': 'List All Project Sites', 'List All Projects': 'List All Projects', 'List All Received Shipments': 'List All Received Shipments', 'List All Records': 'List All Records', 'List All Requested Items': 'List All Requested Items', 'List All Requested Skills': 'List All Requested Skills', 'List All Requests': 'List All Requests', 'List All Sent Shipments': 'List All Sent Shipments', 'List All Vehicles': 'List All Vehicles', 'List Alternative Items': 'List Alternative Items', 'List Assessment Summaries': 'List Assessment Summaries', 'List Assessments': 'List Assessments', 'List Assets': 'List Assets', 'List Availability': 'List Availability', 'List Baseline Types': 'List Baseline Types', 'List Baselines': 'List Baselines', 'List Brands': 'List Brands', 'List Budgets': 'List Budgets', 'List Bundles': 'List Bundles', 'List Camp Services': 'List Camp Services', 'List Camp Types': 'List Camp Types', 'List Camps': 'List Camps', 'List Catalog Items': 'List Catalogue Items', 'List Catalogs': 'List Catalogues', 'List Certificates': 'List Certificates', 'List Certifications': 'List Certifications', 'List Checklists': 'List Checklists', 'List Cluster Subsectors': 'List Cluster Subsectors', 'List Clusters': 'List Clusters', 'List Commitment Items': 'List Commitment Items', 'List Commitments': 'List Commitments', 'List Committed People': 'List Committed People', 'List Competency Ratings': 'List Competency Ratings', 'List Contact Information': 'List Contact Information', 'List Contacts': 'List Contacts', 'List Course Certificates': 'List Course Certificates', 'List Courses': 'List Courses', 'List Credentials': 'List Credentials', 'List Current': 'List Current', 'List Documents': 'List Documents', 'List Donors': 'List Donors', 'List Events': 'List Events', 'List Facilities': 'List Facilities', 'List Feature Classes': 'List Feature Classes', 'List Feature Layers': 'List Feature Layers', 'List Flood Reports': 'List Flood Reports', 'List GPS data': 'List GPS data', 'List Groups': 'List Groups', 'List Groups/View Members': 'List Groups/View Members', 'List Homes': 'List Homes', 'List Hospitals': 'List Hospitals', 'List Human Resources': 'List Human Resources', 'List Identities': 'List Identities', 'List Images': 'List Images', 'List Impact Assessments': 'List Impact Assessments', 'List Impact Types': 'List Impact Types', 'List Impacts': 'List Impacts', 'List Import Files': 'List Import Files', 'List Incident Reports': 'List Incident Reports', 'List Incidents': 'List Incidents', 'List Item Categories': 'List Item Categories', 'List Item Packs': 'List Item Packs', 'List Items': 'List Items', 'List Items in Inventory': 'List Items in Inventory', 'List Job Roles': 'List Job Roles', 'List Jobs': 'List Jobs', 'List Kits': 'List Kits', 'List Layers': 'List Layers', 'List Level 1 Assessments': 'List Level 1 Assessments', 'List Level 1 assessments': 'List Level 1 assessments', 'List Level 2 Assessments': 'List Level 2 Assessments', 'List Level 2 assessments': 'List Level 2 assessments', 'List Locations': 'List Locations', 'List Log Entries': 'List Log Entries', 'List Map Configurations': 'List Map Configurations', 'List Markers': 'List Markers', 'List Members': 'List Members', 'List Memberships': 'List Memberships', 'List Messages': 'List Messages', 'List Missing Persons': 'List Missing Persons', 'List Missions': 'List Missions', 'List Need Types': 'List Need Types', 'List Needs': 'List Needs', 'List Offices': 'List Offices', 'List Order Items': 'List Order Items', 'List Orders': 'List Orders', 'List Organization Domains': 'List Organisation Domains', 'List Organizations': 'List Organisations', 'List Patients': 'List Patients', 'List Personal Effects': 'List Personal Effects', 'List Persons': 'List Persons', 'List Photos': 'List Photos', 'List Population Statistics': 'List Population Statistics', 'List Positions': 'List Positions', 'List Problems': 'List Problems', 'List Project Organizations': 'List Project Organisations', 'List Project Sites': 'List Project Sites', 'List Projections': 'List Projections', 'List Projects': 'List Projects', 'List Rapid Assessments': 'List Rapid Assessments', 'List Received Items': 'List Received Items', 'List Received Shipments': 'List Received Shipments', 'List Records': 'List Records', 'List Registrations': 'List Registrations', 'List Relatives': 'List Relatives', 'List Reports': 'List Reports', 'List Repositories': 'List Repositories', 'List Request Items': 'List Request Items', 'List Requested Skills': 'List Requested Skills', 'List Requests': 'List Requests', 'List Requests for Donations': 'List Requests for Donations', 'List Requests for Volunteers': 'List Requests for Volunteers', 'List Resources': 'List Resources', 'List Rivers': 'List Rivers', 'List Roles': 'List Roles', 'List Rooms': 'List Rooms', 'List Saved Searches': 'List Saved Searches', 'List Scenarios': 'List Scenarios', 'List Sections': 'List Sections', 'List Sectors': 'List Sectors', 'List Sent Items': 'List Sent Items', 'List Sent Shipments': 'List Sent Shipments', 'List Service Profiles': 'List Service Profiles', 'List Settings': 'List Settings', 'List Shelter Services': 'List Shelter Services', 'List Shelter Types': 'List Shelter Types', 'List Shelters': 'List Shelters', 'List Skill Equivalences': 'List Skill Equivalences', 'List Skill Provisions': 'List Skill Provisions', 'List Skill Types': 'List Skill Types', 'List Skills': 'List Skills', 'List Solutions': 'List Solutions', 'List Staff Types': 'List Staff Types', 'List Status': 'List Status', 'List Subscriptions': 'List Subscriptions', 'List Subsectors': 'List Subsectors', 'List Support Requests': 'List Support Requests', 'List Tasks': 'List Tasks', 'List Teams': 'List Teams', 'List Themes': 'List Themes', 'List Tickets': 'List Tickets', 'List Trainings': 'List Trainings', 'List Units': 'List Units', 'List Users': 'List Users', 'List Vehicle Details': 'List Vehicle Details', 'List Vehicles': 'List Vehicles', 'List Warehouses': 'List Warehouses', 'List all': 'List all', 'List all Assessment Answer': 'List all Assessment Answer', 'List all Assessment Questions': 'List all Assessment Questions', 'List all Assessment Series': 'List all Assessment Series', 'List all Assessment Templates': 'List all Assessment Templates', 'List all Completed Assessment': 'List all Completed Assessment', 'List all Question Meta-Data': 'List all Question Meta-Data', 'List all Template Sections': 'List all Template Sections', 'List available Scenarios': 'List available Scenarios', 'List of Assessment Answers': 'List of Assessment Answers', 'List of Assessment Questions': 'List of Assessment Questions', 'List of Assessment Series': 'List of Assessment Series', 'List of Assessment Templates': 'List of Assessment Templates', 'List of CSV files': 'List of CSV files', 'List of CSV files uploaded': 'List of CSV files uploaded', 'List of Completed Assessments': 'List of Completed Assessments', 'List of Items': 'List of Items', 'List of Missing Persons': 'List of Missing Persons', 'List of Question Meta-Data': 'List of Question Meta-Data', 'List of Reports': 'List of Reports', 'List of Requests': 'List of Requests', 'List of Selected Answers': 'List of Selected Answers', 'List of Spreadsheets': 'List of Spreadsheets', 'List of Spreadsheets uploaded': 'List of Spreadsheets uploaded', 'List of Template Sections': 'List of Template Sections', 'List of addresses': 'List of addresses', 'List unidentified': 'List unidentified', 'List/Add': 'List/Add', 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities': 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities', 'Live Help': 'Live Help', 'Livelihood': 'Livelihood', 'Load Cleaned Data into Database': 'Load Cleaned Data into Database', 'Load Raw File into Grid': 'Load Raw File into Grid', 'Load Search': 'Load Search', 'Loading': 'Loading', 'Local Name': 'Local Name', 'Local Names': 'Local Names', 'Location': 'Location', 'Location 1': 'Location 1', 'Location 2': 'Location 2', 'Location Details': 'Location Details', 'Location Hierarchy Level 0 Name': 'Location Hierarchy Level 0 Name', 'Location Hierarchy Level 1 Name': 'Location Hierarchy Level 1 Name', 'Location Hierarchy Level 2 Name': 'Location Hierarchy Level 2 Name', 'Location Hierarchy Level 3 Name': 'Location Hierarchy Level 3 Name', 'Location Hierarchy Level 4 Name': 'Location Hierarchy Level 4 Name', 'Location Hierarchy Level 5 Name': 'Location Hierarchy Level 5 Name', 'Location added': 'Location added', 'Location deleted': 'Location deleted', 'Location group cannot be a parent.': 'Location group cannot be a parent.', 'Location group cannot have a parent.': 'Location group cannot have a parent.', 'Location groups can be used in the Regions menu.': 'Location groups can be used in the Regions menu.', 'Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group.': 'Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group.', 'Location updated': 'Location updated', 'Location: ': 'Location: ', 'Locations': 'Locations', 'Locations of this level need to have a parent of level': 'Locations of this level need to have a parent of level', 'Lockdown': 'Lockdown', 'Log': 'Log', 'Log Entry': 'Log Entry', 'Log Entry Deleted': 'Log Entry Deleted', 'Log Entry Details': 'Log Entry Details', 'Log entry added': 'Log entry added', 'Log entry deleted': 'Log entry deleted', 'Log entry updated': 'Log entry updated', 'Login': 'Login', 'Logistics': 'Logistics', 'Logo': 'Logo', 'Logo file %s missing!': 'Logo file %s missing!', 'Logout': 'Logout', 'Longitude': 'Longitude', 'Longitude is West - East (sideways).': 'Longitude is West - East (sideways).', 'Longitude is West-East (sideways).': 'Longitude is West-East (sideways).', 'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.', 'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.', 'Longitude of Map Center': 'Longitude of Map Center', 'Longitude of far eastern end of the region of interest.': 'Longitude of far eastern end of the region of interest.', 'Longitude of far western end of the region of interest.': 'Longitude of far western end of the region of interest.', 'Longitude should be between': 'Longitude should be between', 'Looting': 'Looting', 'Lost': 'Lost', 'Lost Password': '<PASSWORD>', 'Low': 'Low', 'Magnetic Storm': 'Magnetic Storm', 'Major Damage': 'Major Damage', 'Major expenses': 'Major expenses', 'Major outward damage': 'Major outward damage', 'Make Commitment': 'Make Commitment', 'Make New Commitment': 'Make New Commitment', 'Make Request': 'Make Request', 'Make a Request for Donations': 'Make a Request for Donations', 'Make a Request for Volunteers': 'Make a Request for Volunteers', 'Make preparations per the <instruction>': 'Make preparations per the <instruction>', 'Male': 'Male', 'Manage Events': 'Manage Events', 'Manage Users & Roles': 'Manage Users & Roles', 'Manage Vehicles': 'Manage Vehicles', 'Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.': 'Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.', 'Manage requests of hospitals for assistance.': 'Manage requests of hospitals for assistance.', 'Manager': 'Manager', 'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).', 'Mandatory. The URL to access the service.': 'Mandatory. The URL to access the service.', 'Manual Synchronization': 'Manual Synchronisation', 'Many': 'Many', 'Map': 'Map', 'Map Center Latitude': 'Map Center Latitude', 'Map Center Longitude': 'Map Center Longitude', 'Map Configuration': 'Map Configuration', 'Map Configuration Details': 'Map Configuration Details', 'Map Configuration added': 'Map Configuration added', 'Map Configuration deleted': 'Map Configuration deleted', 'Map Configuration removed': 'Map Configuration removed', 'Map Configuration updated': 'Map Configuration updated', 'Map Configurations': 'Map Configurations', 'Map Height': 'Map Height', 'Map Service Catalog': 'Map Service Catalogue', 'Map Settings': 'Map Settings', 'Map Viewing Client': 'Map Viewing Client', 'Map Width': 'Map Width', 'Map Zoom': 'Map Zoom', 'Map of Hospitals': 'Map of Hospitals', 'MapMaker Hybrid Layer': 'MapMaker Hybrid Layer', 'MapMaker Layer': 'MapMaker Layer', 'Maps': 'Maps', 'Marine Security': 'Marine Security', 'Marital Status': 'Marital Status', 'Marker': 'Marker', 'Marker Details': 'Marker Details', 'Marker added': 'Marker added', 'Marker deleted': 'Marker deleted', 'Marker updated': 'Marker updated', 'Markers': 'Markers', 'Master': 'Master', 'Master Message Log': 'Master Message Log', 'Master Message Log to process incoming reports & requests': 'Master Message Log to process incoming reports & requests', 'Match Percentage': 'Match Percentage', 'Match Requests': 'Match Requests', 'Match percentage indicates the % match between these two records': 'Match percentage indicates the % match between these two records', 'Match?': 'Match?', 'Matching Catalog Items': 'Matching Catalogue Items', 'Matching Items': 'Matching Items', 'Matching Records': 'Matching Records', 'Maximum Location Latitude': 'Maximum Location Latitude', 'Maximum Location Longitude': 'Maximum Location Longitude', 'Measure Area: Click the points around the polygon & end with a double-click': 'Measure Area: Click the points around the polygon & end with a double-click', 'Measure Length: Click the points along the path & end with a double-click': 'Measure Length: Click the points along the path & end with a double-click', 'Medical and public health': 'Medical and public health', 'Medium': 'Medium', 'Megabytes per Month': 'Megabytes per Month', 'Members': 'Members', 'Membership': 'Membership', 'Membership Details': 'Membership Details', 'Membership added': 'Membership added', 'Membership deleted': 'Membership deleted', 'Membership updated': 'Membership updated', 'Memberships': 'Memberships', 'Message': 'Message', 'Message Details': 'Message Details', 'Message Variable': 'Message Variable', 'Message added': 'Message added', 'Message deleted': 'Message deleted', 'Message updated': 'Message updated', 'Message variable': 'Message variable', 'Messages': 'Messages', 'Messaging': 'Messaging', 'Meteorite': 'Meteorite', 'Meteorological (inc. flood)': 'Meteorological (inc. flood)', 'Method used': 'Method used', 'Middle Name': 'Middle Name', 'Migrants or ethnic minorities': 'Migrants or ethnic minorities', 'Mileage': 'Mileage', 'Military': 'Military', 'Minimum Location Latitude': 'Minimum Location Latitude', 'Minimum Location Longitude': 'Minimum Location Longitude', 'Minimum shift time is 6 hours': 'Minimum shift time is 6 hours', 'Minor Damage': 'Minor Damage', 'Minor/None': 'Minor/None', 'Minorities participating in coping activities': 'Minorities participating in coping activities', 'Minute': 'Minute', 'Minutes must be a number between 0 and 60': 'Minutes must be a number between 0 and 60', 'Minutes per Month': 'Minutes per Month', 'Minutes should be a number greater than 0 and less than 60': 'Minutes should be a number greater than 0 and less than 60', 'Miscellaneous': 'Miscellaneous', 'Missing': 'Missing', 'Missing Person': 'Missing Person', 'Missing Person Details': 'Missing Person Details', 'Missing Person Registry': 'Missing Person Registry', 'Missing Persons': 'Missing Persons', 'Missing Persons Registry': 'Missing Persons Registry', 'Missing Persons Report': 'Missing Persons Report', 'Missing Report': 'Missing Report', 'Missing Senior Citizen': 'Missing Senior Citizen', 'Missing Vulnerable Person': 'Missing Vulnerable Person', 'Mission Details': 'Mission Details', 'Mission Record': 'Mission Record', 'Mission added': 'Mission added', 'Mission deleted': 'Mission deleted', 'Mission updated': 'Mission updated', 'Missions': 'Missions', 'Mobile': 'Mobile', 'Mobile Basic Assessment': 'Mobile Basic Assessment', 'Mobile Phone': 'Mobile Phone', 'Mode': 'Mode', 'Model/Type': 'Model/Type', 'Modem settings updated': 'Modem settings updated', 'Moderate': 'Moderate', 'Moderator': 'Moderator', 'Modify Information on groups and individuals': 'Modify Information on groups and individuals', 'Modifying data in spreadsheet before importing it to the database': 'Modifying data in spreadsheet before importing it to the database', 'Module': 'Module', 'Module provides access to information on current Flood Levels.': 'Module provides access to information on current Flood Levels.', 'Monday': 'Monday', 'Monthly Cost': 'Monthly Cost', 'Monthly Salary': 'Monthly Salary', 'Months': 'Months', 'Morgue': 'Morgue', 'Morgue Details': 'Morgue Details', 'Morgue Status': 'Morgue Status', 'Morgue Units Available': 'Morgue Units Available', 'Morgues': 'Morgues', 'Mosque': 'Mosque', 'Motorcycle': 'Motorcycle', 'Moustache': 'Moustache', 'MultiPolygon': 'MultiPolygon', 'Multiple': 'Multiple', 'Multiple Matches': 'Multiple Matches', 'Muslim': 'Muslim', 'Must a location have a parent location?': 'Must a location have a parent location?', 'My Details': 'My Details', 'My Tasks': 'My Tasks', 'N/A': 'N/A', 'NO': 'NO', 'NZSEE Level 1': 'NZSEE Level 1', 'NZSEE Level 2': 'NZSEE Level 2', 'Name': 'Name', 'Name and/or ID': 'Name and/or ID', 'Name field is required!': 'Name field is required!', 'Name of the file (& optional sub-path) located in static which should be used for the background of the header.': 'Name of the file (& optional sub-path) located in static which should be used for the background of the header.', 'Name of the file (& optional sub-path) located in static which should be used for the top-left image.': 'Name of the file (& optional sub-path) located in static which should be used for the top-left image.', 'Name of the file (& optional sub-path) located in views which should be used for footer.': 'Name of the file (& optional sub-path) located in views which should be used for footer.', 'Name of the person in local language and script (optional).': 'Name of the person in local language and script (optional).', 'Name of the repository (for you own reference)': 'Name of the repository (for you own reference)', 'Name, Org and/or ID': 'Name, Org and/or ID', 'Names can be added in multiple languages': 'Names can be added in multiple languages', 'National': 'National', 'National ID Card': 'National ID Card', 'National NGO': 'National NGO', 'Nationality': 'Nationality', 'Nationality of the person.': 'Nationality of the person.', 'Nautical Accident': 'Nautical Accident', 'Nautical Hijacking': 'Nautical Hijacking', 'Need Type': 'Need Type', 'Need Type Details': 'Need Type Details', 'Need Type added': 'Need Type added', 'Need Type deleted': 'Need Type deleted', 'Need Type updated': 'Need Type updated', 'Need Types': 'Need Types', "Need a 'url' argument!": "Need a 'url' argument!", 'Need added': 'Need added', 'Need deleted': 'Need deleted', 'Need to be logged-in to be able to submit assessments': 'Need to be logged-in to be able to submit assessments', 'Need to configure Twitter Authentication': 'Need to configure Twitter Authentication', 'Need to specify a Budget!': 'Need to specify a Budget!', 'Need to specify a Kit!': 'Need to specify a Kit!', 'Need to specify a Resource!': 'Need to specify a Resource!', 'Need to specify a bundle!': 'Need to specify a bundle!', 'Need to specify a group!': 'Need to specify a group!', 'Need to specify a location to search for.': 'Need to specify a location to search for.', 'Need to specify a role!': 'Need to specify a role!', 'Need to specify a table!': 'Need to specify a table!', 'Need to specify a user!': 'Need to specify a user!', 'Need updated': 'Need updated', 'Needs': 'Needs', 'Needs Details': 'Needs Details', 'Needs Maintenance': 'Needs Maintenance', 'Needs to reduce vulnerability to violence': 'Needs to reduce vulnerability to violence', 'Negative Flow Isolation': 'Negative Flow Isolation', 'Neighborhood': 'Neighborhood', 'Neighbourhood': 'Neighbourhood', 'Neighbouring building hazard': 'Neighbouring building hazard', 'Neonatal ICU': 'Neonatal ICU', 'Neonatology': 'Neonatology', 'Network': 'Network', 'Neurology': 'Neurology', 'New': 'New', 'New Assessment': 'New Assessment', 'New Assessment reported from': 'New Assessment reported from', 'New Certificate': 'New Certificate', 'New Checklist': 'New Checklist', 'New Entry': 'New Entry', 'New Event': 'New Event', 'New Home': 'New Home', 'New Item Category': 'New Item Category', 'New Job Role': 'New Job Role', 'New Location': 'New Location', 'New Location Group': 'New Location Group', 'New Patient': 'New Patient', 'New Record': 'New Record', 'New Relative': 'New Relative', 'New Request': 'New Request', 'New Scenario': 'New Scenario', 'New Skill': 'New Skill', 'New Solution Choice': 'New Solution Choice', 'New Staff Member': 'New Staff Member', 'New Support Request': 'New Support Request', 'New Team': 'New Team', 'New Ticket': 'New Ticket', 'New Training Course': 'New Training Course', 'New Volunteer': 'New Volunteer', 'New cases in the past 24h': 'New cases in the past 24h', 'Next': 'Next', 'Next View': 'Next View', 'No': 'No', 'No Activities Found': 'No Activities Found', 'No Activities currently registered in this event': 'No Activities currently registered in this event', 'No Alternative Items currently registered': 'No Alternative Items currently registered', 'No Assessment Answers currently registered': 'No Assessment Answers currently registered', 'No Assessment Question currently registered': 'No Assessment Question currently registered', 'No Assessment Series currently registered': 'No Assessment Series currently registered', 'No Assessment Summaries currently registered': 'No Assessment Summaries currently registered', 'No Assessment Template currently registered': 'No Assessment Template currently registered', 'No Assessments currently registered': 'No Assessments currently registered', 'No Assets currently registered': 'No Assets currently registered', 'No Assets currently registered in this event': 'No Assets currently registered in this event', 'No Assets currently registered in this scenario': 'No Assets currently registered in this scenario', 'No Baseline Types currently registered': 'No Baseline Types currently registered', 'No Baselines currently registered': 'No Baselines currently registered', 'No Brands currently registered': 'No Brands currently registered', 'No Budgets currently registered': 'No Budgets currently registered', 'No Bundles currently registered': 'No Bundles currently registered', 'No Camp Services currently registered': 'No Camp Services currently registered', 'No Camp Types currently registered': 'No Camp Types currently registered', 'No Camps currently registered': 'No Camps currently registered', 'No Catalog Items currently registered': 'No Catalogue Items currently registered', 'No Catalogs currently registered': 'No Catalogues currently registered', 'No Checklist available': 'No Checklist available', 'No Cluster Subsectors currently registered': 'No Cluster Subsectors currently registered', 'No Clusters currently registered': 'No Clusters currently registered', 'No Commitment Items currently registered': 'No Commitment Items currently registered', 'No Commitments': 'No Commitments', 'No Completed Assessments currently registered': 'No Completed Assessments currently registered', 'No Credentials currently set': 'No Credentials currently set', 'No Details currently registered': 'No Details currently registered', 'No Documents currently attached to this request': 'No Documents currently attached to this request', 'No Documents found': 'No Documents found', 'No Donors currently registered': 'No Donors currently registered', 'No Events currently registered': 'No Events currently registered', 'No Facilities currently registered in this event': 'No Facilities currently registered in this event', 'No Facilities currently registered in this scenario': 'No Facilities currently registered in this scenario', 'No Feature Classes currently defined': 'No Feature Classes currently defined', 'No Feature Layers currently defined': 'No Feature Layers currently defined', 'No Flood Reports currently registered': 'No Flood Reports currently registered', 'No GPS data currently registered': 'No GPS data currently registered', 'No Groups currently defined': 'No Groups currently defined', 'No Groups currently registered': 'No Groups currently registered', 'No Homes currently registered': 'No Homes currently registered', 'No Hospitals currently registered': 'No Hospitals currently registered', 'No Human Resources currently registered in this event': 'No Human Resources currently registered in this event', 'No Human Resources currently registered in this scenario': 'No Human Resources currently registered in this scenario', 'No Identification Report Available': 'No Identification Report Available', 'No Identities currently registered': 'No Identities currently registered', 'No Image': 'No Image', 'No Images currently registered': 'No Images currently registered', 'No Impact Types currently registered': 'No Impact Types currently registered', 'No Impacts currently registered': 'No Impacts currently registered', 'No Import Files currently uploaded': 'No Import Files currently uploaded', 'No Incident Reports currently registered': 'No Incident Reports currently registered', 'No Incidents currently registered in this event': 'No Incidents currently registered in this event', 'No Incoming Shipments': 'No Incoming Shipments', 'No Inventories currently have suitable alternative items in stock': 'No Inventories currently have suitable alternative items in stock', 'No Inventories currently have this item in stock': 'No Inventories currently have this item in stock', 'No Item Categories currently registered': 'No Item Categories currently registered', 'No Item Packs currently registered': 'No Item Packs currently registered', 'No Items currently registered': 'No Items currently registered', 'No Items currently registered in this Inventory': 'No Items currently registered in this Inventory', 'No Kits currently registered': 'No Kits currently registered', 'No Level 1 Assessments currently registered': 'No Level 1 Assessments currently registered', 'No Level 2 Assessments currently registered': 'No Level 2 Assessments currently registered', 'No Locations currently available': 'No Locations currently available', 'No Locations currently registered': 'No Locations currently registered', 'No Map Configurations currently defined': 'No Map Configurations currently defined', 'No Map Configurations currently registered in this event': 'No Map Configurations currently registered in this event', 'No Map Configurations currently registered in this scenario': 'No Map Configurations currently registered in this scenario', 'No Markers currently available': 'No Markers currently available', 'No Match': 'No Match', 'No Matching Catalog Items': 'No Matching Catalogue Items', 'No Matching Items': 'No Matching Items', 'No Matching Records': 'No Matching Records', 'No Members currently registered': 'No Members currently registered', 'No Memberships currently defined': 'No Memberships currently defined', 'No Memberships currently registered': 'No Memberships currently registered', 'No Messages currently in Outbox': 'No Messages currently in Outbox', 'No Need Types currently registered': 'No Need Types currently registered', 'No Needs currently registered': 'No Needs currently registered', 'No Offices currently registered': 'No Offices currently registered', 'No Order Items currently registered': 'No Order Items currently registered', 'No Orders registered': 'No Orders registered', 'No Organization Domains currently registered': 'No Organisation Domains currently registered', 'No Organizations currently registered': 'No Organisations currently registered', 'No Organizations for this Project': 'No Organisations for this Project', 'No Packs for Item': 'No Packs for Item', 'No Patients currently registered': 'No Patients currently registered', 'No People currently committed': 'No People currently committed', 'No People currently registered in this camp': 'No People currently registered in this camp', 'No People currently registered in this shelter': 'No People currently registered in this shelter', 'No Persons currently registered': 'No Persons currently registered', 'No Persons currently reported missing': 'No Persons currently reported missing', 'No Persons found': 'No Persons found', 'No Photos found': 'No Photos found', 'No Picture': 'No Picture', 'No Population Statistics currently registered': 'No Population Statistics currently registered', 'No Presence Log Entries currently registered': 'No Presence Log Entries currently registered', 'No Problems currently defined': 'No Problems currently defined', 'No Projections currently defined': 'No Projections currently defined', 'No Projects currently registered': 'No Projects currently registered', 'No Question Meta-Data currently registered': 'No Question Meta-Data currently registered', 'No Rapid Assessments currently registered': 'No Rapid Assessments currently registered', 'No Ratings for Skill Type': 'No Ratings for Skill Type', 'No Received Items currently registered': 'No Received Items currently registered', 'No Received Shipments': 'No Received Shipments', 'No Records currently available': 'No Records currently available', 'No Relatives currently registered': 'No Relatives currently registered', 'No Request Items currently registered': 'No Request Items currently registered', 'No Requests': 'No Requests', 'No Requests for Donations': 'No Requests for Donations', 'No Requests for Volunteers': 'No Requests for Volunteers', 'No Rivers currently registered': 'No Rivers currently registered', 'No Roles currently defined': 'No Roles currently defined', 'No Rooms currently registered': 'No Rooms currently registered', 'No Scenarios currently registered': 'No Scenarios currently registered', 'No Search saved': 'No Search saved', 'No Sections currently registered': 'No Sections currently registered', 'No Sectors currently registered': 'No Sectors currently registered', 'No Sent Items currently registered': 'No Sent Items currently registered', 'No Sent Shipments': 'No Sent Shipments', 'No Settings currently defined': 'No Settings currently defined', 'No Shelter Services currently registered': 'No Shelter Services currently registered', 'No Shelter Types currently registered': 'No Shelter Types currently registered', 'No Shelters currently registered': 'No Shelters currently registered', 'No Skills currently requested': 'No Skills currently requested', 'No Solutions currently defined': 'No Solutions currently defined', 'No Staff Types currently registered': 'No Staff Types currently registered', 'No Subscription available': 'No Subscription available', 'No Subsectors currently registered': 'No Subsectors currently registered', 'No Support Requests currently registered': 'No Support Requests currently registered', 'No Tasks currently registered in this event': 'No Tasks currently registered in this event', 'No Tasks currently registered in this scenario': 'No Tasks currently registered in this scenario', 'No Teams currently registered': 'No Teams currently registered', 'No Template Section currently registered': 'No Template Section currently registered', 'No Themes currently defined': 'No Themes currently defined', 'No Tickets currently registered': 'No Tickets currently registered', 'No Users currently registered': 'No Users currently registered', 'No Vehicle Details currently defined': 'No Vehicle Details currently defined', 'No Vehicles currently registered': 'No Vehicles currently registered', 'No Warehouses currently registered': 'No Warehouses currently registered', 'No access at all': 'No access at all', 'No access to this record!': 'No access to this record!', 'No action recommended': 'No action recommended', 'No contact information available': 'No contact information available', 'No contact method found': 'No contact method found', 'No contacts currently registered': 'No contacts currently registered', 'No data in this table - cannot create PDF!': 'No data in this table - cannot create PDF!', 'No databases in this application': 'No databases in this application', 'No dead body reports available': 'No dead body reports available', 'No entries found': 'No entries found', 'No entry available': 'No entry available', 'No forms to the corresponding resource have been downloaded yet.': 'No forms to the corresponding resource have been downloaded yet.', 'No jobs configured': 'No jobs configured', 'No jobs configured yet': 'No jobs configured yet', 'No match': 'No match', 'No matching records found': 'No matching records found', 'No messages in the system': 'No messages in the system', 'No person record found for current user.': 'No person record found for current user.', 'No problem group defined yet': 'No problem group defined yet', 'No reports available.': 'No reports available.', 'No reports currently available': 'No reports currently available', 'No repositories configured': 'No repositories configured', 'No requests found': 'No requests found', 'No resources configured yet': 'No resources configured yet', 'No resources currently reported': 'No resources currently reported', 'No service profile available': 'No service profile available', 'No skills currently set': 'No skills currently set', 'No staff or volunteers currently registered': 'No staff or volunteers currently registered', 'No status information available': 'No status information available', 'No tasks currently assigned': 'No tasks currently assigned', 'No tasks currently registered': 'No tasks currently registered', 'No units currently registered': 'No units currently registered', 'No volunteer availability registered': 'No volunteer availability registered', 'Non-structural Hazards': 'Non-structural Hazards', 'None': 'None', 'None (no such record)': 'None (no such record)', 'Noodles': 'Noodles', 'Normal': 'Normal', 'Not Applicable': 'Not Applicable', 'Not Authorised!': 'Not Authorised!', 'Not Possible': 'Not Possible', 'Not authorised!': 'Not authorised!', 'Not installed or incorrectly configured.': 'Not installed or incorrectly configured.', 'Note that this list only shows active volunteers. To see all people registered in the system, search from this screen instead': 'Note that this list only shows active volunteers. To see all people registered in the system, search from this screen instead', 'Notes': 'Notes', 'Notice to Airmen': 'Notice to Airmen', 'Number of Patients': 'Number of Patients', 'Number of People Required': 'Number of People Required', 'Number of additional beds of that type expected to become available in this unit within the next 24 hours.': 'Number of additional beds of that type expected to become available in this unit within the next 24 hours.', 'Number of alternative places for studying': 'Number of alternative places for studying', 'Number of available/vacant beds of that type in this unit at the time of reporting.': 'Number of available/vacant beds of that type in this unit at the time of reporting.', 'Number of bodies found': 'Number of bodies found', 'Number of deaths during the past 24 hours.': 'Number of deaths during the past 24 hours.', 'Number of discharged patients during the past 24 hours.': 'Number of discharged patients during the past 24 hours.', 'Number of doctors': 'Number of doctors', 'Number of in-patients at the time of reporting.': 'Number of in-patients at the time of reporting.', 'Number of newly admitted patients during the past 24 hours.': 'Number of newly admitted patients during the past 24 hours.', 'Number of non-medical staff': 'Number of non-medical staff', 'Number of nurses': 'Number of nurses', 'Number of private schools': 'Number of private schools', 'Number of public schools': 'Number of public schools', 'Number of religious schools': 'Number of religious schools', 'Number of residential units': 'Number of residential units', 'Number of residential units not habitable': 'Number of residential units not habitable', 'Number of vacant/available beds in this hospital. Automatically updated from daily reports.': 'Number of vacant/available beds in this hospital. Automatically updated from daily reports.', 'Number of vacant/available units to which victims can be transported immediately.': 'Number of vacant/available units to which victims can be transported immediately.', 'Number or Label on the identification tag this person is wearing (if any).': 'Number or Label on the identification tag this person is wearing (if any).', 'Number or code used to mark the place of find, e.g. flag code, grid coordinates, site reference number or similar (if available)': 'Number or code used to mark the place of find, e.g. flag code, grid coordinates, site reference number or similar (if available)', 'Number/Percentage of affected population that is Female & Aged 0-5': 'Number/Percentage of affected population that is Female & Aged 0-5', 'Number/Percentage of affected population that is Female & Aged 13-17': 'Number/Percentage of affected population that is Female & Aged 13-17', 'Number/Percentage of affected population that is Female & Aged 18-25': 'Number/Percentage of affected population that is Female & Aged 18-25', 'Number/Percentage of affected population that is Female & Aged 26-60': 'Number/Percentage of affected population that is Female & Aged 26-60', 'Number/Percentage of affected population that is Female & Aged 6-12': 'Number/Percentage of affected population that is Female & Aged 6-12', 'Number/Percentage of affected population that is Female & Aged 61+': 'Number/Percentage of affected population that is Female & Aged 61+', 'Number/Percentage of affected population that is Male & Aged 0-5': 'Number/Percentage of affected population that is Male & Aged 0-5', 'Number/Percentage of affected population that is Male & Aged 13-17': 'Number/Percentage of affected population that is Male & Aged 13-17', 'Number/Percentage of affected population that is Male & Aged 18-25': 'Number/Percentage of affected population that is Male & Aged 18-25', 'Number/Percentage of affected population that is Male & Aged 26-60': 'Number/Percentage of affected population that is Male & Aged 26-60', 'Number/Percentage of affected population that is Male & Aged 6-12': 'Number/Percentage of affected population that is Male & Aged 6-12', 'Number/Percentage of affected population that is Male & Aged 61+': 'Number/Percentage of affected population that is Male & Aged 61+', 'Numeric Question:': 'Numeric Question:', 'Nursery Beds': 'Nursery Beds', 'Nutrition': 'Nutrition', 'Nutrition problems': 'Nutrition problems', 'OCR Form Review': 'OCR Form Review', 'OK': 'OK', 'OR Reason': 'OR Reason', 'OR Status': 'OR Status', 'OR Status Reason': 'OR Status Reason', 'Objectives': 'Objectives', 'Observer': 'Observer', 'Obsolete': 'Obsolete', 'Obstetrics/Gynecology': 'Obstetrics/Gynecology', 'Office': 'Office', 'Office Address': 'Office Address', 'Office Details': 'Office Details', 'Office Phone': 'Office Phone', 'Office added': 'Office added', 'Office deleted': 'Office deleted', 'Office updated': 'Office updated', 'Offices': 'Offices', 'Older people as primary caregivers of children': 'Older people as primary caregivers of children', 'Older people in care homes': 'Older people in care homes', 'Older people participating in coping activities': 'Older people participating in coping activities', 'Older person (>60 yrs)': 'Older person (>60 yrs)', 'On by default?': 'On by default?', 'On by default? (only applicable to Overlays)': 'On by default? (only applicable to Overlays)', 'One Time Cost': 'One Time Cost', 'One time cost': 'One time cost', 'One-time': 'One-time', 'One-time costs': 'One-time costs', 'Oops! Something went wrong...': 'Oops! Something went wrong...', 'Oops! something went wrong on our side.': 'Oops! something went wrong on our side.', 'Opacity (1 for opaque, 0 for fully-transparent)': 'Opacity (1 for opaque, 0 for fully-transparent)', 'Open': 'Open', 'Open area': 'Open area', 'Open recent': 'Open recent', 'Operating Rooms': 'Operating Rooms', 'Optical Character Recognition': 'Optical Character Recognition', 'Optical Character Recognition for reading the scanned handwritten paper forms.': 'Optical Character Recognition for reading the scanned handwritten paper forms.', 'Optional': 'Optional', 'Optional Subject to put into Email - can be used as a Security Password by the service provider': 'Optional Subject to put into Email - can be used as a Security Password by the service provider', 'Optional link to an Incident which this Assessment was triggered by.': 'Optional link to an Incident which this Assessment was triggered by.', 'Optional selection of a MapServer map.': 'Optional selection of a MapServer map.', 'Optional selection of a background color.': 'Optional selection of a background colour.', 'Optional selection of an alternate style.': 'Optional selection of an alternate style.', 'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.': 'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.', 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).': 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).', 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.': 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.', 'Optional. The name of an element whose contents should be put into Popups.': 'Optional. The name of an element whose contents should be put into Popups.', "Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.": "Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.", 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.': 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.', 'Options': 'Options', 'Order': 'Order', 'Order Created': 'Order Created', 'Order Details': 'Order Details', 'Order Item Details': 'Order Item Details', 'Order Item updated': 'Order Item updated', 'Order Items': 'Order Items', 'Order canceled': 'Order canceled', 'Order updated': 'Order updated', 'Orders': 'Orders', 'Organization': 'Organisation', 'Organization Details': 'Organisation Details', 'Organization Domain Details': 'Organisation Domain Details', 'Organization Domain added': 'Organisation Domain added', 'Organization Domain deleted': 'Organisation Domain deleted', 'Organization Domain updated': 'Organisation Domain updated', 'Organization Domains': 'Organisation Domains', 'Organization Registry': 'Organisation Registry', 'Organization added': 'Organisation added', 'Organization added to Project': 'Organisation added to Project', 'Organization deleted': 'Organisation deleted', 'Organization removed from Project': 'Organisation removed from Project', 'Organization updated': 'Organisation updated', 'Organizational Development': 'Organisational Development', 'Organizations': 'Organisations', 'Origin': 'Origin', 'Origin of the separated children': 'Origin of the separated children', 'Other': 'Other', 'Other (describe)': 'Other (describe)', 'Other (specify)': 'Other (specify)', 'Other Evidence': 'Other Evidence', 'Other Faucet/Piped Water': 'Other Faucet/Piped Water', 'Other Isolation': 'Other Isolation', 'Other Name': 'Other Name', 'Other activities of boys 13-17yrs': 'Other activities of boys 13-17yrs', 'Other activities of boys 13-17yrs before disaster': 'Other activities of boys 13-17yrs before disaster', 'Other activities of boys <12yrs': 'Other activities of boys <12yrs', 'Other activities of boys <12yrs before disaster': 'Other activities of boys <12yrs before disaster', 'Other activities of girls 13-17yrs': 'Other activities of girls 13-17yrs', 'Other activities of girls 13-17yrs before disaster': 'Other activities of girls 13-17yrs before disaster', 'Other activities of girls<12yrs': 'Other activities of girls<12yrs', 'Other activities of girls<12yrs before disaster': 'Other activities of girls<12yrs before disaster', 'Other alternative infant nutrition in use': 'Other alternative infant nutrition in use', 'Other alternative places for study': 'Other alternative places for study', 'Other assistance needed': 'Other assistance needed', 'Other assistance, Rank': 'Other assistance, Rank', 'Other current health problems, adults': 'Other current health problems, adults', 'Other current health problems, children': 'Other current health problems, children', 'Other events': 'Other events', 'Other factors affecting school attendance': 'Other factors affecting school attendance', 'Other major expenses': 'Other major expenses', 'Other non-food items': 'Other non-food items', 'Other recommendations': 'Other recommendations', 'Other residential': 'Other residential', 'Other school assistance received': 'Other school assistance received', 'Other school assistance, details': 'Other school assistance, details', 'Other school assistance, source': 'Other school assistance, source', 'Other settings can only be set by editing a file on the server': 'Other settings can only be set by editing a file on the server', 'Other side dishes in stock': 'Other side dishes in stock', 'Other types of water storage containers': 'Other types of water storage containers', 'Other ways to obtain food': 'Other ways to obtain food', 'Outbound Mail settings are configured in models/000_config.py.': 'Outbound Mail settings are configured in models/000_config.py.', 'Outbox': 'Outbox', 'Outgoing SMS Handler': 'Outgoing SMS Handler', 'Outgoing SMS handler': 'Outgoing SMS handler', 'Overall Hazards': 'Overall Hazards', 'Overhead falling hazard': 'Overhead falling hazard', 'Overland Flow Flood': 'Overland Flow Flood', 'Overlays': 'Overlays', 'Owned Resources': 'Owned Resources', 'PAHO UID': 'PAHO UID', 'PDAM': 'PDAM', 'PDF File': 'PDF File', 'PIN': 'PIN', 'PIN number ': 'PIN number ', 'PL Women': 'PL Women', 'Pack': 'Pack', 'Packs': 'Packs', 'Page': 'Page', 'Pan Map: keep the left mouse button pressed and drag the map': 'Pan Map: keep the left mouse button pressed and drag the map', 'Parameters': 'Parameters', 'Parapets, ornamentation': 'Parapets, ornamentation', 'Parent': 'Parent', 'Parent Office': 'Parent Office', "Parent level should be higher than this record's level. Parent level is": "Parent level should be higher than this record's level. Parent level is", 'Parent needs to be of the correct level': 'Parent needs to be of the correct level', 'Parent needs to be set': 'Parent needs to be set', 'Parent needs to be set for locations of level': 'Parent needs to be set for locations of level', 'Parents/Caregivers missing children': 'Parents/Caregivers missing children', 'Parking Area': 'Parking Area', 'Partial': 'Partial', 'Participant': 'Participant', 'Partner National Society': 'Partner National Society', 'Pass': 'Pass', 'Passport': 'Passport', 'Password': 'Password', "Password fields don't match": "Password fields don't match", 'Password to use for authentication at the remote site': 'Password to use for authentication at the remote site', 'Path': 'Path', 'Pathology': 'Pathology', 'Patient': 'Patient', 'Patient Details': 'Patient Details', 'Patient Tracking': 'Patient Tracking', 'Patient added': 'Patient added', 'Patient deleted': 'Patient deleted', 'Patient updated': 'Patient updated', 'Patients': 'Patients', 'Pediatric ICU': 'Pediatric ICU', 'Pediatric Psychiatric': 'Pediatric Psychiatric', 'Pediatrics': 'Pediatrics', 'Pending': 'Pending', 'People': 'People', 'People Needing Food': 'People Needing Food', 'People Needing Shelter': 'People Needing Shelter', 'People Needing Water': 'People Needing Water', 'People Trapped': 'People Trapped', 'Performance Rating': 'Performance Rating', 'Person': 'Person', 'Person 1': 'Person 1', 'Person 1, Person 2 are the potentially duplicate records': 'Person 1, Person 2 are the potentially duplicate records', 'Person 2': 'Person 2', 'Person De-duplicator': 'Person De-duplicator', 'Person Details': 'Person Details', 'Person Name': 'Person Name', 'Person Registry': 'Person Registry', 'Person added': 'Person added', 'Person added to Commitment': 'Person added to Commitment', 'Person deleted': 'Person deleted', 'Person details updated': 'Person details updated', 'Person interviewed': 'Person interviewed', 'Person must be specified!': 'Person must be specified!', 'Person removed from Commitment': 'Person removed from Commitment', 'Person who has actually seen the person/group.': 'Person who has actually seen the person/group.', 'Person/Group': 'Person/Group', 'Personal Data': 'Personal Data', 'Personal Effects': 'Personal Effects', 'Personal Effects Details': 'Personal Effects Details', 'Personal Map': 'Personal Map', 'Personal Profile': 'Personal Profile', 'Personal impact of disaster': 'Personal impact of disaster', 'Persons': 'Persons', 'Persons in institutions': 'Persons in institutions', 'Persons with disability (mental)': 'Persons with disability (mental)', 'Persons with disability (physical)': 'Persons with disability (physical)', 'Phone': 'Phone', 'Phone 1': 'Phone 1', 'Phone 2': 'Phone 2', 'Phone number is required': 'Phone number is required', "Phone number to donate to this organization's relief efforts.": "Phone number to donate to this organization's relief efforts.", 'Phone/Business': 'Phone/Business', 'Phone/Emergency': 'Phone/Emergency', 'Phone/Exchange (Switchboard)': 'Phone/Exchange (Switchboard)', 'Photo': 'Photo', 'Photo Details': 'Photo Details', 'Photo Taken?': 'Photo Taken?', 'Photo added': 'Photo added', 'Photo deleted': 'Photo deleted', 'Photo updated': 'Photo updated', 'Photograph': 'Photograph', 'Photos': 'Photos', 'Physical Description': 'Physical Description', 'Physical Safety': 'Physical Safety', 'Picture': 'Picture', 'Picture upload and finger print upload facility': 'Picture upload and finger print upload facility', 'Place': 'Place', 'Place of Recovery': 'Place of Recovery', 'Place on Map': 'Place on Map', 'Places for defecation': 'Places for defecation', 'Places the children have been sent to': 'Places the children have been sent to', 'Playing': 'Playing', "Please come back after sometime if that doesn't help.": "Please come back after sometime if that doesn't help.", 'Please enter a first name': 'Please enter a first name', 'Please enter a number only': 'Please enter a number only', 'Please enter a site OR a location': 'Please enter a site OR a location', 'Please enter a valid email address': 'Please enter a valid email address', 'Please enter the first few letters of the Person/Group for the autocomplete.': 'Please enter the first few letters of the Person/Group for the autocomplete.', 'Please enter the recipient': 'Please enter the recipient', 'Please fill this!': 'Please fill this!', 'Please give an estimated figure about how many bodies have been found.': 'Please give an estimated figure about how many bodies have been found.', 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.': 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.', 'Please report here where you are:': 'Please report here where you are:', 'Please select': 'Please select', 'Please select another level': 'Please select another level', 'Please specify any problems and obstacles with the proper handling of the disease, in detail (in numbers, where appropriate). You may also add suggestions the situation could be improved.': 'Please specify any problems and obstacles with the proper handling of the disease, in detail (in numbers, where appropriate). You may also add suggestions the situation could be improved.', 'Please use this field to record any additional information, including a history of the record if it is updated.': 'Please use this field to record any additional information, including a history of the record if it is updated.', 'Please use this field to record any additional information, including any Special Needs.': 'Please use this field to record any additional information, including any Special Needs.', 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.': 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.', 'Pledge Support': 'Pledge Support', 'Point': 'Point', 'Poisoning': 'Poisoning', 'Poisonous Gas': 'Poisonous Gas', 'Police': 'Police', 'Pollution and other environmental': 'Pollution and other environmental', 'Polygon': 'Polygon', 'Polygon reference of the rating unit': 'Polygon reference of the rating unit', 'Poor': 'Poor', 'Population': 'Population', 'Population Statistic Details': 'Population Statistic Details', 'Population Statistic added': 'Population Statistic added', 'Population Statistic deleted': 'Population Statistic deleted', 'Population Statistic updated': 'Population Statistic updated', 'Population Statistics': 'Population Statistics', 'Population and number of households': 'Population and number of households', 'Popup Fields': 'Popup Fields', 'Popup Label': 'Popup Label', 'Porridge': 'Porridge', 'Port': 'Port', 'Port Closure': 'Port Closure', 'Portable App': 'Portable App', 'Portal at': 'Portal at', 'Portuguese': 'Portuguese', 'Portuguese (Brazil)': 'Portuguese (Brazil)', 'Position': 'Position', 'Position Catalog': 'Position Catalogue', 'Position Details': 'Position Details', 'Position added': 'Position added', 'Position deleted': 'Position deleted', 'Position updated': 'Position updated', 'Positions': 'Positions', 'Postcode': 'Postcode', 'Poultry': 'Poultry', 'Poultry restocking, Rank': 'Poultry restocking, Rank', 'Power Failure': 'Power Failure', 'Powered by Sahana Eden': 'Powered by Sahana Eden', 'Pre-cast connections': 'Pre-cast connections', 'Preferred Name': 'Preferred Name', 'Pregnant women': 'Pregnant women', 'Preliminary': 'Preliminary', 'Presence': 'Presence', 'Presence Condition': 'Presence Condition', 'Presence Log': 'Presence Log', 'Previous View': 'Previous View', 'Primary Occupancy': 'Primary Occupancy', 'Priority': 'Priority', 'Priority from 1 to 9. 1 is most preferred.': 'Priority from 1 to 9. 1 is most preferred.', 'Privacy': 'Privacy', 'Private': 'Private', 'Problem': 'Problem', 'Problem Administration': 'Problem Administration', 'Problem Details': 'Problem Details', 'Problem Group': 'Problem Group', 'Problem Title': 'Problem Title', 'Problem added': 'Problem added', 'Problem connecting to twitter.com - please refresh': 'Problem connecting to twitter.com - please refresh', 'Problem deleted': 'Problem deleted', 'Problem updated': 'Problem updated', 'Problems': 'Problems', 'Procedure': 'Procedure', 'Process Received Shipment': 'Process Received Shipment', 'Process Shipment to Send': 'Process Shipment to Send', 'Profile': 'Profile', 'Project': 'Project', 'Project Details': 'Project Details', 'Project Details including organizations': 'Project Details including organisations', 'Project Details including organizations and communities': 'Project Details including organisations and communities', 'Project Organization Details': 'Project Organisation Details', 'Project Organization updated': 'Project Organisation updated', 'Project Organizations': 'Project Organisations', 'Project Site': 'Project Site', 'Project Sites': 'Project Sites', 'Project Status': 'Project Status', 'Project Tracking': 'Project Tracking', 'Project added': 'Project added', 'Project deleted': 'Project deleted', 'Project updated': 'Project updated', 'Projection': 'Projection', 'Projection Details': 'Projection Details', 'Projection added': 'Projection added', 'Projection deleted': 'Projection deleted', 'Projection updated': 'Projection updated', 'Projections': 'Projections', 'Projects': 'Projects', 'Property reference in the council system': 'Property reference in the council system', 'Protection': 'Protection', 'Provide Metadata for your media files': 'Provide Metadata for your media files', 'Provide a password': 'Provide a password', 'Provide an optional sketch of the entire building or damage points. Indicate damage points.': 'Provide an optional sketch of the entire building or damage points. Indicate damage points.', 'Proxy Server URL': 'Proxy Server URL', 'Psychiatrics/Adult': 'Psychiatrics/Adult', 'Psychiatrics/Pediatric': 'Psychiatrics/Pediatric', 'Public': 'Public', 'Public Event': 'Public Event', 'Public and private transportation': 'Public and private transportation', 'Public assembly': 'Public assembly', 'Pull tickets from external feed': 'Pull tickets from external feed', 'Purchase Date': 'Purchase Date', 'Purpose': 'Purpose', 'Push tickets to external system': 'Push tickets to external system', 'Pyroclastic Flow': 'Pyroclastic Flow', 'Pyroclastic Surge': 'Pyroclastic Surge', 'Python Serial module not available within the running Python - this needs installing to activate the Modem': 'Python Serial module not available within the running Python - this needs installing to activate the Modem', 'Quantity': 'Quantity', 'Quantity Committed': 'Quantity Committed', 'Quantity Fulfilled': 'Quantity Fulfilled', "Quantity in %s's Inventory": "Quantity in %s's Inventory", 'Quantity in Transit': 'Quantity in Transit', 'Quarantine': 'Quarantine', 'Queries': 'Queries', 'Query': 'Query', 'Queryable?': 'Queryable?', 'Question': 'Question', 'Question Details': 'Question Details', 'Question Meta-Data': 'Question Meta-Data', 'Question Meta-Data Details': 'Question Meta-Data Details', 'Question Meta-Data added': 'Question Meta-Data added', 'Question Meta-Data deleted': 'Question Meta-Data deleted', 'Question Meta-Data updated': 'Question Meta-Data updated', 'Question Summary': 'Question Summary', 'RC frame with masonry infill': 'RC frame with masonry infill', 'RECORD A': 'RECORD A', 'RECORD B': 'RECORD B', 'RMS': 'RMS', 'RMS Team': 'RMS Team', 'Race': 'Race', 'Radio': 'Radio', 'Radio Details': 'Radio Details', 'Radiological Hazard': 'Radiological Hazard', 'Radiology': 'Radiology', 'Railway Accident': 'Railway Accident', 'Railway Hijacking': 'Railway Hijacking', 'Rain Fall': 'Rain Fall', 'Rapid Assessment': 'Rapid Assessment', 'Rapid Assessment Details': 'Rapid Assessment Details', 'Rapid Assessment added': 'Rapid Assessment added', 'Rapid Assessment deleted': 'Rapid Assessment deleted', 'Rapid Assessment updated': 'Rapid Assessment updated', 'Rapid Assessments': 'Rapid Assessments', 'Rapid Assessments & Flexible Impact Assessments': 'Rapid Assessments & Flexible Impact Assessments', 'Rapid Close Lead': 'Rapid Close Lead', 'Rapid Data Entry': 'Rapid Data Entry', 'Raw Database access': 'Raw Database access', 'Receive': 'Receive', 'Receive New Shipment': 'Receive New Shipment', 'Receive Shipment': 'Receive Shipment', 'Receive this shipment?': 'Receive this shipment?', 'Received': 'Received', 'Received By': 'Received By', 'Received By Person': 'Received By Person', 'Received Item Details': 'Received Item Details', 'Received Item updated': 'Received Item updated', 'Received Shipment Details': 'Received Shipment Details', 'Received Shipment canceled': 'Received Shipment canceled', 'Received Shipment canceled and items removed from Inventory': 'Received Shipment canceled and items removed from Inventory', 'Received Shipment updated': 'Received Shipment updated', 'Received Shipments': 'Received Shipments', 'Receiving and Sending Items': 'Receiving and Sending Items', 'Recipient': 'Recipient', 'Recipients': 'Recipients', 'Recommendations for Repair and Reconstruction or Demolition': 'Recommendations for Repair and Reconstruction or Demolition', 'Record': 'Record', 'Record Details': 'Record Details', 'Record Saved': 'Record Saved', 'Record added': 'Record added', 'Record any restriction on use or entry': 'Record any restriction on use or entry', 'Record created': 'Record created', 'Record deleted': 'Record deleted', 'Record last updated': 'Record last updated', 'Record not found': 'Record not found', 'Record not found!': 'Record not found!', 'Record updated': 'Record updated', 'Recording and Assigning Assets': 'Recording and Assigning Assets', 'Recovery': 'Recovery', 'Recovery Request': 'Recovery Request', 'Recovery Request added': 'Recovery Request added', 'Recovery Request deleted': 'Recovery Request deleted', 'Recovery Request updated': 'Recovery Request updated', 'Recurring': 'Recurring', 'Recurring Cost': 'Recurring Cost', 'Recurring cost': 'Recurring cost', 'Recurring costs': 'Recurring costs', 'Red': 'Red', 'Red Cross / Red Crescent': 'Red Cross / Red Crescent', 'Reference Document': 'Reference Document', 'Refresh Rate (seconds)': 'Refresh Rate (seconds)', 'Region': 'Region', 'Region Location': 'Region Location', 'Regional': 'Regional', 'Register': 'Register', 'Register Person': 'Register Person', 'Register Person into this Camp': 'Register Person into this Camp', 'Register Person into this Shelter': 'Register Person into this Shelter', 'Register them as a volunteer': 'Register them as a volunteer', 'Registered People': 'Registered People', 'Registered users can': 'Registered users can', 'Registration': 'Registration', 'Registration Details': 'Registration Details', 'Registration added': 'Registration added', 'Registration entry deleted': 'Registration entry deleted', 'Registration is still pending approval from Approver (%s) - please wait until confirmation received.': 'Registration is still pending approval from Approver (%s) - please wait until confirmation received.', 'Registration key': 'Registration key', 'Registration updated': 'Registration updated', 'Rehabilitation/Long Term Care': 'Rehabilitation/Long Term Care', 'Reinforced masonry': 'Reinforced masonry', 'Rejected': 'Rejected', 'Relative Details': 'Relative Details', 'Relative added': 'Relative added', 'Relative deleted': 'Relative deleted', 'Relative updated': 'Relative updated', 'Relatives': 'Relatives', 'Relief': 'Relief', 'Relief Team': 'Relief Team', 'Religion': 'Religion', 'Religious': 'Religious', 'Religious Leader': 'Religious Leader', 'Relocate as instructed in the <instruction>': 'Relocate as instructed in the <instruction>', 'Remote Error': 'Remote Error', 'Remove': 'Remove', 'Remove Activity from this event': 'Remove Activity from this event', 'Remove Asset from this event': 'Remove Asset from this event', 'Remove Asset from this scenario': 'Remove Asset from this scenario', 'Remove Document from this request': 'Remove Document from this request', 'Remove Facility from this event': 'Remove Facility from this event', 'Remove Facility from this scenario': 'Remove Facility from this scenario', 'Remove Human Resource from this event': 'Remove Human Resource from this event', 'Remove Human Resource from this scenario': 'Remove Human Resource from this scenario', 'Remove Incident from this event': 'Remove Incident from this event', 'Remove Item from Inventory': 'Remove Item from Inventory', 'Remove Item from Order': 'Remove Item from Order', 'Remove Item from Shipment': 'Remove Item from Shipment', 'Remove Map Configuration from this event': 'Remove Map Configuration from this event', 'Remove Map Configuration from this scenario': 'Remove Map Configuration from this scenario', 'Remove Organization from Project': 'Remove Organisation from Project', 'Remove Person from Commitment': 'Remove Person from Commitment', 'Remove Skill': 'Remove Skill', 'Remove Skill from Request': 'Remove Skill from Request', 'Remove Task from this event': 'Remove Task from this event', 'Remove Task from this scenario': 'Remove Task from this scenario', 'Remove this asset from this event': 'Remove this asset from this event', 'Remove this asset from this scenario': 'Remove this asset from this scenario', 'Remove this facility from this event': 'Remove this facility from this event', 'Remove this facility from this scenario': 'Remove this facility from this scenario', 'Remove this human resource from this event': 'Remove this human resource from this event', 'Remove this human resource from this scenario': 'Remove this human resource from this scenario', 'Remove this task from this event': 'Remove this task from this event', 'Remove this task from this scenario': 'Remove this task from this scenario', 'Repair': 'Repair', 'Repaired': 'Repaired', 'Repeat your password': 'Repeat your password', 'Report': 'Report', 'Report Another Assessment...': 'Report Another Assessment...', 'Report Details': 'Report Details', 'Report Resource': 'Report Resource', 'Report To': 'Report To', 'Report Types Include': 'Report Types Include', 'Report added': 'Report added', 'Report deleted': 'Report deleted', 'Report my location': 'Report my location', 'Report the contributing factors for the current EMS status.': 'Report the contributing factors for the current EMS status.', 'Report the contributing factors for the current OR status.': 'Report the contributing factors for the current OR status.', 'Report them as found': 'Report them as found', 'Report them missing': 'Report them missing', 'Report updated': 'Report updated', 'ReportLab module not available within the running Python - this needs installing for PDF output!': 'ReportLab module not available within the running Python - this needs installing for PDF output!', 'Reported To': 'Reported To', 'Reporter': 'Reporter', 'Reporter Name': 'Reporter Name', 'Reporting on the projects in the region': 'Reporting on the projects in the region', 'Reports': 'Reports', 'Repositories': 'Repositories', 'Repository': 'Repository', 'Repository Base URL': 'Repository Base URL', 'Repository Configuration': 'Repository Configuration', 'Repository Name': 'Repository Name', 'Repository UUID': 'Repository UUID', 'Repository configuration deleted': 'Repository configuration deleted', 'Repository configuration updated': 'Repository configuration updated', 'Repository configured': 'Repository configured', 'Request': 'Request', 'Request Added': 'Request Added', 'Request Canceled': 'Request Canceled', 'Request Details': 'Request Details', 'Request From': 'Request From', 'Request Item': 'Request Item', 'Request Item Details': 'Request Item Details', 'Request Item added': 'Request Item added', 'Request Item deleted': 'Request Item deleted', 'Request Item from Available Inventory': 'Request Item from Available Inventory', 'Request Item updated': 'Request Item updated', 'Request Items': 'Request Items', 'Request New People': 'Request New People', 'Request Number': 'Request Number', 'Request Status': 'Request Status', 'Request Type': 'Request Type', 'Request Updated': 'Request Updated', 'Request added': 'Request added', 'Request deleted': 'Request deleted', 'Request for Account': 'Request for Account', 'Request for Donations Added': 'Request for Donations Added', 'Request for Donations Canceled': 'Request for Donations Canceled', 'Request for Donations Details': 'Request for Donations Details', 'Request for Donations Updated': 'Request for Donations Updated', 'Request for Role Upgrade': 'Request for Role Upgrade', 'Request for Volunteers Added': 'Request for Volunteers Added', 'Request for Volunteers Canceled': 'Request for Volunteers Canceled', 'Request for Volunteers Details': 'Request for Volunteers Details', 'Request for Volunteers Updated': 'Request for Volunteers Updated', 'Request updated': 'Request updated', 'Request, Response & Session': 'Request, Response & Session', 'Requested': 'Requested', 'Requested By': 'Requested By', 'Requested By Facility': 'Requested By Facility', 'Requested For': 'Requested For', 'Requested For Facility': 'Requested For Facility', 'Requested From': 'Requested From', 'Requested Items': 'Requested Items', 'Requested Skill Details': 'Requested Skill Details', 'Requested Skill updated': 'Requested Skill updated', 'Requested Skills': 'Requested Skills', 'Requester': 'Requester', 'Requests': 'Requests', 'Requests Management': 'Requests Management', 'Requests for Donations': 'Requests for Donations', 'Requests for Volunteers': 'Requests for Volunteers', 'Required Skills': 'Required Skills', 'Requires Login': 'Requires Login', 'Requires Login!': 'Requires Login!', 'Rescue and recovery': 'Rescue and recovery', 'Reset': 'Reset', 'Reset Password': '<PASSWORD> Password', 'Resolve': 'Resolve', 'Resolve link brings up a new screen which helps to resolve these duplicate records and update the database.': 'Resolve link brings up a new screen which helps to resolve these duplicate records and update the database.', 'Resource': 'Resource', 'Resource Configuration': 'Resource Configuration', 'Resource Details': 'Resource Details', 'Resource Mapping System': 'Resource Mapping System', 'Resource Mapping System account has been activated': 'Resource Mapping System account has been activated', 'Resource Name': 'Resource Name', 'Resource added': 'Resource added', 'Resource configuration deleted': 'Resource configuration deleted', 'Resource configuration updated': 'Resource configuration updated', 'Resource configured': 'Resource configured', 'Resource deleted': 'Resource deleted', 'Resource updated': 'Resource updated', 'Resources': 'Resources', 'Respiratory Infections': 'Respiratory Infections', 'Response': 'Response', 'Restricted Access': 'Restricted Access', 'Restricted Use': 'Restricted Use', 'Results': 'Results', 'Retail Crime': 'Retail Crime', 'Retrieve Password': 'Retrieve Password', 'Return': 'Return', 'Return to Request': 'Return to Request', 'Returned': 'Returned', 'Returned From': 'Returned From', 'Review Incoming Shipment to Receive': 'Review Incoming Shipment to Receive', 'Rice': 'Rice', 'Riot': 'Riot', 'River': 'River', 'River Details': 'River Details', 'River added': 'River added', 'River deleted': 'River deleted', 'River updated': 'River updated', 'Rivers': 'Rivers', 'Road Accident': 'Road Accident', 'Road Closed': 'Road Closed', 'Road Conditions': 'Road Conditions', 'Road Delay': 'Road Delay', 'Road Hijacking': 'Road Hijacking', 'Road Usage Condition': 'Road Usage Condition', 'Roads Layer': 'Roads Layer', 'Role': 'Role', 'Role Details': 'Role Details', 'Role Required': 'Role Required', 'Role Updated': 'Role Updated', 'Role added': 'Role added', 'Role deleted': 'Role deleted', 'Role updated': 'Role updated', 'Roles': 'Roles', 'Roles Permitted': 'Roles Permitted', 'Roof tile': 'Roof tile', 'Roofs, floors (vertical load)': 'Roofs, floors (vertical load)', 'Room': 'Room', 'Room Details': 'Room Details', 'Room added': 'Room added', 'Room deleted': 'Room deleted', 'Room updated': 'Room updated', 'Rooms': 'Rooms', 'Rows in table': 'Rows in table', 'Rows selected': 'Rows selected', 'Running Cost': 'Running Cost', 'Russian': 'Russian', 'SMS': 'SMS', 'SMS Modems (Inbound & Outbound)': 'SMS Modems (Inbound & Outbound)', 'SMS Outbound': 'SMS Outbound', 'SMS Settings': 'SMS Settings', 'SMS settings updated': 'SMS settings updated', 'SMTP to SMS settings updated': 'SMTP to SMS settings updated', 'Safe environment for vulnerable groups': 'Safe environment for vulnerable groups', 'Safety Assessment Form': 'Safety Assessment Form', 'Safety of children and women affected by disaster?': 'Safety of children and women affected by disaster?', 'Sahana Eden': 'Sahana Eden', 'Sahana Eden Humanitarian Management Platform': 'Sahana Eden Humanitarian Management Platform', 'Sahana Eden portable application generator': 'Sahana Eden portable application generator', 'Salted Fish': 'Salted Fish', 'Sanitation problems': 'Sanitation problems', 'Satellite': 'Satellite', 'Satellite Layer': 'Satellite Layer', 'Saturday': 'Saturday', 'Save': 'Save', 'Save Search': 'Save Search', 'Save: Default Lat, Lon & Zoom for the Viewport': 'Save: Default Lat, Lon & Zoom for the Viewport', 'Saved Search Details': 'Saved Search Details', 'Saved Search added': 'Saved Search added', 'Saved Search deleted': 'Saved Search deleted', 'Saved Search updated': 'Saved Search updated', 'Saved Searches': 'Saved Searches', 'Saved.': 'Saved.', 'Saving...': 'Saving...', 'Scale of Results': 'Scale of Results', 'Scanned Copy': 'Scanned Copy', 'Scanned Forms Upload': 'Scanned Forms Upload', 'Scenario': 'Scenario', 'Scenario Details': 'Scenario Details', 'Scenario added': 'Scenario added', 'Scenario deleted': 'Scenario deleted', 'Scenario updated': 'Scenario updated', 'Scenarios': 'Scenarios', 'Schedule': 'Schedule', 'Schedule synchronization jobs': 'Schedule synchronisation jobs', 'Schema': 'Schema', 'School': 'School', 'School Closure': 'School Closure', 'School Lockdown': 'School Lockdown', 'School Teacher': 'School Teacher', 'School activities': 'School activities', 'School assistance': 'School assistance', 'School attendance': 'School attendance', 'School destroyed': 'School destroyed', 'School heavily damaged': 'School heavily damaged', 'School tents received': 'School tents received', 'School tents, source': 'School tents, source', 'School used for other purpose': 'School used for other purpose', 'School/studying': 'School/studying', 'Search': 'Search', 'Search Activities': 'Search Activities', 'Search Activity Report': 'Search Activity Report', 'Search Addresses': 'Search Addresses', 'Search Alternative Items': 'Search Alternative Items', 'Search Assessment Summaries': 'Search Assessment Summaries', 'Search Assessments': 'Search Assessments', 'Search Asset Log': 'Search Asset Log', 'Search Assets': 'Search Assets', 'Search Baseline Type': 'Search Baseline Type', 'Search Baselines': 'Search Baselines', 'Search Brands': 'Search Brands', 'Search Budgets': 'Search Budgets', 'Search Bundles': 'Search Bundles', 'Search Camp Services': 'Search Camp Services', 'Search Camp Types': 'Search Camp Types', 'Search Camps': 'Search Camps', 'Search Catalog Items': 'Search Catalogue Items', 'Search Catalogs': 'Search Catalogues', 'Search Certificates': 'Search Certificates', 'Search Certifications': 'Search Certifications', 'Search Checklists': 'Search Checklists', 'Search Cluster Subsectors': 'Search Cluster Subsectors', 'Search Clusters': 'Search Clusters', 'Search Commitment Items': 'Search Commitment Items', 'Search Commitments': 'Search Commitments', 'Search Committed People': 'Search Committed People', 'Search Competency Ratings': 'Search Competency Ratings', 'Search Contact Information': 'Search Contact Information', 'Search Contacts': 'Search Contacts', 'Search Course Certificates': 'Search Course Certificates', 'Search Courses': 'Search Courses', 'Search Credentials': 'Search Credentials', 'Search Criteria': 'Search Criteria', 'Search Documents': 'Search Documents', 'Search Donors': 'Search Donors', 'Search Entries': 'Search Entries', 'Search Events': 'Search Events', 'Search Facilities': 'Search Facilities', 'Search Feature Class': 'Search Feature Class', 'Search Feature Layers': 'Search Feature Layers', 'Search Flood Reports': 'Search Flood Reports', 'Search GPS data': 'Search GPS data', 'Search Geonames': 'Search Geonames', 'Search Groups': 'Search Groups', 'Search Homes': 'Search Homes', 'Search Human Resources': 'Search Human Resources', 'Search Identity': 'Search Identity', 'Search Images': 'Search Images', 'Search Impact Type': 'Search Impact Type', 'Search Impacts': 'Search Impacts', 'Search Import Files': 'Search Import Files', 'Search Incident Reports': 'Search Incident Reports', 'Search Incidents': 'Search Incidents', 'Search Inventory Items': 'Search Inventory Items', 'Search Inventory items': 'Search Inventory items', 'Search Item Categories': 'Search Item Categories', 'Search Item Packs': 'Search Item Packs', 'Search Items': 'Search Items', 'Search Job Roles': 'Search Job Roles', 'Search Kits': 'Search Kits', 'Search Layers': 'Search Layers', 'Search Level': 'Search Level', 'Search Level 1 Assessments': 'Search Level 1 Assessments', 'Search Level 2 Assessments': 'Search Level 2 Assessments', 'Search Locations': 'Search Locations', 'Search Log Entry': 'Search Log Entry', 'Search Map Configurations': 'Search Map Configurations', 'Search Markers': 'Search Markers', 'Search Member': 'Search Member', 'Search Membership': 'Search Membership', 'Search Memberships': 'Search Memberships', 'Search Missions': 'Search Missions', 'Search Need Type': 'Search Need Type', 'Search Needs': 'Search Needs', 'Search Offices': 'Search Offices', 'Search Order Items': 'Search Order Items', 'Search Orders': 'Search Orders', 'Search Organization Domains': 'Search Organisation Domains', 'Search Organizations': 'Search Organisations', 'Search Patients': 'Search Patients', 'Search Personal Effects': 'Search Personal Effects', 'Search Persons': 'Search Persons', 'Search Photos': 'Search Photos', 'Search Population Statistics': 'Search Population Statistics', 'Search Positions': 'Search Positions', 'Search Problems': 'Search Problems', 'Search Project Organizations': 'Search Project Organisations', 'Search Projections': 'Search Projections', 'Search Projects': 'Search Projects', 'Search Rapid Assessments': 'Search Rapid Assessments', 'Search Received Items': 'Search Received Items', 'Search Received Shipments': 'Search Received Shipments', 'Search Records': 'Search Records', 'Search Registations': 'Search Registations', 'Search Relatives': 'Search Relatives', 'Search Report': 'Search Report', 'Search Request': 'Search Request', 'Search Request Items': 'Search Request Items', 'Search Requested Items': 'Search Requested Items', 'Search Requested Skills': 'Search Requested Skills', 'Search Requests': 'Search Requests', 'Search Requests for Donations': 'Search Requests for Donations', 'Search Requests for Volunteers': 'Search Requests for Volunteers', 'Search Resources': 'Search Resources', 'Search Rivers': 'Search Rivers', 'Search Roles': 'Search Roles', 'Search Rooms': 'Search Rooms', 'Search Saved Searches': 'Search Saved Searches', 'Search Scenarios': 'Search Scenarios', 'Search Sections': 'Search Sections', 'Search Sectors': 'Search Sectors', 'Search Sent Items': 'Search Sent Items', 'Search Sent Shipments': 'Search Sent Shipments', 'Search Service Profiles': 'Search Service Profiles', 'Search Settings': 'Search Settings', 'Search Shelter Services': 'Search Shelter Services', 'Search Shelter Types': 'Search Shelter Types', 'Search Shelters': 'Search Shelters', 'Search Skill Equivalences': 'Search Skill Equivalences', 'Search Skill Provisions': 'Search Skill Provisions', 'Search Skill Types': 'Search Skill Types', 'Search Skills': 'Search Skills', 'Search Solutions': 'Search Solutions', 'Search Staff Types': 'Search Staff Types', 'Search Staff or Volunteer': 'Search Staff or Volunteer', 'Search Status': 'Search Status', 'Search Subscriptions': 'Search Subscriptions', 'Search Subsectors': 'Search Subsectors', 'Search Support Requests': 'Search Support Requests', 'Search Tasks': 'Search Tasks', 'Search Teams': 'Search Teams', 'Search Themes': 'Search Themes', 'Search Tickets': 'Search Tickets', 'Search Trainings': 'Search Trainings', 'Search Twitter Tags': 'Search Twitter Tags', 'Search Units': 'Search Units', 'Search Users': 'Search Users', 'Search Vehicle Details': 'Search Vehicle Details', 'Search Vehicles': 'Search Vehicles', 'Search Volunteer Availability': 'Search Volunteer Availability', 'Search Warehouses': 'Search Warehouses', 'Search and Edit Group': 'Search and Edit Group', 'Search and Edit Individual': 'Search and Edit Individual', 'Search by organization.': 'Search by organisation.', 'Search for Job': 'Search for Job', 'Search for Repository': 'Search for Repository', 'Search for Resource': 'Search for Resource', 'Search for Staff or Volunteers': 'Search for Staff or Volunteers', 'Search for a Location by name, including local names.': 'Search for a Location by name, including local names.', 'Search for a Person': 'Search for a Person', 'Search for a Project': 'Search for a Project', 'Search for a shipment by looking for text in any field.': 'Search for a shipment by looking for text in any field.', 'Search for a shipment received between these dates': 'Search for a shipment received between these dates', 'Search for a vehicle by text.': 'Search for a vehicle by text.', 'Search for an Organization by name or acronym': 'Search for an Organisation by name or acronym', 'Search for an Organization by name or acronym.': 'Search for an Organisation by name or acronym.', 'Search for an asset by text.': 'Search for an asset by text.', 'Search for an item by Year of Manufacture.': 'Search for an item by Year of Manufacture.', 'Search for an item by brand.': 'Search for an item by brand.', 'Search for an item by catalog.': 'Search for an item by catalogue.', 'Search for an item by category.': 'Search for an item by category.', 'Search for an item by its code, name, model and/or comment.': 'Search for an item by its code, name, model and/or comment.', 'Search for an item by text.': 'Search for an item by text.', 'Search for an order by looking for text in any field.': 'Search for an order by looking for text in any field.', 'Search for an order expected between these dates': 'Search for an order expected between these dates', 'Search for asset by location.': 'Search for asset by location.', 'Search for office by location.': 'Search for office by location.', 'Search for office by organization.': 'Search for office by organisation.', 'Search for office by text.': 'Search for office by text.', 'Search for vehicle by location.': 'Search for vehicle by location.', 'Search for warehouse by location.': 'Search for warehouse by location.', 'Search for warehouse by organization.': 'Search for warehouse by organisation.', 'Search for warehouse by text.': 'Search for warehouse by text.', 'Search here for a person record in order to:': 'Search here for a person record in order to:', 'Search messages': 'Search messages', 'Searching for different groups and individuals': 'Searching for different groups and individuals', 'Secondary Server (Optional)': 'Secondary Server (Optional)', 'Seconds must be a number between 0 and 60': 'Seconds must be a number between 0 and 60', 'Section': 'Section', 'Section Details': 'Section Details', 'Section deleted': 'Section deleted', 'Section updated': 'Section updated', 'Sections': 'Sections', 'Sections that are part of this template': 'Sections that are part of this template', 'Sections that can be selected': 'Sections that can be selected', 'Sector': 'Sector', 'Sector Details': 'Sector Details', 'Sector added': 'Sector added', 'Sector deleted': 'Sector deleted', 'Sector updated': 'Sector updated', 'Sector(s)': 'Sector(s)', 'Sectors': 'Sectors', 'Security Required': 'Security Required', 'Security Status': 'Security Status', 'Security problems': 'Security problems', 'See All Entries': 'See All Entries', 'See a detailed description of the module on the Sahana Eden wiki': 'See a detailed description of the module on the Sahana Eden wiki', 'See all': 'See all', 'See the universally unique identifier (UUID) of this repository': 'See the universally unique identifier (UUID) of this repository', 'See unassigned recovery requests': 'See unassigned recovery requests', 'Select Existing Location': 'Select Existing Location', 'Select Items from the Request': 'Select Items from the Request', 'Select Items from this Inventory': 'Select Items from this Inventory', 'Select This Location': 'Select This Location', "Select a Room from the list or click 'Add Room'": "Select a Room from the list or click 'Add Room'", 'Select a location': 'Select a location', "Select a manager for status 'assigned'": "Select a manager for status 'assigned'", 'Select a range for the number of total beds': 'Select a range for the number of total beds', 'Select all that apply': 'Select all that apply', 'Select an Organization to see a list of offices': 'Select an Organisation to see a list of offices', 'Select the overlays for Assessments and Activities relating to each Need to identify the gap.': 'Select the overlays for Assessments and Activities relating to each Need to identify the gap.', 'Select the person assigned to this role for this project.': 'Select the person assigned to this role for this project.', "Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.": "Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.", "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.": "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.", 'Select to show this configuration in the menu.': 'Select to show this configuration in the menu.', 'Selected Answers': 'Selected Answers', 'Selected Jobs': 'Selected Jobs', 'Selects what type of gateway to use for outbound SMS': 'Selects what type of gateway to use for outbound SMS', 'Send': 'Send', 'Send Alerts using Email &/or SMS': 'Send Alerts using Email &/or SMS', 'Send Commitment as Shipment': 'Send Commitment as Shipment', 'Send New Shipment': 'Send New Shipment', 'Send Notification': 'Send Notification', 'Send Shipment': 'Send Shipment', 'Send a message to this person': 'Send a message to this person', 'Send from %s': 'Send from %s', 'Send message': 'Send message', 'Send new message': 'Send new message', 'Sends & Receives Alerts via Email & SMS': 'Sends & Receives Alerts via Email & SMS', 'Senior (50+)': 'Senior (50+)', 'Sent': 'Sent', 'Sent By': 'Sent By', 'Sent By Person': 'Sent By Person', 'Sent Item Details': 'Sent Item Details', 'Sent Item deleted': 'Sent Item deleted', 'Sent Item updated': 'Sent Item updated', 'Sent Shipment Details': 'Sent Shipment Details', 'Sent Shipment canceled': 'Sent Shipment canceled', 'Sent Shipment canceled and items returned to Inventory': 'Sent Shipment canceled and items returned to Inventory', 'Sent Shipment updated': 'Sent Shipment updated', 'Sent Shipments': 'Sent Shipments', 'Separated children, caregiving arrangements': 'Separated children, caregiving arrangements', 'Serial Number': 'Serial Number', 'Series': 'Series', 'Series Analysis': 'Series Analysis', 'Series Details': 'Series Details', 'Series Map': 'Series Map', 'Series Summary': 'Series Summary', 'Server': 'Server', 'Service Catalog': 'Service Catalogue', 'Service Due': 'Service Due', 'Service or Facility': 'Service or Facility', 'Service profile added': 'Service profile added', 'Service profile deleted': 'Service profile deleted', 'Service profile updated': 'Service profile updated', 'Services': 'Services', 'Services Available': 'Services Available', 'Set Base Site': 'Set Base Site', 'Set By': 'Set By', 'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.': 'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.', 'Setting Details': 'Setting Details', 'Setting added': 'Setting added', 'Setting deleted': 'Setting deleted', 'Setting updated': 'Setting updated', 'Settings': 'Settings', 'Settings updated': 'Settings updated', 'Settings were reset because authenticating with Twitter failed': 'Settings were reset because authenticating with Twitter failed', 'Settings which can be configured through the web interface are available here.': 'Settings which can be configured through the web interface are available here.', 'Severe': 'Severe', 'Severity': 'Severity', 'Share a common Marker (unless over-ridden at the Feature level)': 'Share a common Marker (unless over-ridden at the Feature level)', 'Shelter': 'Shelter', 'Shelter & Essential NFIs': 'Shelter & Essential NFIs', 'Shelter Details': 'Shelter Details', 'Shelter Name': 'Shelter Name', 'Shelter Registry': 'Shelter Registry', 'Shelter Service': 'Shelter Service', 'Shelter Service Details': 'Shelter Service Details', 'Shelter Service added': 'Shelter Service added', 'Shelter Service deleted': 'Shelter Service deleted', 'Shelter Service updated': 'Shelter Service updated', 'Shelter Services': 'Shelter Services', 'Shelter Type': 'Shelter Type', 'Shelter Type Details': 'Shelter Type Details', 'Shelter Type added': 'Shelter Type added', 'Shelter Type deleted': 'Shelter Type deleted', 'Shelter Type updated': 'Shelter Type updated', 'Shelter Types': 'Shelter Types', 'Shelter Types and Services': 'Shelter Types and Services', 'Shelter added': 'Shelter added', 'Shelter deleted': 'Shelter deleted', 'Shelter updated': 'Shelter updated', 'Shelter/NFI Assistance': 'Shelter/NFI Assistance', 'Shelters': 'Shelters', 'Shipment Created': 'Shipment Created', 'Shipment Items': 'Shipment Items', 'Shipment Items received by Inventory': 'Shipment Items received by Inventory', 'Shipment Items sent from Inventory': 'Shipment Items sent from Inventory', 'Shipment to Send': 'Shipment to Send', 'Shipments': 'Shipments', 'Shipments To': 'Shipments To', 'Shooting': 'Shooting', 'Short Assessment': 'Short Assessment', 'Short Description': 'Short Description', 'Show Checklist': 'Show Checklist', 'Show Map': 'Show Map', 'Show in Menu?': 'Show in Menu?', 'Show on Map': 'Show on Map', 'Show on map': 'Show on map', 'Show selected answers': 'Show selected answers', 'Showing latest entries first': 'Showing latest entries first', 'Sign-up for Account': 'Sign-up for Account', 'Single PDF File': 'Single PDF File', 'Site': 'Site', 'Site Administration': 'Site Administration', 'Sites': 'Sites', 'Situation Awareness & Geospatial Analysis': 'Situation Awareness & Geospatial Analysis', 'Sketch': 'Sketch', 'Skill': 'Skill', 'Skill Catalog': 'Skill Catalogue', 'Skill Details': 'Skill Details', 'Skill Equivalence': 'Skill Equivalence', 'Skill Equivalence Details': 'Skill Equivalence Details', 'Skill Equivalence added': 'Skill Equivalence added', 'Skill Equivalence deleted': 'Skill Equivalence deleted', 'Skill Equivalence updated': 'Skill Equivalence updated', 'Skill Equivalences': 'Skill Equivalences', 'Skill Provision': 'Skill Provision', 'Skill Provision Catalog': 'Skill Provision Catalogue', 'Skill Provision Details': 'Skill Provision Details', 'Skill Provision added': 'Skill Provision added', 'Skill Provision deleted': 'Skill Provision deleted', 'Skill Provision updated': 'Skill Provision updated', 'Skill Provisions': 'Skill Provisions', 'Skill Type': 'Skill Type', 'Skill Type Catalog': 'Skill Type Catalogue', 'Skill Type added': 'Skill Type added', 'Skill Type deleted': 'Skill Type deleted', 'Skill Type updated': 'Skill Type updated', 'Skill Types': 'Skill Types', 'Skill added': 'Skill added', 'Skill added to Request': 'Skill added to Request', 'Skill deleted': 'Skill deleted', 'Skill removed': 'Skill removed', 'Skill removed from Request': 'Skill removed from Request', 'Skill updated': 'Skill updated', 'Skills': 'Skills', 'Skills Catalog': 'Skills Catalogue', 'Skills Management': 'Skills Management', 'Skype ID': 'Skype ID', 'Slope failure, debris': 'Slope failure, debris', 'Small Trade': 'Small Trade', 'Smoke': 'Smoke', 'Snapshot': 'Snapshot', 'Snapshot Report': 'Snapshot Report', 'Snow Fall': 'Snow Fall', 'Snow Squall': 'Snow Squall', 'Soil bulging, liquefaction': 'Soil bulging, liquefaction', 'Solid waste': 'Solid waste', 'Solution': 'Solution', 'Solution Details': 'Solution Details', 'Solution Item': 'Solution Item', 'Solution added': 'Solution added', 'Solution deleted': 'Solution deleted', 'Solution updated': 'Solution updated', 'Solutions': 'Solutions', 'Some': 'Some', 'Sorry - the server has a problem, please try again later.': 'Sorry - the server has a problem, please try again later.', 'Sorry that location appears to be outside the area of the Parent.': 'Sorry that location appears to be outside the area of the Parent.', 'Sorry that location appears to be outside the area supported by this deployment.': 'Sorry that location appears to be outside the area supported by this deployment.', 'Sorry, I could not understand your request': 'Sorry, I could not understand your request', 'Sorry, only users with the MapAdmin role are allowed to create location groups.': 'Sorry, only users with the MapAdmin role are allowed to create location groups.', 'Sorry, only users with the MapAdmin role are allowed to edit these locations': 'Sorry, only users with the MapAdmin role are allowed to edit these locations', 'Sorry, something went wrong.': 'Sorry, something went wrong.', 'Sorry, that page is forbidden for some reason.': 'Sorry, that page is forbidden for some reason.', 'Sorry, that service is temporary unavailable.': 'Sorry, that service is temporary unavailable.', 'Sorry, there are no addresses to display': 'Sorry, there are no addresses to display', "Sorry, things didn't get done on time.": "Sorry, things didn't get done on time.", "Sorry, we couldn't find that page.": "Sorry, we couldn't find that page.", 'Source': 'Source', 'Source ID': 'Source ID', 'Source Time': 'Source Time', 'Sources of income': 'Sources of income', 'Space Debris': 'Space Debris', 'Spanish': 'Spanish', 'Special Ice': 'Special Ice', 'Special Marine': 'Special Marine', 'Specialized Hospital': 'Specialized Hospital', 'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.': 'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.', 'Specific locations need to have a parent of level': 'Specific locations need to have a parent of level', 'Specify a descriptive title for the image.': 'Specify a descriptive title for the image.', 'Specify the bed type of this unit.': 'Specify the bed type of this unit.', 'Specify the number of available sets': 'Specify the number of available sets', 'Specify the number of available units (adult doses)': 'Specify the number of available units (adult doses)', 'Specify the number of available units (litres) of Ringer-Lactate or equivalent solutions': 'Specify the number of available units (litres) of Ringer-Lactate or equivalent solutions', 'Specify the number of sets needed per 24h': 'Specify the number of sets needed per 24h', 'Specify the number of units (adult doses) needed per 24h': 'Specify the number of units (adult doses) needed per 24h', 'Specify the number of units (litres) of Ringer-Lactate or equivalent solutions needed per 24h': 'Specify the number of units (litres) of Ringer-Lactate or equivalent solutions needed per 24h', 'Speed': 'Speed', 'Spherical Mercator?': 'Spherical Mercator?', 'Spreadsheet Importer': 'Spreadsheet Importer', 'Spreadsheet uploaded': 'Spreadsheet uploaded', 'Spring': 'Spring', 'Squall': 'Squall', 'Staff': 'Staff', 'Staff & Volunteers': 'Staff & Volunteers', 'Staff ID': 'Staff ID', 'Staff Member Details': 'Staff Member Details', 'Staff Members': 'Staff Members', 'Staff Record': 'Staff Record', 'Staff Type Details': 'Staff Type Details', 'Staff Type added': 'Staff Type added', 'Staff Type deleted': 'Staff Type deleted', 'Staff Type updated': 'Staff Type updated', 'Staff Types': 'Staff Types', 'Staff and Volunteers': 'Staff and Volunteers', 'Staff and volunteers': 'Staff and volunteers', 'Staff member added': 'Staff member added', 'Staff present and caring for residents': 'Staff present and caring for residents', 'Staff2': 'Staff2', 'Staffing': 'Staffing', 'Stairs': 'Stairs', 'Start Date': 'Start Date', 'Start date': 'Start date', 'Start date and end date should have valid date values': 'Start date and end date should have valid date values', 'State': 'State', 'Stationery': 'Stationery', 'Status': 'Status', 'Status Report': 'Status Report', 'Status Updated': 'Status Updated', 'Status added': 'Status added', 'Status deleted': 'Status deleted', 'Status of clinical operation of the facility.': 'Status of clinical operation of the facility.', 'Status of general operation of the facility.': 'Status of general operation of the facility.', 'Status of morgue capacity.': 'Status of morgue capacity.', 'Status of operations of the emergency department of this hospital.': 'Status of operations of the emergency department of this hospital.', 'Status of security procedures/access restrictions in the hospital.': 'Status of security procedures/access restrictions in the hospital.', 'Status of the operating rooms of this hospital.': 'Status of the operating rooms of this hospital.', 'Status updated': 'Status updated', 'Steel frame': 'Steel frame', 'Stolen': 'Stolen', 'Store spreadsheets in the Eden database': 'Store spreadsheets in the Eden database', 'Storeys at and above ground level': 'Storeys at and above ground level', 'Storm Force Wind': 'Storm Force Wind', 'Storm Surge': 'Storm Surge', 'Stowaway': 'Stowaway', 'Strategy': 'Strategy', 'Street Address': 'Street Address', 'Streetview Enabled?': 'Streetview Enabled?', 'Strong Wind': 'Strong Wind', 'Structural': 'Structural', 'Structural Hazards': 'Structural Hazards', 'Style': 'Style', 'Style Field': 'Style Field', 'Style Values': 'Style Values', 'Subject': 'Subject', 'Submission successful - please wait': 'Submission successful - please wait', 'Submit': 'Submit', 'Submit New': 'Submit New', 'Submit New (full form)': 'Submit New (full form)', 'Submit New (triage)': 'Submit New (triage)', 'Submit a request for recovery': 'Submit a request for recovery', 'Submit new Level 1 assessment (full form)': 'Submit new Level 1 assessment (full form)', 'Submit new Level 1 assessment (triage)': 'Submit new Level 1 assessment (triage)', 'Submit new Level 2 assessment': 'Submit new Level 2 assessment', 'Subscribe': 'Subscribe', 'Subscription Details': 'Subscription Details', 'Subscription added': 'Subscription added', 'Subscription deleted': 'Subscription deleted', 'Subscription updated': 'Subscription updated', 'Subscriptions': 'Subscriptions', 'Subsector': 'Subsector', 'Subsector Details': 'Subsector Details', 'Subsector added': 'Subsector added', 'Subsector deleted': 'Subsector deleted', 'Subsector updated': 'Subsector updated', 'Subsectors': 'Subsectors', 'Subsistence Cost': 'Subsistence Cost', 'Suburb': 'Suburb', 'Suggest not changing this field unless you know what you are doing.': 'Suggest not changing this field unless you know what you are doing.', 'Summary': 'Summary', 'Summary by Administration Level': 'Summary by Administration Level', 'Summary by Question Type': 'Summary by Question Type', 'Summary of Responses within Series': 'Summary of Responses within Series', 'Sunday': 'Sunday', 'Supply Chain Management': 'Supply Chain Management', 'Supply Item Categories': 'Supply Item Categories', 'Support Request': 'Support Request', 'Support Requests': 'Support Requests', 'Supports the decision making of large groups of Crisis Management Experts by helping the groups create ranked list.': 'Supports the decision making of large groups of Crisis Management Experts by helping the groups create ranked list.', 'Surgery': 'Surgery', 'Survey Module': 'Survey Module', 'Surveys': 'Surveys', 'Symbology': 'Symbology', 'Synchronization': 'Synchronisation', 'Synchronization Job': 'Synchronisation Job', 'Synchronization Log': 'Synchronisation Log', 'Synchronization Schedule': 'Synchronisation Schedule', 'Synchronization Settings': 'Synchronisation Settings', 'Synchronization mode': 'Synchronisation mode', 'Synchronization settings updated': 'Synchronisation settings updated', 'Synchronize now': 'Synchronise now', "System's Twitter account updated": "System's Twitter account updated", 'Table name of the resource to synchronize': 'Table name of the resource to synchronise', 'Tags': 'Tags', 'Take shelter in place or per <instruction>': 'Take shelter in place or per <instruction>', 'Task': 'Task', 'Task Details': 'Task Details', 'Task List': 'Task List', 'Task Status': 'Task Status', 'Task added': 'Task added', 'Task deleted': 'Task deleted', 'Task removed': 'Task removed', 'Task updated': 'Task updated', 'Tasks': 'Tasks', 'Team Description': 'Team Description', 'Team Details': 'Team Details', 'Team ID': 'Team ID', 'Team Leader': 'Team Leader', 'Team Member added': 'Team Member added', 'Team Members': 'Team Members', 'Team Name': 'Team Name', 'Team Type': 'Team Type', 'Team added': 'Team added', 'Team deleted': 'Team deleted', 'Team updated': 'Team updated', 'Teams': 'Teams', 'Technical testing only, all recipients disregard': 'Technical testing only, all recipients disregard', 'Telecommunications': 'Telecommunications', 'Telephone': 'Telephone', 'Telephone Details': 'Telephone Details', 'Telephony': 'Telephony', 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.': 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.', 'Temp folder %s not writable - unable to apply theme!': 'Temp folder %s not writable - unable to apply theme!', 'Template': 'Template', 'Template Name': 'Template Name', 'Template Section Details': 'Template Section Details', 'Template Section added': 'Template Section added', 'Template Section deleted': 'Template Section deleted', 'Template Section updated': 'Template Section updated', 'Template Sections': 'Template Sections', 'Template Summary': 'Template Summary', 'Template file %s not readable - unable to apply theme!': 'Template file %s not readable - unable to apply theme!', 'Templates': 'Templates', 'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.': 'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.', 'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).': 'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).', 'Term for the primary within-country administrative division (e.g. State or Province).': 'Term for the primary within-country administrative division (e.g. State or Province).', 'Term for the secondary within-country administrative division (e.g. District or County).': 'Term for the secondary within-country administrative division (e.g. District or County).', 'Term for the third-level within-country administrative division (e.g. City or Town).': 'Term for the third-level within-country administrative division (e.g. City or Town).', 'Term for the top-level administrative division (i.e. Country).': 'Term for the top-level administrative division (i.e. Country).', 'Terms of Service\n\nYou have to be eighteen or over to register as a volunteer.': 'Terms of Service\n\nYou have to be eighteen or over to register as a volunteer.', 'Terms of Service:': 'Terms of Service:', 'Territorial Authority': 'Territorial Authority', 'Terrorism': 'Terrorism', 'Tertiary Server (Optional)': 'Tertiary Server (Optional)', 'Text': 'Text', 'Text Color for Text blocks': 'Text Colour for Text blocks', 'Thank you for validating your email. Your user account is still pending for approval by the system administator (%s).You will get a notification by email when your account is activated.': 'Thank you for validating your email. Your user account is still pending for approval by the system administator (%s).You will get a notification by email when your account is activated.', 'Thanks for your assistance': 'Thanks for your assistance', 'The': 'The', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.', 'The Area which this Site is located within.': 'The Area which this Site is located within.', 'The Assessment Module stores assessment templates and allows responses to assessments for specific events to be collected and analysed': 'The Assessment Module stores assessment templates and allows responses to assessments for specific events to be collected and analysed', 'The Assessments module allows field workers to send in assessments.': 'The Assessments module allows field workers to send in assessments.', 'The Author of this Document (optional)': 'The Author of this Document (optional)', 'The Building Asssesments module allows building safety to be assessed, e.g. after an Earthquake.': 'The Building Asssesments module allows building safety to be assessed, e.g. after an Earthquake.', 'The Camp this Request is from': 'The Camp this Request is from', 'The Camp this person is checking into.': 'The Camp this person is checking into.', 'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.', "The Donor(s) for this project. Multiple values can be selected by holding down the 'Control' key.": "The Donor(s) for this project. Multiple values can be selected by holding down the 'Control' key.", 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.': 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.', 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.': 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.', 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.', 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.', 'The Media Library provides a catalog of digital media.': 'The Media Library provides a catalogue of digital media.', 'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': 'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.', 'The Organization Registry keeps track of all the relief organizations working in the area.': 'The Organisation Registry keeps track of all the relief organisations working in the area.', 'The Patient Tracking system keeps track of all the evacuated patients & their relatives.': 'The Patient Tracking system keeps track of all the evacuated patients & their relatives.', "The Project Tool can be used to record project Information and generate Who's Doing What Where Reports.": "The Project Tool can be used to record project Information and generate Who's Doing What Where Reports.", 'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.': 'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.', 'The Role this person plays within this hospital.': 'The Role this person plays within this hospital.', 'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.': 'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.', 'The Shelter this Request is from': 'The Shelter this Request is from', 'The Shelter this person is checking into.': 'The Shelter this person is checking into.', 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.', "The URL of the image file. If you don't upload an image file, then you must specify its location here.": "The URL of the image file. If you don't upload an image file, then you must specify its location here.", 'The URL of your web gateway without the post parameters': 'The URL of your web gateway without the post parameters', 'The URL to access the service.': 'The URL to access the service.', 'The Unique Identifier (UUID) as assigned to this facility by the government.': 'The Unique Identifier (UUID) as assigned to this facility by the government.', 'The area is': 'The area is', 'The asset must be assigned to a site OR location.': 'The asset must be assigned to a site OR location.', 'The attribute which is used for the title of popups.': 'The attribute which is used for the title of popups.', 'The attribute within the KML which is used for the title of popups.': 'The attribute within the KML which is used for the title of popups.', 'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)': 'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)', 'The body height (crown to heel) in cm.': 'The body height (crown to heel) in cm.', 'The country the person usually lives in.': 'The country the person usually lives in.', 'The default Facility for which this person is acting.': 'The default Facility for which this person is acting.', 'The default Facility for which you are acting.': 'The default Facility for which you are acting.', 'The default Organization for whom this person is acting.': 'The default Organisation for whom this person is acting.', 'The default Organization for whom you are acting.': 'The default Organisation for whom you are acting.', 'The duplicate record will be deleted': 'The duplicate record will be deleted', 'The first or only name of the person (mandatory).': 'The first or only name of the person (mandatory).', 'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.': 'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.', 'The language you wish the site to be displayed in.': 'The language you wish the site to be displayed in.', 'The length is': 'The length is', 'The level at which Searches are filtered.': 'The level at which Searches are filtered.', 'The list of Brands are maintained by the Administrators.': 'The list of Brands are maintained by the Administrators.', 'The list of Catalogs are maintained by the Administrators.': 'The list of Catalogues are maintained by the Administrators.', 'The map will be displayed initially with this latitude at the center.': 'The map will be displayed initially with this latitude at the center.', 'The map will be displayed initially with this longitude at the center.': 'The map will be displayed initially with this longitude at the center.', 'The minimum number of characters is ': 'The minimum number of characters is ', 'The minimum number of features to form a cluster.': 'The minimum number of features to form a cluster.', 'The name to be used when calling for or directly addressing the person (optional).': 'The name to be used when calling for or directly addressing the person (optional).', 'The next screen will allow you to detail the number of people here & their needs.': 'The next screen will allow you to detail the number of people here & their needs.', 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item', 'The number of pixels apart that features need to be before they are clustered.': 'The number of pixels apart that features need to be before they are clustered.', 'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.': 'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.', 'The person at the location who is reporting this incident (optional)': 'The person at the location who is reporting this incident (optional)', 'The post variable containing the phone number': 'The post variable containing the phone number', 'The post variable on the URL used for sending messages': 'The post variable on the URL used for sending messages', 'The post variables other than the ones containing the message and the phone number': 'The post variables other than the ones containing the message and the phone number', 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows': 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows', 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.': 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.', 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.': 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.', 'The site where this position is based.': 'The site where this position is based.', 'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.': 'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.', 'The subject event no longer poses a threat or concern and any follow on action is described in <instruction>': 'The subject event no longer poses a threat or concern and any follow on action is described in <instruction>', 'The synchronization module allows the synchronization of data resources between Sahana Eden instances.': 'The synchronisation module allows the synchronisation of data resources between Sahana Eden instances.', 'The time at which the Event started.': 'The time at which the Event started.', 'The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones.': 'The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones.', 'The token associated with this application on': 'The token associated with this application on', 'The way in which an item is normally distributed': 'The way in which an item is normally distributed', 'The weight in kg.': 'The weight in kg.', 'Theme': 'Theme', 'Theme Details': 'Theme Details', 'Theme added': 'Theme added', 'Theme deleted': 'Theme deleted', 'Theme updated': 'Theme updated', 'Themes': 'Themes', 'There are errors': 'There are errors', 'There are insufficient items in the Inventory to send this shipment': 'There are insufficient items in the Inventory to send this shipment', 'There are multiple records at this location': 'There are multiple records at this location', 'There is no address for this person yet. Add new address.': 'There is no address for this person yet. Add new address.', 'There was a problem, sorry, please try again later.': 'There was a problem, sorry, please try again later.', 'These are settings for Inbound Mail.': 'These are settings for Inbound Mail.', 'These are the Incident Categories visible to normal End-Users': 'These are the Incident Categories visible to normal End-Users', 'These need to be added in Decimal Degrees.': 'These need to be added in Decimal Degrees.', 'They': 'They', 'This appears to be a duplicate of ': 'This appears to be a duplicate of ', 'This email address is already in use': 'This email address is already in use', 'This file already exists on the server as': 'This file already exists on the server as', 'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.': 'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.', 'This is the way to transfer data between machines as it maintains referential integrity.': 'This is the way to transfer data between machines as it maintains referential integrity.', 'This is the way to transfer data between machines as it maintains referential integrity...duplicate data should be removed manually 1st!': 'This is the way to transfer data between machines as it maintains referential integrity...duplicate data should be removed manually 1st!', 'This level is not open for editing.': 'This level is not open for editing.', 'This might be due to a temporary overloading or maintenance of the server.': 'This might be due to a temporary overloading or maintenance of the server.', 'This module allows Inventory Items to be Requested & Shipped between the Inventories of Facilities.': 'This module allows Inventory Items to be Requested & Shipped between the Inventories of Facilities.', 'This module allows you to manage Events - whether pre-planned (e.g. exercises) or Live Incidents. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.': 'This module allows you to manage Events - whether pre-planned (e.g. exercises) or Live Incidents. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.', 'This module allows you to plan scenarios for both Exercises & Events. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.': 'This module allows you to plan scenarios for both Exercises & Events. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.', 'This resource is already configured for this repository': 'This resource is already configured for this repository', 'This screen allows you to upload a collection of photos to the server.': 'This screen allows you to upload a collection of photos to the server.', 'This setting can only be controlled by the Administrator.': 'This setting can only be controlled by the Administrator.', 'This shipment has already been received.': 'This shipment has already been received.', 'This shipment has already been sent.': 'This shipment has already been sent.', 'This shipment has not been received - it has NOT been canceled because can still be edited.': 'This shipment has not been received - it has NOT been canceled because can still be edited.', 'This shipment has not been sent - it has NOT been canceled because can still be edited.': 'This shipment has not been sent - it has NOT been canceled because can still be edited.', 'This shipment will be confirmed as received.': 'This shipment will be confirmed as received.', 'Thunderstorm': 'Thunderstorm', 'Thursday': 'Thursday', 'Ticket': 'Ticket', 'Ticket Details': 'Ticket Details', 'Ticket ID': 'Ticket ID', 'Ticket added': 'Ticket added', 'Ticket deleted': 'Ticket deleted', 'Ticket updated': 'Ticket updated', 'Ticketing Module': 'Ticketing Module', 'Tickets': 'Tickets', 'Tiled': 'Tiled', 'Tilt-up concrete': 'Tilt-up concrete', 'Timber frame': 'Timber frame', 'Timeline': 'Timeline', 'Timeline Report': 'Timeline Report', 'Timestamp': 'Timestamp', 'Timestamps can be correlated with the timestamps on the photos to locate them on the map.': 'Timestamps can be correlated with the timestamps on the photos to locate them on the map.', 'Title': 'Title', 'Title to show for the Web Map Service panel in the Tools panel.': 'Title to show for the Web Map Service panel in the Tools panel.', 'To': 'To', 'To Location': 'To Location', 'To Person': 'To Person', 'To create a personal map configuration, click ': 'To create a personal map configuration, click ', 'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in models/000_config.py': 'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in models/000_config.py', 'To search by job title, enter any portion of the title. You may use % as wildcard.': 'To search by job title, enter any portion of the title. You may use % as wildcard.', "To search by person name, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "To search by person name, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.", "To search for a body, enter the ID tag number of the body. You may use % as wildcard. Press 'Search' without input to list all bodies.": "To search for a body, enter the ID tag number of the body. You may use % as wildcard. Press 'Search' without input to list all bodies.", "To search for a hospital, enter any of the names or IDs of the hospital, or the organisation name or acronym, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.": "To search for a hospital, enter any of the names or IDs of the hospital, or the organisation name or acronym, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.", "To search for a hospital, enter any of the names or IDs of the hospital, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.": "To search for a hospital, enter any of the names or IDs of the hospital, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.", "To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.": "To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.", "To search for a patient, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all patients.": "To search for a patient, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all patients.", "To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.", "To search for an assessment, enter any portion the ticket number of the assessment. You may use % as wildcard. Press 'Search' without input to list all assessments.": "To search for an assessment, enter any portion the ticket number of the assessment. You may use % as wildcard. Press 'Search' without input to list all assessments.", 'To variable': 'To variable', 'Tools': 'Tools', 'Tornado': 'Tornado', 'Total': 'Total', 'Total # of Target Beneficiaries': 'Total # of Target Beneficiaries', 'Total # of households of site visited': 'Total # of households of site visited', 'Total Beds': 'Total Beds', 'Total Beneficiaries': 'Total Beneficiaries', 'Total Cost per Megabyte': 'Total Cost per Megabyte', 'Total Cost per Minute': 'Total Cost per Minute', 'Total Monthly': 'Total Monthly', 'Total Monthly Cost': 'Total Monthly Cost', 'Total Monthly Cost: ': 'Total Monthly Cost: ', 'Total One-time Costs': 'Total One-time Costs', 'Total Persons': 'Total Persons', 'Total Recurring Costs': 'Total Recurring Costs', 'Total Unit Cost': 'Total Unit Cost', 'Total Unit Cost: ': 'Total Unit Cost: ', 'Total Units': 'Total Units', 'Total gross floor area (square meters)': 'Total gross floor area (square meters)', 'Total number of beds in this hospital. Automatically updated from daily reports.': 'Total number of beds in this hospital. Automatically updated from daily reports.', 'Total number of houses in the area': 'Total number of houses in the area', 'Total number of schools in affected area': 'Total number of schools in affected area', 'Total population of site visited': 'Total population of site visited', 'Totals for Budget:': 'Totals for Budget:', 'Totals for Bundle:': 'Totals for Bundle:', 'Totals for Kit:': 'Totals for Kit:', 'Tourist Group': 'Tourist Group', 'Town': 'Town', 'Traces internally displaced people (IDPs) and their needs': 'Traces internally displaced people (IDPs) and their needs', 'Track with this Person?': 'Track with this Person?', 'Tracking of Patients': 'Tracking of Patients', 'Tracking of Projects, Activities and Tasks': 'Tracking of Projects, Activities and Tasks', 'Tracking of basic information on the location, facilities and size of the Shelters': 'Tracking of basic information on the location, facilities and size of the Shelters', 'Tracks the location, capacity and breakdown of victims in Shelters': 'Tracks the location, capacity and breakdown of victims in Shelters', 'Traffic Report': 'Traffic Report', 'Training': 'Training', 'Training Course Catalog': 'Training Course Catalogue', 'Training Details': 'Training Details', 'Training added': 'Training added', 'Training deleted': 'Training deleted', 'Training updated': 'Training updated', 'Trainings': 'Trainings', 'Transit': 'Transit', 'Transit Status': 'Transit Status', 'Transition Effect': 'Transition Effect', 'Transparent?': 'Transparent?', 'Transportation Required': 'Transportation Required', 'Transportation assistance, Rank': 'Transportation assistance, Rank', 'Trauma Center': 'Trauma Center', 'Travel Cost': 'Travel Cost', 'Tropical Storm': 'Tropical Storm', 'Tropo Messaging Token': 'Tropo Messaging Token', 'Tropo Voice Token': 'Tropo Voice Token', 'Tropo settings updated': 'Tropo settings updated', 'Truck': 'Truck', 'Try checking the URL for errors, maybe it was mistyped.': 'Try checking the URL for errors, maybe it was mistyped.', 'Try hitting refresh/reload button or trying the URL from the address bar again.': 'Try hitting refresh/reload button or trying the URL from the address bar again.', 'Try refreshing the page or hitting the back button on your browser.': 'Try refreshing the page or hitting the back button on your browser.', 'Tsunami': 'Tsunami', 'Tuesday': 'Tuesday', 'Twitter': 'Twitter', 'Twitter ID or #hashtag': 'Twitter ID or #hashtag', 'Twitter Settings': 'Twitter Settings', 'Type': 'Type', 'Type of Construction': 'Type of Construction', 'Type of water source before the disaster': 'Type of water source before the disaster', "Type the first few characters of one of the Person's names.": "Type the first few characters of one of the Person's names.", 'UN': 'UN', 'URL': 'URL', 'URL of the default proxy server to connect to remote repositories (if required). If only some of the repositories require the use of a proxy server, you can configure this in the respective repository configuration.': 'URL of the default proxy server to connect to remote repositories (if required). If only some of the repositories require the use of a proxy server, you can configure this in the respective repository configuration.', 'URL of the proxy server to connect to this repository (leave empty for default proxy)': 'URL of the proxy server to connect to this repository (leave empty for default proxy)', 'UTC Offset': 'UTC Offset', 'UUID': 'UUID', 'Un-Repairable': 'Un-Repairable', 'Unable to parse CSV file!': 'Unable to parse CSV file!', 'Under which condition a local record shall be updated if it also has been modified locally since the last synchronization': 'Under which condition a local record shall be updated if it also has been modified locally since the last synchronisation', 'Under which conditions local records shall be updated': 'Under which conditions local records shall be updated', 'Understaffed': 'Understaffed', 'Unidentified': 'Unidentified', 'Unique identifier which THIS repository identifies itself with when sending synchronization requests.': 'Unique identifier which THIS repository identifies itself with when sending synchronisation requests.', 'Unit Cost': 'Unit Cost', 'Unit added': 'Unit added', 'Unit deleted': 'Unit deleted', 'Unit of Measure': 'Unit of Measure', 'Unit updated': 'Unit updated', 'United States Dollars': 'United States Dollars', 'Units': 'Units', 'Universally unique identifier for the local repository, needed to register the local repository at remote instances to allow push-synchronization.': 'Universally unique identifier for the local repository, needed to register the local repository at remote instances to allow push-synchronisation.', 'Unknown': 'Unknown', 'Unknown type of facility': 'Unknown type of facility', 'Unreinforced masonry': 'Unreinforced masonry', 'Unsafe': 'Unsafe', 'Unselect to disable the modem': 'Unselect to disable the modem', 'Unselect to disable this API service': 'Unselect to disable this API service', 'Unselect to disable this SMTP service': 'Unselect to disable this SMTP service', 'Unsent': 'Unsent', 'Unsubscribe': 'Unsubscribe', 'Unsupported data format!': 'Unsupported data format!', 'Unsupported method!': 'Unsupported method!', 'Update': 'Update', 'Update Activity Report': 'Update Activity Report', 'Update Cholera Treatment Capability Information': 'Update Cholera Treatment Capability Information', 'Update Method': 'Update Method', 'Update Policy': 'Update Policy', 'Update Request': 'Update Request', 'Update Service Profile': 'Update Service Profile', 'Update Status': 'Update Status', 'Update Task Status': 'Update Task Status', 'Update Unit': 'Update Unit', 'Update your current ordered list': 'Update your current ordered list', 'Updated By': 'Updated By', 'Upload Comma Separated Value File': 'Upload Comma Separated Value File', 'Upload Format': 'Upload Format', 'Upload Photos': 'Upload Photos', 'Upload Scanned OCR Form': 'Upload Scanned OCR Form', 'Upload Spreadsheet': 'Upload Spreadsheet', 'Upload Web2py portable build as a zip file': 'Upload Web2py portable build as a zip file', 'Upload a Assessment Template import file': 'Upload a Assessment Template import file', 'Upload a CSV file': 'Upload a CSV file', 'Upload a CSV file formatted according to the Template.': 'Upload a CSV file formatted according to the Template.', 'Upload a Question List import file': 'Upload a Question List import file', 'Upload a Spreadsheet': 'Upload a Spreadsheet', 'Upload an image file (bmp, gif, jpeg or png), max. 300x300 pixels!': 'Upload an image file (bmp, gif, jpeg or png), max. 300x300 pixels!', 'Upload an image file here.': 'Upload an image file here.', "Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.": "Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.", 'Upload an image, such as a photo': 'Upload an image, such as a photo', 'Upload the Completed Assessments import file': 'Upload the Completed Assessments import file', 'Uploaded': 'Uploaded', 'Urban Fire': 'Urban Fire', 'Urban area': 'Urban area', 'Urdu': 'Urdu', 'Urgent': 'Urgent', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'Use Geocoder for address lookups?': 'Use Geocoder for address lookups?', 'Use default': 'Use default', 'Use these links to download data that is currently in the database.': 'Use these links to download data that is currently in the database.', 'Use this to set the starting location for the Location Selector.': 'Use this to set the starting location for the Location Selector.', 'Used by IRS & Assess': 'Used by IRS & Assess', 'Used in onHover Tooltip & Cluster Popups to differentiate between types.': 'Used in onHover Tooltip & Cluster Popups to differentiate between types.', 'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.': 'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.', 'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.', 'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.', 'Used to import data from spreadsheets into the database': 'Used to import data from spreadsheets into the database', 'Used within Inventory Management, Request Management and Asset Management': 'Used within Inventory Management, Request Management and Asset Management', 'User': 'User', 'User %(id)s Logged-in': 'User %(id)s Logged-in', 'User %(id)s Registered': 'User %(id)s Registered', 'User Account has been Approved': 'User Account has been Approved', 'User Account has been Disabled': 'User Account has been Disabled', 'User Details': 'User Details', 'User Guidelines Synchronization': 'User Guidelines Synchronisation', 'User ID': 'User ID', 'User Management': 'User Management', 'User Profile': 'User Profile', 'User Requests': 'User Requests', 'User Updated': 'User Updated', 'User added': 'User added', 'User already has this role': 'User already has this role', 'User deleted': 'User deleted', 'User updated': 'User updated', 'Username': 'Username', 'Username to use for authentication at the remote site': 'Username to use for authentication at the remote site', 'Users': 'Users', 'Users removed': 'Users removed', 'Uses the REST Query Format defined in': 'Uses the REST Query Format defined in', 'Utilities': 'Utilities', 'Utility, telecommunication, other non-transport infrastructure': 'Utility, telecommunication, other non-transport infrastructure', 'Value': 'Value', 'Value per Pack': 'Value per Pack', 'Various Reporting functionalities': 'Various Reporting functionalities', 'Vehicle': 'Vehicle', 'Vehicle Crime': 'Vehicle Crime', 'Vehicle Details': 'Vehicle Details', 'Vehicle Details added': 'Vehicle Details added', 'Vehicle Details deleted': 'Vehicle Details deleted', 'Vehicle Details updated': 'Vehicle Details updated', 'Vehicle Management': 'Vehicle Management', 'Vehicle Types': 'Vehicle Types', 'Vehicle added': 'Vehicle added', 'Vehicle deleted': 'Vehicle deleted', 'Vehicle updated': 'Vehicle updated', 'Vehicles': 'Vehicles', 'Vehicles are assets with some extra details.': 'Vehicles are assets with some extra details.', 'Verification Status': 'Verification Status', 'Verified?': 'Verified?', 'Verify Password': '<PASSWORD>', 'Verify password': '<PASSWORD>', 'Version': 'Version', 'Very Good': 'Very Good', 'Very High': 'Very High', 'Vietnamese': 'Vietnamese', 'View Alerts received using either Email or SMS': 'View Alerts received using either Email or SMS', 'View All': 'View All', 'View All Tickets': 'View All Tickets', 'View Error Tickets': 'View Error Tickets', 'View Fullscreen Map': 'View Fullscreen Map', 'View Image': 'View Image', 'View Items': 'View Items', 'View Location Details': 'View Location Details', 'View Outbox': 'View Outbox', 'View Picture': 'View Picture', 'View Results of completed and/or partially completed assessments': 'View Results of completed and/or partially completed assessments', 'View Settings': 'View Settings', 'View Tickets': 'View Tickets', 'View all log entries': 'View all log entries', 'View and/or update their details': 'View and/or update their details', 'View log entries per repository': 'View log entries per repository', 'View on Map': 'View on Map', 'View or update the status of a hospital.': 'View or update the status of a hospital.', 'View pending requests and pledge support.': 'View pending requests and pledge support.', 'View the hospitals on a map.': 'View the hospitals on a map.', 'View/Edit the Database directly': 'View/Edit the Database directly', 'Village': 'Village', 'Village Leader': 'Village Leader', 'Visual Recognition': 'Visual Recognition', 'Volcanic Ash Cloud': 'Volcanic Ash Cloud', 'Volcanic Event': 'Volcanic Event', 'Volume (m3)': 'Volume (m3)', 'Volunteer Availability': 'Volunteer Availability', 'Volunteer Details': 'Volunteer Details', 'Volunteer Information': 'Volunteer Information', 'Volunteer Management': 'Volunteer Management', 'Volunteer Project': 'Volunteer Project', 'Volunteer Record': 'Volunteer Record', 'Volunteer Request': 'Volunteer Request', 'Volunteer added': 'Volunteer added', 'Volunteer availability added': 'Volunteer availability added', 'Volunteer availability deleted': 'Volunteer availability deleted', 'Volunteer availability updated': 'Volunteer availability updated', 'Volunteers': 'Volunteers', 'Vote': 'Vote', 'Votes': 'Votes', 'WARNING': 'WARNING', 'WASH': 'WASH', 'Walking Only': 'Walking Only', 'Wall or other structural damage': 'Wall or other structural damage', 'Warehouse': 'Warehouse', 'Warehouse Details': 'Warehouse Details', 'Warehouse added': 'Warehouse added', 'Warehouse deleted': 'Warehouse deleted', 'Warehouse updated': 'Warehouse updated', 'Warehouses': 'Warehouses', 'WatSan': 'WatSan', 'Water Sanitation Hygiene': 'Water Sanitation Hygiene', 'Water collection': 'Water collection', 'Water gallon': 'Water gallon', 'Water storage containers in households': 'Water storage containers in households', 'Water supply': 'Water supply', 'Waterspout': 'Waterspout', 'We have tried': 'We have tried', 'Web API settings updated': 'Web API settings updated', 'Web Map Service Browser Name': 'Web Map Service Browser Name', 'Web Map Service Browser URL': 'Web Map Service Browser URL', 'Web2py executable zip file found - Upload to replace the existing file': 'Web2py executable zip file found - Upload to replace the existing file', 'Web2py executable zip file needs to be uploaded to use this function.': 'Web2py executable zip file needs to be uploaded to use this function.', 'Website': 'Website', 'Wednesday': 'Wednesday', 'Weight': 'Weight', 'Weight (kg)': 'Weight (kg)', 'Welcome to the': 'Welcome to the', 'Well-Known Text': 'Well-Known Text', 'What order to be contacted in.': 'What order to be contacted in.', 'What the Items will be used for': 'What the Items will be used for', 'Wheat': 'Wheat', 'When reports were entered': 'When reports were entered', 'Where Project is implemented, including activities and beneficiaries': 'Where Project is implemented, including activities and beneficiaries', 'Whether to accept unsolicited data transmissions from the repository': 'Whether to accept unsolicited data transmissions from the repository', 'Which methods to apply when importing data to the local repository': 'Which methods to apply when importing data to the local repository', 'Whiskers': 'Whiskers', 'Who is doing what and where': 'Who is doing what and where', 'Who usually collects water for the family?': 'Who usually collects water for the family?', 'Width (m)': 'Width (m)', 'Wild Fire': 'Wild Fire', 'Wind Chill': 'Wind Chill', 'Window frame': 'Window frame', 'Winter Storm': 'Winter Storm', 'With best regards': 'With best regards', 'Women of Child Bearing Age': 'Women of Child Bearing Age', 'Women participating in coping activities': 'Women participating in coping activities', 'Women who are Pregnant or in Labour': 'Women who are Pregnant or in Labour', 'Womens Focus Groups': 'Womens Focus Groups', 'Wooden plank': 'Wooden plank', 'Wooden poles': 'Wooden poles', 'Working hours end': 'Working hours end', 'Working hours start': 'Working hours start', 'Working or other to provide money/food': 'Working or other to provide money/food', 'X-Ray': 'X-Ray', 'YES': 'YES', "Yahoo Layers cannot be displayed if there isn't a valid API Key": "Yahoo Layers cannot be displayed if there isn't a valid API Key", 'Year': 'Year', 'Year built': 'Year built', 'Year of Manufacture': 'Year of Manufacture', 'Yellow': 'Yellow', 'Yes': 'Yes', 'You are a recovery team?': 'You are a recovery team?', 'You are attempting to delete your own account - are you sure you want to proceed?': 'You are attempting to delete your own account - are you sure you want to proceed?', 'You are currently reported missing!': 'You are currently reported missing!', 'You can click on the map below to select the Lat/Lon fields': 'You can click on the map below to select the Lat/Lon fields', 'You can select the Draw tool': 'You can select the Draw tool', 'You can set the modem settings for SMS here.': 'You can set the modem settings for SMS here.', 'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.': 'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.', 'You do not have permission for any facility to add an order.': 'You do not have permission for any facility to add an order.', 'You do not have permission for any facility to make a commitment.': 'You do not have permission for any facility to make a commitment.', 'You do not have permission for any facility to make a request.': 'You do not have permission for any facility to make a request.', 'You do not have permission for any facility to receive a shipment.': 'You do not have permission for any facility to receive a shipment.', 'You do not have permission for any facility to send a shipment.': 'You do not have permission for any facility to send a shipment.', 'You do not have permission for any site to add an inventory item.': 'You do not have permission for any site to add an inventory item.', 'You do not have permission to cancel this received shipment.': 'You do not have permission to cancel this received shipment.', 'You do not have permission to cancel this sent shipment.': 'You do not have permission to cancel this sent shipment.', 'You do not have permission to make this commitment.': 'You do not have permission to make this commitment.', 'You do not have permission to receive this shipment.': 'You do not have permission to receive this shipment.', 'You do not have permission to send a shipment from this site.': 'You do not have permission to send a shipment from this site.', 'You do not have permission to send this shipment.': 'You do not have permission to send this shipment.', 'You have a personal map configuration. To change your personal configuration, click ': 'You have a personal map configuration. To change your personal configuration, click ', 'You have found a dead body?': 'You have found a dead body?', "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.": "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.", "You haven't made any calculations": "You haven't made any calculations", 'You must be logged in to register volunteers.': 'You must be logged in to register volunteers.', 'You must be logged in to report persons missing or found.': 'You must be logged in to report persons missing or found.', 'You should edit Twitter settings in models/000_config.py': 'You should edit Twitter settings in models/000_config.py', 'Your current ordered list of solution items is shown below. You can change it by voting again.': 'Your current ordered list of solution items is shown below. You can change it by voting again.', 'Your post was added successfully.': 'Your post was added successfully.', 'Your request for Red Cross and Red Crescent Resource Mapping System (RMS) has been approved and you can now access the system at': 'Your request for Red Cross and Red Crescent Resource Mapping System (RMS) has been approved and you can now access the system at', 'ZIP Code': 'ZIP Code', 'Zero Hour': 'Zero Hour', 'Zinc roof': 'Zinc roof', 'Zoom': 'Zoom', 'Zoom In: click in the map or use the left mouse button and drag to create a rectangle': 'Zoom In: click in the map or use the left mouse button and drag to create a rectangle', 'Zoom Levels': 'Zoom Levels', 'Zoom Out: click in the map or use the left mouse button and drag to create a rectangle': 'Zoom Out: click in the map or use the left mouse button and drag to create a rectangle', 'Zoom to Current Location': 'Zoom to Current Location', 'Zoom to maximum map extent': 'Zoom to maximum map extent', 'access granted': 'access granted', 'active': 'active', 'added': 'added', 'allows a budget to be developed based on staff & equipment costs, including any admin overheads.': 'allows a budget to be developed based on staff & equipment costs, including any admin overheads.', 'allows for creation and management of assessments.': 'allows for creation and management of assessments.', 'always update': 'always update', 'an individual/team to do in 1-2 days': 'an individual/team to do in 1-2 days', 'assigned': 'assigned', 'average': 'average', 'black': 'black', 'blond': 'blond', 'blue': 'blue', 'brown': 'brown', 'business_damaged': 'business_damaged', 'by': 'by', 'by %(person)s': 'by %(person)s', 'c/o Name': 'c/o Name', 'can be used to extract data from spreadsheets and put them into database tables.': 'can be used to extract data from spreadsheets and put them into database tables.', 'cancelled': 'cancelled', 'caucasoid': 'caucasoid', 'check all': 'check all', 'click for more details': 'click for more details', 'click here': 'click here', 'completed': 'completed', 'consider': 'consider', 'curly': 'curly', 'currently registered': 'currently registered', 'dark': 'dark', 'data uploaded': 'data uploaded', 'database': 'database', 'database %s select': 'database %s select', 'days': 'days', 'db': 'db', 'deceased': 'deceased', 'delete all checked': 'delete all checked', 'deleted': 'deleted', 'design': 'design', 'diseased': 'diseased', 'displaced': 'displaced', 'divorced': 'divorced', 'done!': 'done!', 'duplicate': 'duplicate', 'edit': 'edit', 'eg. gas, electricity, water': 'eg. gas, electricity, water', 'enclosed area': 'enclosed area', 'enter a number between %(min)g and %(max)g': 'enter a number between %(min)g and %(max)g', 'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g', 'export as csv file': 'export as csv file', 'fat': 'fat', 'feedback': 'feedback', 'female': 'female', 'flush latrine with septic tank': 'flush latrine with septic tank', 'food_sources': 'food_sources', 'forehead': 'forehead', 'form data': 'form data', 'found': 'found', 'from Twitter': 'from Twitter', 'getting': 'getting', 'green': 'green', 'grey': 'grey', 'here': 'here', 'hours': 'hours', 'households': 'households', 'identified': 'identified', 'ignore': 'ignore', 'in Deg Min Sec format': 'in Deg Min Sec format', 'in GPS format': 'in GPS format', 'in Inv.': 'in Inv.', 'inactive': 'inactive', 'injured': 'injured', 'insert new': 'insert new', 'insert new %s': 'insert new %s', 'invalid': 'invalid', 'invalid request': 'invalid request', 'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.': 'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.', 'keeps track of all incoming tickets allowing them to be categorised & routed to the appropriate place for actioning.': 'keeps track of all incoming tickets allowing them to be categorised & routed to the appropriate place for actioning.', 'latrines': 'latrines', 'leave empty to detach account': 'leave empty to detach account', 'legend URL': 'legend URL', 'light': 'light', 'login': 'login', 'long': 'long', 'long>12cm': 'long>12cm', 'male': 'male', 'married': 'married', 'maxExtent': 'maxExtent', 'maxResolution': 'maxResolution', 'medium': 'medium', 'medium<12cm': 'medium<12cm', 'meters': 'meters', 'minutes': 'minutes', 'missing': 'missing', 'module allows the site administrator to configure various options.': 'module allows the site administrator to configure various options.', 'module helps monitoring the status of hospitals.': 'module helps monitoring the status of hospitals.', 'mongoloid': 'mongoloid', 'more': 'more', 'negroid': 'negroid', 'never': 'never', 'never update': 'never update', 'new': 'new', 'new record inserted': 'new record inserted', 'next 100 rows': 'next 100 rows', 'no': 'no', 'none': 'none', 'not specified': 'not specified', 'obsolete': 'obsolete', 'on': 'on', 'on %(date)s': 'on %(date)s', 'open defecation': 'open defecation', 'optional': 'optional', 'or import from csv file': 'or import from csv file', 'other': 'other', 'over one hour': 'over one hour', 'people': 'people', 'piece': 'piece', 'pit': 'pit', 'pit latrine': 'pit latrine', 'postponed': 'postponed', 'preliminary template or draft, not actionable in its current form': 'preliminary template or draft, not actionable in its current form', 'previous 100 rows': 'previous 100 rows', 'pull': 'pull', 'pull and push': 'pull and push', 'push': 'push', 'record does not exist': 'record does not exist', 'record id': 'record id', 'red': 'red', 'replace': 'replace', 'reports successfully imported.': 'reports successfully imported.', 'representation of the Polygon/Line.': 'representation of the Polygon/Line.', 'retired': 'retired', 'retry': 'retry', 'river': 'river', 'see comment': 'see comment', 'selected': 'selected', 'separated': 'separated', 'separated from family': 'separated from family', 'shaved': 'shaved', 'short': 'short', 'short<6cm': 'short<6cm', 'sides': 'sides', 'sign-up now': 'sign-up now', 'single': 'single', 'slim': 'slim', 'specify': 'specify', 'staff': 'staff', 'staff members': 'staff members', 'state': 'state', 'state location': 'state location', 'straight': 'straight', 'suffered financial losses': 'suffered financial losses', 'table': 'table', 'tall': 'tall', 'times and it is still not working. We give in. Sorry.': 'times and it is still not working. We give in. Sorry.', 'to access the system': 'to access the system', 'to download a OCR Form.': 'to download a OCR Form.', 'to reset your password': '<PASSWORD>', 'to verify your email': 'to verify your email', 'tonsure': 'tonsure', 'total': 'total', 'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!': 'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!', 'unable to parse csv file': 'unable to parse csv file', 'uncheck all': 'uncheck all', 'unidentified': 'unidentified', 'unknown': 'unknown', 'unspecified': 'unspecified', 'unverified': 'unverified', 'update': 'update', 'update if master': 'update if master', 'update if newer': 'update if newer', 'updated': 'updated', 'verified': 'verified', 'volunteer': 'volunteer', 'volunteers': 'volunteers', 'wavy': 'wavy', 'weeks': 'weeks', 'white': 'white', 'wider area, longer term, usually contain multiple Activities': 'wider area, longer term, usually contain multiple Activities', 'widowed': 'widowed', 'within human habitat': 'within human habitat', 'xlwt module not available within the running Python - this needs installing for XLS output!': 'xlwt module not available within the running Python - this needs installing for XLS output!', 'yes': 'yes', }
michaelcw02/PrograIV
I/Ejercicio 10 Practica Examen/PracticaExamen/js/estudiante.js
function Estudiante (carnet, apellidos, nombre, examenes) { this.Estudiante(carnet, apellidos, nombre, examenes); } Estudiante.prototype = { Estudiante: function (carnet, apellidos, nombre, examenes) { this.carnet = carnet; this.apellidos = apellidos; this.nombre = nombre; this.examenes = examenes; } }
longluo/leetcode
Java/src/com/longluo/leetcode/array/Problem1588_sumOfAllOddLengthSubarrays.java
<reponame>longluo/leetcode package com.longluo.leetcode.array; /** * 1588. 所有奇数长度子数组的和 * <p> * 给你一个正整数数组 arr ,请你计算所有可能的奇数长度子数组的和。 * 子数组 定义为原数组中的一个连续子序列。 * 请你返回 arr 中 所有奇数长度子数组的和 。 * <p> * 示例 1: * 输入:arr = [1,4,2,5,3] * 输出:58 * 解释:所有奇数长度子数组和它们的和为: * [1] = 1 * [4] = 4 * [2] = 2 * [5] = 5 * [3] = 3 * [1,4,2] = 7 * [4,2,5] = 11 * [2,5,3] = 10 * [1,4,2,5,3] = 15 * 我们将所有值求和得到 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 * <p> * 示例 2: * 输入:arr = [1,2] * 输出:3 * 解释:总共只有 2 个长度为奇数的子数组,[1] 和 [2]。它们的和为 3 。 * <p> * 示例 3: * 输入:arr = [10,11,12] * 输出:66 * <p> * 提示: * 1 <= arr.length <= 100 * 1 <= arr[i] <= 1000 * <p> * https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays/ */ public class Problem1588_sumOfAllOddLengthSubarrays { public static int sumOddLengthSubarrays(int[] arr) { if (arr == null || arr.length == 0) { return 0; } int sum = 0; int n = arr.length; for (int start = 0; start < n; start++) { for (int length = 1; start + length <= n; length += 2) { int end = start + length - 1; for (int i = start; i <= end; i++) { sum += arr[i]; } } } return sum; } public static void main(String[] args) { System.out.println("3 ?= " + sumOddLengthSubarrays(new int[]{1, 2})); System.out.println("58 ?= " + sumOddLengthSubarrays(new int[]{1, 4, 2, 5, 3})); System.out.println("66 ?= " + sumOddLengthSubarrays(new int[]{10, 11, 12})); } }
smortex/go-choria
client/choria_utilclient/doc.go
// generated code; DO NOT EDIT" // // Client for Choria RPC Agent 'choria_util' Version 0.22.0 generated using Choria version 0.22.0 // Package choria_utilclient is an API client to the Choria Choria_util agent Version 0.22.0. // // Actions: // * Info - Choria related information from the running Daemon and Middleware // * MachineState - Retrieves the current state of a specific Choria Autonomous Agent // * MachineStates - States of the hosted Choria Autonomous Agents // * MachineTransition - Attempts to force a transition in a hosted Choria Autonomous Agent package choria_utilclient
billbrod/foveated-metamers
foveated_metamers/curve_fit.py
<reponame>billbrod/foveated-metamers<gh_stars>0 #!/usr/bin/env python3 """Code to fit the psychophysical curve to data.""" import torch # this is a wrapper and drop-in replacement for multiprocessing: # https://pytorch.org/docs/stable/multiprocessing.html import torch.multiprocessing as mp import inspect from collections import OrderedDict import numpy as np import pandas as pd from tqdm import tqdm import seaborn as sns import matplotlib.pyplot as plt import matplotlib as mpl def calculate_discriminability(scaling, proportionality_factor, critical_scaling): r"""Calculate disriminability at given scaling, for specified parameters. This comes from the Online Methods section of [1]_, equation 17. Parameters ---------- scaling : torch.Tensor or np.ndarray Scaling value(s) to calculate discriminability for. proportionality_factor : torch.Tensor or float The "gain" of the curve, determines how quickly it rises, parameter $\alpha_0$ in [1]_, equation 17. This will vary more across subjects and isn't as directly relevant for this study. critical_scaling : torch.Tensor or float The "threshold" of the curve, the scaling value at which discriminability falls to 0 and thus performance falls to chance, parameter $s_0$ in [1]_, equation 17. This should be more consistent, and is the focus of this study. Returns ------- discrim : torch.tensor discriminability ($d^2$ in [1]_) at each scaling value. References ---------- .. [1] <NAME>., & <NAME>. (2011). Metamers of the ventral stream. Nature Neuroscience, 14(9), 1195–1201. http://dx.doi.org/10.1038/nn.2889 """ if not isinstance(scaling, torch.Tensor): scaling = torch.tensor(scaling) vals = proportionality_factor * (1 - (critical_scaling**2 / scaling**2)) # this has to be non-negative return vals.clamp(min=0) def proportion_correct_curve(scaling, proportionality_factor, critical_scaling): r"""Compute the proportion correct curve, as function of parameters. This comes from the Online Methods section of [1]_, equation 18. Parameters ---------- scaling : torch.Tensor Scaling value(s) to calculate discriminability for. proportionality_factor : torch.Tensor or float The "gain" of the curve, determines how quickly it rises, parameter $\alpha_0$ in [1]_, equation 17. This will vary more across subjects and isn't as directly relevant for this study. critical_scaling : torch.Tensor or float The "threshold" of the curve, the scaling value at which discriminability falls to 0 and thus performance falls to chance, parameter $s_0$ in [1]_, equation 17. This should be more consistent, and is the focus of this study. Returns ------- proportion_correct : torch.tensor The proportion correct curve at each scaling value, as given by the parameter values References ---------- .. [1] <NAME>., & <NAME>. (2011). Metamers of the ventral stream. Nature Neuroscience, 14(9), 1195–1201. http://dx.doi.org/10.1038/nn.2889 """ norm = torch.distributions.Normal(0, 1) discrim = calculate_discriminability(scaling, proportionality_factor, critical_scaling) # we use the fact that norm.cdf(-x) = 1 - norm.cdf(x) to speed up the # following, which is equivalent to: norm.cdf(d/sqrt(2)) * norm.cdf(d/2) + # norm.cdf(-d/sqrt(2)) * norm.cdf(-d/2) norm_cdf_sqrt_2 = norm.cdf(discrim / np.sqrt(2)) norm_cdf_2 = norm.cdf(discrim / 2) return norm_cdf_sqrt_2 * norm_cdf_2 + (1-norm_cdf_sqrt_2) * (1-norm_cdf_2) def fit_psychophysical_parameters(scaling, proportion_correct, lr=.001, scheduler=True, max_iter=10000, seed=None, proportionality_factor_init_range=(1, 5), critical_scaling_init_range=(0, .5)): r"""Fit the parameters of psychophysical curve for a single set of values. This has trouble (unsurprisingly) if critical scaling falls too far outside the range of tested values. Also has issues if critical_scaling's initialization is too far outside of tested values (it seems less sensitive to proportionality_factor); default values seem to work pretty well. Loss is MSE between predicted proportion correct and ``proportion_correct``, plus a quadratic penalty on negative values of critical_scaling (``10*(critical_scaling)**2``, in order to make its magnitude matter when compared against the proportion correct MSE) Parameters ---------- scaling : torch.tensor The scaling values tested. proportion_correct : torch.tensor The proportion correct at each of those scaling values. lr : float, optional The learning rate for Adam optimizer. scheduler : bool, optional Whether to use the scheduler or not (reduces lr by half when loss appears to plateau). max_iter : int, optional The number of iterations to optimize for. seed : int or None, optional Seed to set pytorch's RNG with (we don't set numpy's, because we don't use any numpy function) proportionality_factor_init_range : tuple of floats, optional Range of values for initialization of proportionality_factor parameter (uniform distribution on this interval). If initialized value is too small, seems to have trouble finding a good solution. critical_scaling_init_range : tuple of floats, optional Range of values for initialization of critical_scaling parameter (uniform distribution on this interval). If initialized value is too large, seems to have trouble finding a good solution. Can tell because neither parameter changes. Should probably be the same as the range of ``scaling`` Returns ------- result : pd.DataFrame DataFrame with 6 columns and ``max_iter`` rows, containing the proportionality_factor, critical_scaling (both constant across iterations), iteration, loss, proportionality_factor_history, critical_scaling_history. """ if seed is not None: torch.manual_seed(seed) a_0 = torch.nn.Parameter(np.diff(proportionality_factor_init_range)[0]*torch.rand(1) + np.min(proportionality_factor_init_range)) s_0 = torch.nn.Parameter(np.diff(critical_scaling_init_range)[0]*torch.rand(1) + np.min(critical_scaling_init_range)) losses = [] a_0s = [] s_0s = [] optimizer = torch.optim.Adam([a_0, s_0], lr=lr) if scheduler: scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', .5) pbar = tqdm(range(max_iter)) for i in pbar: yhat = proportion_correct_curve(scaling, a_0, s_0) # MSE on proportion correct, plus a penalty on negative critical # scaling values loss = torch.sum((proportion_correct - yhat)**2) if s_0 < 0: # the sum is really unnecessary (s_0 will only ever be a single # value), but it makes sure that it's a 0d tensor, like loss. the # 10* is necessary to make it have enough weight to matter. loss += 10*(s_0 ** 2).sum() optimizer.zero_grad() loss.backward(retain_graph=True) optimizer.step() if scheduler: scheduler.step(loss.item()) pbar.set_postfix({'loss': loss.item(), 'a_0': a_0.item(), 's_0': s_0.item(), 'lr': optimizer.param_groups[0]['lr']}) losses.append(loss.item()) a_0s.append(a_0.item()) s_0s.append(s_0.item()) result = pd.DataFrame({'proportionality_factor': a_0.item(), 'critical_scaling': s_0.item(), 'loss': np.array(losses), 'proportionality_factor_history': np.array(a_0s), 'critical_scaling_history': np.array(s_0s), 'iteration': np.arange(max_iter)}) return result def multi_fit_psychophysical_parameters(kwargs, use_multiproc=True, n_processes=None, identifiers=[]): """Run fit_psychophysical_parameters multiple times, optionally using multiproc. Simple helper function to fit the psychophysical parameters multiple times, using either multiproc or a simple for loop. Parameters ---------- kwargs : list List of dictionaries to pass to ``fit_psychophysical_parameters``. We simply iterate through them and unpack on the call. use_multiproc : bool, optional Whether to use multiprocessing to parallelize across cores or not. n_processes : int or None, optional If ``use_multiproc`` is True, how many processes to run in parallel. If None, will be equal to ``os.cpu_count()``. If ``use_multiproc`` is False, this is ignored. identifiers : list, optional If not empty, list of dictionaries with same length as kwargs. Contains key: value pairs to add to the results from each run to identify them (e.g., different seeds, bootstrap numbers). Returns ------- results : pd.DataFrame DataFrame containing all the results. we add the values from args as additional columns, to differentiate among them. """ if len(identifiers) > 0 and len(identifiers) != len(kwargs): raise Exception("identifiers must be the same length as kwargs, but " f'got {len(identifiers)} and {len(kwargs)}!') if use_multiproc: # multiprocessing.pool does not allow for kwargs, so we have to # construct the args tuple. this is difficult because we don't know # whether the kwargs we've been passed has all the args or not. to # solve that, we grab the function signature (in order)... defaults = OrderedDict(inspect.signature(fit_psychophysical_parameters).parameters) # and iterate through the arguments for each dictionary in kwargs. if # that dictionary has the corresponding key, grab it; else, grab the # value from defaults args = [[kwarg.get(k, v.default) for k, v in defaults.items()] for kwarg in kwargs] # see https://github.com/pytorch/pytorch/wiki/Autograd-and-Fork for why # we use spawn ctx = mp.get_context('spawn') with ctx.Pool(n_processes) as pool: results = pool.starmap_async(fit_psychophysical_parameters, args) results = results.get() else: results = [] for kwarg in kwargs: results.append(fit_psychophysical_parameters(**kwarg)) for (iden, result) in zip(identifiers, results): for (k, v) in iden.items(): result[k] = v results = pd.concat(results) return results def plot_optimization_results(data, result, hue=None, fig=None, plot_data=True, plot_mean=False, **plot_kwargs): r"""Plot results of psychophysical curve fitting. Creates 5 plot figure: 1. Data and psychophysical curve 2. Loss over iterations 3. History of proportionality_factor values 4. History of critical_scaling values 5. Scatter plot showing initial and final values of the two parameters (critical_scaling on x, proportionality_factor on y) Intended to be called multiple time with, e.g., multiple bootstraps or optimization iterations. In order to do that, call this once with ``fig=None``, then pass the returned figure as the ``fig`` argument to subsequent calls (probably with ``plot_data=False``) Parameters ---------- data : pd.DataFrame data DataFrame containing columns for scaling and proportion correct. result : pd.DataFrame results DataFrame, as returned by ``fit_psychophysical_parameters``. can be from multiple fits, in which case hue must be set. hue : str or None, optional The variable in result to facet the hue on (we don't facet data) fig : plt.Figure or None, optional If not None, the figure to plot on. We don't check number of axes or add any more, so make sure you've created enough. plot_data : bool, optional Whether to plot data on the first axes or just the psychophysical curve plot_mean : bool, optional Whether to plot the (bootstrapped) mean across hue as well as the individual values. If so, we plot the individual values with a reduced alpha. This increases the amount of time this takes by a fair amount (roughly 3x; due to bootstrapping). plot_kwargs : passed to each plotting funtion. Returns ------- fig : plt.Figure Figure containing the plots """ alpha = 1 if plot_mean: alpha = .5 if fig is None: fig, axes = plt.subplots(1, 5, figsize=(25, 5)) else: axes = fig.axes prop_corr_curves = [] scaling = data.scaling.unique() if hue is None: gb = [(None, result)] else: gb = result.groupby(hue) for n, g in gb: if g.critical_scaling.nunique() > 1 or g.proportionality_factor.nunique() > 1: raise Exception("For a given hue value, need a single solution!") prop_corr = proportion_correct_curve(scaling, g.proportionality_factor.unique()[0], g.critical_scaling.unique()[0]) prop_corr = pd.DataFrame({'proportion_correct': prop_corr, 'scaling': scaling, hue: n}) prop_corr_curves.append(prop_corr) prop_corr_curves = pd.concat(prop_corr_curves) sns.lineplot(x='scaling', y='proportion_correct', hue=hue, ax=axes[0], data=prop_corr_curves, alpha=alpha, **plot_kwargs) if plot_mean: sns.lineplot(x='scaling', y='proportion_correct', ax=axes[0], data=prop_corr_curves, legend=False, color='k', **plot_kwargs) if plot_data: data_kwargs = plot_kwargs.copy() data_kwargs.update({'color': 'k', 'label': 'data'}) sns.lineplot(x='scaling', y='proportion_correct', ax=axes[0], data=data, marker='o', err_style='bars', linestyle='', **data_kwargs) axes[0].set(title='Data and psychophysical curve') sns.lineplot(x='iteration', y='loss', hue=hue, data=result, ax=axes[1], legend=False, alpha=alpha, **plot_kwargs) if plot_mean: sns.lineplot(x='iteration', y='loss', data=result, ax=axes[1], legend=False, color='k', **plot_kwargs) axes[1].set(title='Loss') sns.lineplot(x='iteration', y='proportionality_factor_history', hue=hue, data=result, ax=axes[2], legend=False, alpha=alpha, color='k', **plot_kwargs) if plot_mean: sns.lineplot(x='iteration', y='proportionality_factor_history', data=result, ax=axes[2], legend=False, color='k', **plot_kwargs) axes[2].set(title='Parameter history') sns.lineplot(x='iteration', y='critical_scaling_history', hue=hue, data=result, ax=axes[3], legend=False, alpha=alpha, **plot_kwargs) if plot_mean: sns.lineplot(x='iteration', y='critical_scaling_history', color='k', data=result, ax=axes[3], legend=False, **plot_kwargs) axes[3].set(title='Parameter history') reduced = pd.concat([result.groupby(hue).first().reset_index(), result.groupby(hue).last().reset_index()]) sns.lineplot(x='critical_scaling_history', y='proportionality_factor_history', hue=hue, data=reduced, ax=axes[4], alpha=alpha, legend=False, **plot_kwargs) sns.scatterplot(x='critical_scaling_history', y='proportionality_factor_history', hue=hue, style='iteration', data=reduced, ax=axes[4], markers=['.', 'o'], alpha=alpha, **plot_kwargs) if plot_mean: # just plot the final one reduced = result.groupby(hue).last().reset_index() s_0 = np.percentile([reduced.critical_scaling.sample(frac=1, replace=True).mean() for _ in range(1000)], [2.5, 50, 97.5]) a_0 = np.percentile([reduced.proportionality_factor.sample(frac=1, replace=True).mean() for _ in range(1000)], [2.5, 50, 97.5]) ellipse = mpl.patches.Ellipse((s_0[1], a_0[1]), s_0[2] - s_0[0], a_0[2] - a_0[0], facecolor='k', alpha=.5, zorder=10) axes[4].add_patch(ellipse) axes[4].set(title='Initial and final parameter values') fig.tight_layout() return fig
kkroboth/Intentional-Concurrent-Programming
src/main/applications/forkjoin/OneTimeLatchKThreadsVariant.java
package applications.forkjoin; import applications.forkjoin.shared.TextFile; import icp.core.ICP; import icp.core.Permissions; import icp.core.Task; import icp.lib.OneTimeLatchRegistration; import icp.lib.SimpleReentrantLock; import java.util.Arrays; /** * Same as OneTimeLatchKThreads except instead of using an * atomic integer for remaining textFiles, a reentrant lock guarding * integer. */ public class OneTimeLatchKThreadsVariant { // Permission[index]: Latch Permission private final TextFile[] textFiles; // Permission: Reentrant locked permission private final MyInteger tasksLeft; private final SimpleReentrantLock tasksLeftLock; private final OneTimeLatchRegistration latch; // Container for integer @Deprecated() // Use icp.core.wrapper.Number instead private static class MyInteger { public int value; public MyInteger(int value) { this.value = value; } } OneTimeLatchKThreadsVariant(TextFile[] textFiles) { this.textFiles = textFiles; latch = new OneTimeLatchRegistration(); tasksLeftLock = new SimpleReentrantLock(); tasksLeft = new MyInteger(textFiles.length); /* * Potential Problem: * * int tasksLeft; * ICP.setPermission(tasksLeft, permission); // boxed integer * * If ICP decides to add permissions on all objects, it wil have to either handle * boxing and unboxing of primatives differently (custom container) or ignore them * and raise errors. This compiles, but isn't allowed since current version doesn't * edit jdk classes. Code can box, unbox, and box again with different Integer objects. * * Autoboxing could use cached Integer objects if range (-128 to 127). Javadoc mentions * it *could* cache values outside range. * http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/Integer.java#785 * * For current version, tasksLeft must be in a container class. */ // taskLefts guarded-by reentrant lock ICP.setPermission(tasksLeft, tasksLeftLock.getLockedPermission()); } void compute() { for (int i = 0; i < textFiles.length; i++) { final int finalI = i; new Thread(Task.ofThreadSafe(() -> { latch.registerOpener(); // Create results and add latch permission to ith index TextFile textFile = textFiles[finalI]; ICP.setPermission(textFile, latch.getPermission()); // Compute results textFile.run(); // If task is the last to compute, open the latch tasksLeftLock.lock(); try { tasksLeft.value -= 1; if (tasksLeft.value == 0) latch.open(); } finally { tasksLeftLock.unlock(); } })).start(); } } void awaitComputation() throws InterruptedException { latch.registerWaiter(); latch.await(); } public static void main(String[] args) throws InterruptedException { TextFile[] textFiles = new TextFile[]{ new TextFile("alice.txt", "the"), new TextFile("alice.txt", "alice"), new TextFile("alice.txt", "I"), }; // Transfer the array of text files Arrays.stream(textFiles).forEach(t -> ICP.setPermission(t, Permissions.getTransferPermission())); OneTimeLatchKThreadsVariant app = new OneTimeLatchKThreadsVariant(textFiles); // Compute app.compute(); app.awaitComputation(); // Print results for (TextFile textFile : textFiles) { System.out.println("Word: " + textFile.word + " Count: " + textFile.getCount()); } } }
TuLinhNGUYEN/chutney
server/src/test/java/com/chutneytesting/agent/infra/storage/AgentNetworkMapperJsonFileMapperTest.java
<filename>server/src/test/java/com/chutneytesting/agent/infra/storage/AgentNetworkMapperJsonFileMapperTest.java package com.chutneytesting.agent.infra.storage; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import com.chutneytesting.agent.domain.configure.ImmutableNetworkConfiguration; import com.chutneytesting.agent.domain.network.Agent; import com.chutneytesting.agent.domain.network.AgentGraph; import com.chutneytesting.agent.domain.network.ImmutableNetworkDescription; import com.chutneytesting.agent.domain.network.NetworkDescription; import com.chutneytesting.design.domain.environment.Environment; import com.chutneytesting.design.domain.environment.Target; import com.chutneytesting.engine.domain.delegation.NamedHostAndPort; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.assertj.core.api.Condition; import org.junit.Test; public class AgentNetworkMapperJsonFileMapperTest { private AgentNetworkMapperJsonFileMapper mapper = new AgentNetworkMapperJsonFileMapper(); @Test public void toDto_should_map_every_information() { Agent agent = new Agent(new NamedHostAndPort("name", "host", 42)); Agent reachableAgent = new Agent(new NamedHostAndPort("reachable", "host2", 42)); Target target = Target.builder() .withId(Target.TargetId.of("targetName", "env")) .withUrl("prot://me:42") .build(); Environment environment = Environment.builder().withName("env").addTarget(target).build(); Target.TargetId targetId = Target.TargetId.of("targetName", "env"); agent.addReachable(reachableAgent); reachableAgent.addReachable(targetId); ImmutableNetworkDescription network = ImmutableNetworkDescription.builder() .configuration(ImmutableNetworkConfiguration.builder() .creationDate(Instant.now()) .agentNetworkConfiguration(ImmutableNetworkConfiguration.AgentNetworkConfiguration.of(Arrays.asList(agent.agentInfo, reachableAgent.agentInfo))) .environmentConfiguration(ImmutableNetworkConfiguration.EnvironmentConfiguration.of(singleton(environment))) .build()) .agentGraph(new AgentGraph(Arrays.asList(agent, reachableAgent))) .build(); AgentNetworkForJsonFile dto = mapper.toDto(network); AgentForJsonFile firstAgent = dto.agents.get(0); assertThat(firstAgent.name).isEqualTo("name"); assertThat(firstAgent.host).isEqualTo("host"); assertThat(firstAgent.port).isEqualTo(42); assertThat(firstAgent.reachableAgentNames).contains("reachable"); assertThat(firstAgent.reachableTargetIds).isEmpty(); AgentForJsonFile secondAgent = dto.agents.get(1); assertThat(secondAgent.name).isEqualTo("reachable"); assertThat(secondAgent.host).isEqualTo("host2"); assertThat(secondAgent.port).isEqualTo(42); assertThat(secondAgent.reachableAgentNames).isEmpty(); assertThat(secondAgent.reachableTargetIds).hasOnlyOneElementSatisfying(target1 -> assertThat(target1.name).isEqualTo("targetName") ); } @Test public void fromDto_should_rebuild_everything() { String targetName = "targetName"; TargetForJsonFile target = new TargetForJsonFile(); target.name = targetName; target.environment = "env"; AgentNetworkForJsonFile networkJson = new AgentNetworkForJsonFile(); networkJson.configurationCreationDate = Instant.now(); AgentForJsonFile agent1Json = createAgentJson("agent1", "host1", singletonList("agent2"), emptyList()); AgentForJsonFile agent2Json = createAgentJson("agent2", "host2", emptyList(), singletonList(target)); networkJson.agents = Arrays.asList(agent1Json, agent2Json); List<Target> targets = new ArrayList<>(); targets.add( Target.builder() .withId(Target.TargetId.of(targetName, "env")) .withUrl("http://s1:90") .build() ); Environment environment = Environment.builder().withName("env").addAllTargets(targets).build(); NetworkDescription description = mapper.fromDto(networkJson, singletonList(environment)); assertThat(description.agentGraph().agents()).hasSize(2); assertThat(description.agentGraph().agents()).haveAtLeastOne(agentThatMatch(agent1Json)); assertThat(description.agentGraph().agents()).haveAtLeastOne(agentThatMatch(agent2Json)); } private Condition<Agent> agentThatMatch(AgentForJsonFile expectedAgent) { return new Condition<>(actualAgent -> { boolean result = actualAgent.agentInfo.name().equals(expectedAgent.name); result &= actualAgent.agentInfo.host().equals(expectedAgent.host); result &= actualAgent.agentInfo.port() == expectedAgent.port; result &= actualAgent.reachableAgents().stream() .map(_agent -> _agent.agentInfo.name()) .allMatch(expectedAgent.reachableAgentNames::contains); result &= actualAgent.reachableTargets().stream() .allMatch(reachableTarget -> expectedAgent.reachableTargetIds.stream().anyMatch(targetJson -> targetJson.name.equals(reachableTarget.name))); return result; }, expectedAgent.name); } private AgentForJsonFile createAgentJson(String agentName, String agentHost, List<String> reachableAgents, List<TargetForJsonFile> reachableTargets) { AgentForJsonFile agent1Json = new AgentForJsonFile(); agent1Json.name = agentName; agent1Json.host = agentHost; agent1Json.port = 42; agent1Json.reachableAgentNames = reachableAgents; agent1Json.reachableTargetIds = reachableTargets; return agent1Json; } }
AdrianLozano96/Apuntes-Acceso_a_Datos
Apuntes XML/src/main/java/org/adrianl/jaxb/Anotaciones.java
<reponame>AdrianLozano96/Apuntes-Acceso_a_Datos<filename>Apuntes XML/src/main/java/org/adrianl/jaxb/Anotaciones.java package org.adrianl.jaxb; public class Anotaciones { /* ANOTACIONES Anotaciones para convertir el JavaBeans (clases a mapear POJO) en XML @XmlRootElement(namespace = "namespace"): Define la raíz del XML. Si una clase va a ser la raíz del documento @XmlRootElement public class ClaseRaiz {...} @XmlType(propOrder = { "field2", "fieldl",.. }): Permite definir en qué orden se van a escribir los elementos (o las etiquetas) dentro del XML. Para clases que no vayan a ser raíz. @XmlElement(name = "nombre"): Define el elemento de XML que se va usar. Para asignar el nombre de la etiqueta del XML: @XmlRootElement(name = "Un_Nombre_para_la_raiz") @XmlType(name = "Otro_Nombre") Para los atributos que se quieran mostrar en el XML: @XmlRootElement(name = "La ClaseRaiz") public class UnaClase { private String unAtributo; @XmlElement(name = "El_Atributo") String getUnAtributo() { return this.unAtributo; } } Si el atributo es una colección: @XmlRootElement(name = "La_ClaseRaiz") public class UnaClase { privare String [] unArray; @XmlElementWrapper @XmlElement(name = "Elemento_Array") String [] getUnArray() { return this.unArray; } } Si el atributo es otra clase (otro JavaBean), le ponemos igualmente @XmlElement al método get, pero la clase que hace de atributo debería llevar a la vez sus anotaciones correspondientes. */ }
hedzr/voxr-lite
misc/impl/ws/ws.hub.reg.go
<filename>misc/impl/ws/ws.hub.reg.go /* * Copyright © 2019 <NAME>. */ package ws import ( "github.com/sirupsen/logrus" "unsafe" ) func (h *WsHub) onRegister(client *WsClient) { h.mutex.RLock() if ok, _ := h.clients[client]; !ok { h.mutex.RUnlock() h.mutex.Lock() h.clients[client] = true h.linkToClient(client) h.mutex.Unlock() // and start a routine to interpret the client's messages // NOTE, the push message from server will be sent at hub routine. go client.writePump() go client.readPump() go client.monitor() size := int(unsafe.Sizeof(*client)) logrus.Debugf("=== [ws] new client in. %v clients x %v bytes. %s", h.clients, size, client.userAgent) // and log it for debugging } else { h.mutex.RUnlock() logrus.Warnf("=== [ws] new client had existed. %v", client) } } func (h *WsHub) onDeregister(client *WsClient) { h.mutex.RLock() if _, ok := h.clients[client]; ok { h.mutex.RUnlock() h.mutex.Lock() delete(h.clients, client) h.unlinkClient(client) h.mutex.Unlock() // defer func() { // if r := recover(); r != nil { // err, _ := r.(error) // logrus.Errorln(" [ws] Websocket error:", err) // } // }() go func() { client.Close() logrus.Printf("=== [ws] the client leaved,closed,unregistered (%s).", client.userAgent) // and log it for debugging client = nil }() } else { h.mutex.RUnlock() logrus.Debugf("=== [ws] the client unregistered (%s).", client.userAgent) } } func (h *WsHub) linkToClient(c *WsClient) { h.clientsMap[c.deviceId] = c } func (h *WsHub) unlinkClient(c *WsClient) { delete(h.clientsMap, c.deviceId) }
vikramsomavaram/hashbrown-kubernetes-helm
template/listItem/panelItem.js
'use strict'; module.exports = (_, model, state) => _.div({class: `list-item--panel-item ${model.type || ''} ${state.isActive ? 'active' : ''}`, 'data-sort': model.sort, id: model.id}, _.div({class: 'list-item--panel-item__inner', name: 'inner', draggable: model.isDraggable, ondragstart: _.onDragStart, ondragend: _.onDragEnd, ondragover: _.onDragOver, ondragleave: _.onDragLeave, ondrop: _.onDrop}, _[model.isDisabled ? 'div' : 'a']({href: model.isDisabled ? null : `#/${model.library}/${model.id}`, class: 'list-item--panel-item__name', oncontextmenu: _.onClickContext}, model.icon && !model.image ? [ _.span({class: `list-item--panel-item__icon fa fa-${model.icon}`}) ] : null, model.name ), _.div({class: 'list-item--panel-item__properties'}, model.isRemote ? [ _.div({class: 'list-item--panel-item__property fa fa-external-link', title: 'This resource is on a remote server'}) ] : null, model.isLocked ? [ _.div({class: 'list-item--panel-item__property fa fa-lock', title: 'This resource is locked'}) ] : null, model.message ? [ _.div({class: 'list-item--panel-item__property fa fa-exclamation-triangle', title: model.message}) ] : null ), _.div({class: 'list-item--panel-item__actions'}, model.children.length > 0 ? [ _.button({class: `list-item--panel-item__action fa fa-${state.isExpanded ? 'caret-down' : 'caret-right'}`, onclick: _.onClickExpand}) ] : null, !model.isDisabled && model.options && Object.keys(model.options).length > 0 ? [ _.button({class: 'list-item--panel-item__action fa fa-ellipsis-v', onclick: _.onClickContext}) ] : null ) ), state.isExpanded && model.children.length > 0 ? [ _.div({class: 'list-item--panel-item__children'}, model.children ) ] : null )
Adham-M/Paint-for-Kids
GUI/Output.cpp
<reponame>Adham-M/Paint-for-Kids<gh_stars>0 #include "Output.h" Output::Output() { //Initialize user interface parameters UI.InterfaceMode = MODE_DRAW; UI.width = 1440; UI.height = 750; UI.wx = 5; UI.wy = 5; UI.StatusBarHeight = 50; UI.ToolBarHeight = 50; UI.MenuItemWidth = 75; UI.DrawColor = BLUE; //Drawing color UI.FillColor = LIGHTGOLDENRODYELLOW; //Filling color UI.MsgColor = RED; //Messages color UI.BkGrndColor = LIGHTGOLDENRODYELLOW; //Background color UI.HighlightColor = MAGENTA; //This color should NOT be used to draw figures. use if for highlight only UI.StatusBarColor = TURQUOISE; UI.PenWidth = 3; //width of the figures frames UI.ToolBarLineWidth = 3; //width of the line under the tool bar //Create the output window pWind = CreateWind(UI.width, UI.height, UI.wx, UI.wy); //Change the title pWind->ChangeTitle("Paint for Kids - Programming Techniques Project"); CreateDrawToolBar(); CreateStatusBar(); } Input* Output::CreateInput() const { Input* pIn = new Input(pWind); return pIn; } //======================================================================================// // Interface Functions // //======================================================================================// window* Output::CreateWind(int w, int h, int x, int y) const { window* pW = new window(w, h, x, y); pW->SetBrush(UI.BkGrndColor); pW->SetPen(UI.BkGrndColor, 1); pW->DrawRectangle(0, UI.ToolBarHeight, w, h); return pW; } ////////////////////////////////////////////////////////////////////////////////////////// void Output::CreateStatusBar() const { pWind->SetPen(UI.StatusBarColor, 1); pWind->SetBrush(UI.StatusBarColor); pWind->DrawRectangle(0, UI.height - UI.StatusBarHeight, UI.width, UI.height); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::ClearStatusBar() const { //Clear Status bar by drawing a filled white rectangle pWind->SetPen(UI.StatusBarColor, 1); pWind->SetBrush(UI.StatusBarColor); pWind->DrawRectangle(0, UI.height - UI.StatusBarHeight, UI.width, UI.height); } void Output::ClearToolBar() const { pWind->SetPen(UI.BkGrndColor, 1); pWind->SetBrush(UI.BkGrndColor); pWind->DrawRectangle(0, 0, UI.width, UI.ToolBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::CreateDrawToolBar() const { UI.InterfaceMode = MODE_DRAW; ClearToolBar(); //You can draw the tool bar icons in any way you want. //Below is one possible way //First prepare List of images for each menu item //To control the order of these images in the menu, //reoder them in UI_Info.h ==> enum DrawMenuItem string MenuItemImages[DRAW_ITM_COUNT]; //////// MenuItemImages[ITM_RECT] = "images\\MenuItems\\Menu_Rectangle.jpg"; MenuItemImages[ITM_LINE] = "images\\MenuItems\\Menu_Line.jpg"; MenuItemImages[ITM_TRI] = "images\\MenuItems\\Menu_Triangle.jpg"; MenuItemImages[ITM_RHOMBUS] = "images\\MenuItems\\Menu_Rhombus.jpg"; MenuItemImages[ITM_ELLIPSE] = "images\\MenuItems\\Menu_Ellipse.jpg"; MenuItemImages[ITM_PALETTE] = "images\\MenuItems\\Menu_Palette.jpg"; MenuItemImages[ITM_CHNGCLR] = "images\\MenuItems\\Menu_ChangeColor.jpg"; //MenuItemImages[ITM_CHNGFILLCLR] = "images\\MenuItems\\Menu_ChangeFillingColor.jpg"; MenuItemImages[ITM_SELECT] = "images\\MenuItems\\Menu_Select.jpg"; MenuItemImages[ITM_COPY] = "images\\MenuItems\\Menu_Copy.jpg"; MenuItemImages[ITM_CUT] = "images\\MenuItems\\Menu_Cut.jpg"; MenuItemImages[ITM_PASTE] = "images\\MenuItems\\Menu_Paste.jpg"; MenuItemImages[ITM_DELETE] = "images\\MenuItems\\Menu_Delete.jpg"; //MenuItemImages[ITM_Sound] = "images\\MenuItems\\Menu_Sound.jpg"; MenuItemImages[ITM_Resize] = "images\\MenuItems\\Menu_Resize.jpg"; MenuItemImages[ITM_Set2BkOrFrnt] = "images\\MenuItems\\Menu_SetToBackOrFront.jpg"; MenuItemImages[ITM_SAVE] = "images\\MenuItems\\Menu_Save.jpg"; MenuItemImages[ITM_SAVEBYTYPE] = "images\\MenuItems\\Menu_SaveByType.jpg"; MenuItemImages[ITM_LOAD] = "images\\MenuItems\\Menu_Load.jpg"; MenuItemImages[ITM_PLAYMODE] = "images\\MenuItems\\Menu_PlayMode.jpg"; MenuItemImages[ITM_EXIT] = "images\\MenuItems\\Menu_Exit.jpg"; //TODO: Prepare images for each menu item and add it to the list //Draw menu item one image at a time //int f = 1, d = 0; bool l = true; for (int i = 0; i < DRAW_ITM_COUNT; i++) //{ //if ((i + 1)*UI.MenuItemWidth > UI.width) //{ // pWind->DrawImage(MenuItemImages[i], d, f * UI.ToolBarHeight, UI.MenuItemWidth, UI.ToolBarHeight); // f++; // l = false; //} //else //{ pWind->DrawImage(MenuItemImages[i], i*UI.MenuItemWidth, 0, UI.MenuItemWidth, UI.ToolBarHeight); // d = i * UI.MenuItemWidth; // } //} //Draw a line under the toolbar pWind->SetPen(BLUE, UI.ToolBarLineWidth); //if (l) pWind->DrawLine(0, UI.ToolBarHeight, UI.width, UI.ToolBarHeight); //else //{ // pWind->DrawLine(0, UI.ToolBarHeight, d - 3, UI.ToolBarHeight); // pWind->SetPen(BLUE, UI.ToolBarLineWidth); // pWind->DrawLine(d - 3, UI.ToolBarHeight, d - 3, f * UI.ToolBarHeight); // pWind->SetPen(BLUE, UI.ToolBarLineWidth); // pWind->DrawLine(d - 3, f * UI.ToolBarHeight, UI.width, f * UI.ToolBarHeight); //} pWind->SetPen(GREEN, UI.ToolBarLineWidth); pWind->DrawLine(0, UI.ToolBarHeight, UI.width * 2 / 3, UI.ToolBarHeight); pWind->SetPen(RED, UI.ToolBarLineWidth); pWind->DrawLine(0, UI.ToolBarHeight, UI.width / 3, UI.ToolBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::CreatePlayToolBar() const { UI.InterfaceMode = MODE_PLAY; //////// ClearToolBar(); string MenuItemImages2[PLAY_ITM_COUNT]; MenuItemImages2[ITM_FIGURE] = "images\\MenuItems\\ITM_FIGURE.jpg"; MenuItemImages2[ITM_COLOR] = "images\\MenuItems\\ITM_COLOR.jpg"; MenuItemImages2[ITM_REST] = "images\\MenuItems\\ITM_REST.jpg"; MenuItemImages2[ITM_DRAWMODE] = "images\\MenuItems\\ITM_DRAWMODE.jpg"; MenuItemImages2[ITM_EXIT2] = "images\\MenuItems\\Menu_Exit.jpg"; //Draw a line under the toolbar pWind->SetPen(LIGHTGOLDENRODYELLOW, UI.ToolBarLineWidth); pWind->DrawLine(0, UI.ToolBarHeight, UI.width, UI.ToolBarHeight); pWind->SetPen(BLUE, UI.ToolBarLineWidth); pWind->DrawLine(0, UI.ToolBarHeight, UI.MenuItemWidth*PLAY_ITM_COUNT, UI.ToolBarHeight); pWind->SetPen(GREEN, UI.ToolBarLineWidth); pWind->DrawLine(0, UI.ToolBarHeight, UI.MenuItemWidth*PLAY_ITM_COUNT * 2 / 3, UI.ToolBarHeight); pWind->SetPen(RED, UI.ToolBarLineWidth); pWind->DrawLine(0, UI.ToolBarHeight, UI.MenuItemWidth*PLAY_ITM_COUNT / 3, UI.ToolBarHeight); for (int i = 0; i < PLAY_ITM_COUNT; i++) pWind->DrawImage(MenuItemImages2[i], i*UI.MenuItemWidth, 0, UI.MenuItemWidth, UI.ToolBarHeight); ///TODO: write code to create Play mode menu } ////////////////////////////////////////////////////////////////////////////////////////// void Output::ClearDrawArea() const { pWind->SetPen(UI.BkGrndColor, 1); pWind->SetBrush(UI.BkGrndColor); pWind->DrawRectangle(0, UI.ToolBarHeight + 2, UI.width, UI.height - UI.StatusBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// void Output::PrintMessage(string msg) const //Prints a message on status bar { ClearStatusBar(); //First clear the status bar pWind->SetPen(UI.MsgColor, 50); pWind->SetFont(20, BOLD, BY_NAME, "Arial"); pWind->DrawString(10, UI.height - (int)(UI.StatusBarHeight / 1.2), msg); } ////////////////////////////////////////////////////////////////////////////////////////// color Output::getCrntDrawColor() const //get current drawing color { return UI.DrawColor; } ////////////////////////////////////////////////////////////////////////////////////////// color Output::getCrntFillColor() const //get current filling color { return UI.FillColor; } ////////////////////////////////////////////////////////////////////////////////////////// int Output::getCrntPenWidth() const //get current pen width { return UI.PenWidth; } //======================================================================================// // Figures Drawing Functions // //======================================================================================// void Output::DrawRect(Point P1, Point P2, GfxInfo RectGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = RectGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (RectGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(RectGfxInfo.FillClr); } else style = FRAME; //To Place the Rectangle in the Drawing Area if (P1.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P1.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P1.y > UI.height - UI.StatusBarHeight - 1) P1.y = UI.height - UI.StatusBarHeight - 1; if (P2.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P2.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P2.y > UI.height - UI.StatusBarHeight - 1) P2.y = UI.height - UI.StatusBarHeight - 1; // pWind->DrawRectangle(P1.x, P1.y, P2.x, P2.y, style); } void Output::DrawTri(Point P1, Point P2, Point P3, GfxInfo TRIGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = TRIGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (TRIGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(TRIGfxInfo.FillClr); } else style = FRAME; //To Place the Triangle in the Drawing Area if (P1.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P1.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P1.y > UI.height - UI.StatusBarHeight - 1) P1.y = UI.height - UI.StatusBarHeight - 1; if (P2.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P2.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P2.y > UI.height - UI.StatusBarHeight - 1) P2.y = UI.height - UI.StatusBarHeight - 1; if (P3.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P3.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P3.y > UI.height - UI.StatusBarHeight - 1) P3.y = UI.height - UI.StatusBarHeight - 1; // pWind->DrawTriangle(P1.x, P1.y, P2.x, P2.y, P3.x, P3.y, style); } void Output::DrawLine(Point P1, Point P2, GfxInfo LINEGfxInfo, bool selected) const { color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = LINEGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; style = FRAME; //To Place the Line in the Drawing Area if (P1.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P1.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P1.y > UI.height - UI.StatusBarHeight - 1) P1.y = UI.height - UI.StatusBarHeight - 1; if (P2.y < UI.ToolBarHeight + UI.ToolBarLineWidth) P2.y = UI.ToolBarHeight + UI.ToolBarLineWidth; if (P2.y > UI.height - UI.StatusBarHeight - 1) P2.y = UI.height - UI.StatusBarHeight - 1; // pWind->DrawLine(P1.x, P1.y, P2.x, P2.y, style); } void Output::DrawRhomb(Point P1, int xx, int yy, GfxInfo RHOMBGfxInfo, bool selected) const { int *PPx = new int[4]; int *PPy = new int[4]; color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = RHOMBGfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; style = FRAME; if (RHOMBGfxInfo.isFilled) { style = FILLED; pWind->SetBrush(RHOMBGfxInfo.FillClr); } else style = FRAME; //To Place the Rhombus in the Drawing Area if (P1.y < UI.ToolBarHeight + yy + UI.ToolBarLineWidth) P1.y = UI.ToolBarHeight + yy + UI.ToolBarLineWidth; if (P1.y > UI.height - UI.StatusBarHeight - yy - 1) P1.y = UI.height - UI.StatusBarHeight - yy - 1; if (P1.x < xx) P1.x = xx; if (P1.x > UI.width - xx - 15) P1.x = UI.width - xx - 15; // PPx[0] = P1.x; PPy[0] = P1.y + yy; PPx[1] = P1.x + xx; PPy[1] = P1.y; PPx[2] = P1.x; PPy[2] = P1.y - yy; PPx[3] = P1.x - xx; PPy[3] = P1.y; pWind->DrawPolygon(PPx, PPy, 4, style); delete[] PPx; delete[] PPy; } void Output::DrawEllip(Point P1, int xx, int yy, GfxInfo ELLIPfxInfo, bool selected) const { int PEx1, PEx2, PEy1, PEy2; color DrawingClr; if (selected) DrawingClr = UI.HighlightColor; //Figure should be drawn highlighted else DrawingClr = ELLIPfxInfo.DrawClr; pWind->SetPen(DrawingClr, 1); drawstyle style; if (ELLIPfxInfo.isFilled) { style = FILLED; pWind->SetBrush(ELLIPfxInfo.FillClr); } else style = FRAME; //To Place the Ellipse in the Drawing Area if (P1.y < UI.ToolBarHeight + yy + UI.ToolBarLineWidth) P1.y = UI.ToolBarHeight + yy + UI.ToolBarLineWidth; if (P1.y > UI.height - UI.StatusBarHeight - yy - 1) P1.y = UI.height - UI.StatusBarHeight - yy - 1; if (P1.x < xx) P1.x = xx; if (P1.x > UI.width - xx - 15) P1.x = UI.width - xx - 15; // PEx1 = P1.x + xx; PEx2 = P1.x - xx; PEy1 = P1.y + yy; PEy2 = P1.y - yy; pWind->DrawEllipse(PEx1, PEy1, PEx2, PEy2, style); } ////////////////////////////////////////////////////////////////////////////////////////// Output::~Output() { delete pWind; }
ucuenca/REDI
storage/src/main/java/edu/ucuenca/storage/services/MongoServiceImpl.java
/* * 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 edu.ucuenca.storage.services; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Filters.or; import static com.mongodb.client.model.Projections.exclude; import static com.mongodb.client.model.Projections.include; import static com.mongodb.client.model.Sorts.ascending; import edu.ucuenca.storage.api.MongoService; import edu.ucuenca.storage.exceptions.FailMongoConnectionException; import java.io.StringWriter; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.apache.marmotta.platform.core.api.config.ConfigurationService; import org.apache.marmotta.ucuenca.wk.commons.service.ExternalSPARQLService; import org.bson.Document; import org.bson.conversions.Bson; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.openrdf.query.QueryLanguage; import org.openrdf.repository.RepositoryConnection; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; import org.slf4j.Logger; ; /** * Default Implementation of {@link MongoService} */ @ApplicationScoped public class MongoServiceImpl implements MongoService { @Inject private Logger log; @Inject private ConfigurationService configurationService; @Inject private ExternalSPARQLService sesameService2; private MongoClient mongoClient; private MongoDatabase db; private MongoCollection<Document> authors; private MongoCollection<Document> statistics; private MongoCollection<Document> statisticsByInst; private MongoCollection<Document> documentbyarea; private MongoCollection<Document> statisticsByAuthor; private MongoCollection<Document> relatedauthors; private MongoCollection<Document> clusters; private MongoCollection<Document> clustersTotals; private MongoCollection<Document> authorsByArea; private MongoCollection<Document> authorsByDisc; private MongoCollection<Document> countries; private MongoCollection<Document> sparqls; private MongoCollection<Document> authors_val; private MongoCollection<Document> projects; private MongoCollection<Document> instbyProject; private MongoCollection<Document> sessions; @PostConstruct public void initialize() throws FailMongoConnectionException { connect(); } @Override public void connect() throws FailMongoConnectionException { String host = configurationService.getStringConfiguration("mongo.host"); int port = configurationService.getIntConfiguration("mongo.port"); mongoClient = new MongoClient(host, port); db = mongoClient.getDatabase(Database.NAME.getDBName()); authors = db.getCollection(Collection.AUTHORS.getValue()); relatedauthors = db.getCollection(Collection.RELATEDAUTHORS.getValue()); statistics = db.getCollection(Collection.STATISTICS.getValue()); statisticsByInst = db.getCollection(Collection.STATISTICS_INST.getValue()); clusters = db.getCollection(Collection.CLUSTERS.getValue()); clustersTotals = db.getCollection(Collection.CLUSTERSTOTALS.getValue()); authorsByArea = db.getCollection(Collection.AUTHORS_AREA.getValue()); authorsByDisc = db.getCollection(Collection.AUTHORS_DISCPLINE.getValue()); countries = db.getCollection(Collection.COUNTRIES.getValue()); sparqls = db.getCollection(Collection.SPARQLS.getValue()); statisticsByAuthor = db.getCollection(Collection.STATISTICS_AUTHOR.getValue()); authors_val = db.getCollection(Collection.PROFILE_AUTHOR.getValue()); projects = db.getCollection(Collection.PROJECTPROFILE.getValue()); sessions = db.getCollection(Collection.SESSIONS.getValue()); instbyProject = db.getCollection(Collection.INSTBYPROJECT.getValue()); documentbyarea = db.getCollection(Collection.DOCUMENTBYAREA.getValue()); } @Override public String getAuthor(String uri) { return authors.find(eq("_id", uri)) .first() .toJson(); } @Override public Document getProfileValAuthor(String id) { return authors_val.find(eq("_id", id)).first(); } @Override public String getStatistics(String id) { return statistics.find(eq("_id", id)) .first().toJson(); } @Override public String getStatisticsByInst(String id) { return statisticsByInst.find(eq("_id", id)).first().toJson(); } @Override public String getStatisticsByAuthor(String id) { return statisticsByAuthor.find(eq("_id", id)).first().toJson(); } @Override public String getRelatedAuthors(String uri) { return relatedauthors.find(eq("_id", uri)) .first() .toJson(); } @Override public Document getCluster(String... uri) { List<Bson> ls = new ArrayList<>(); List<Document> c = new ArrayList<>(); for (String p : uri) { Bson eq = eq("_id", p); ls.add(eq); } FindIterable<Document> sort = clusters.find(or(ls)) .projection(include("subclusters")) .sort(ascending("label-en")); MongoCursor<Document> it = sort.iterator(); while (it.hasNext()) { c.add(it.next()); } Document parse = new Document(); if (c.size() == 1) { parse = c.get(0); } else { parse.put("data", c); } return parse; } @Override public Document getProfileProject(String id) { return projects.find(eq("_id", id)).first(); } @Override public Document removeProfileValAuthor(String id) { return authors_val.findOneAndDelete(eq("_id", id)); } @Override public List<Document> getClusters() { List<Document> c = new ArrayList<>(); FindIterable<Document> cls = clusters.find() .projection(exclude("subclusters")) .sort(ascending("label-en", "label-es")); MongoCursor<Document> it = cls.iterator(); while (it.hasNext()) { c.add(it.next()); } return c; } @Override public List<Document> getCountries() { List<Document> c = new ArrayList<>(); FindIterable<Document> cls = countries.find(); MongoCursor<Document> it = cls.iterator(); while (it.hasNext()) { c.add(it.next()); } return c; } @Override public String getAuthorsByArea(String cluster, String subcluster) { BasicDBObject key = new BasicDBObject(); key.put("cluster", cluster); key.put("subcluster", subcluster); return authorsByArea.find(eq("_id", key)) .first().toJson(); } @Override public String getAuthorsByDiscipline(String cluster) { BasicDBObject key = new BasicDBObject(); key.put("cluster", cluster); return authorsByDisc.find(eq("_id", key)) .first().toJson(); } @PreDestroy public void shutdown() { log.info("Killing connection to MongoDB."); mongoClient.close(); } @Override public List<Document> getClustersTotals() { List<Document> c = new ArrayList<>(); MongoCursor<Document> it = clustersTotals.find().iterator(); while (it.hasNext()) { c.add(it.next()); } return c; } @Override public List<Document> getSubClustersTotals(String uri) { Document first = clustersTotals.find(eq("_id", uri)).first(); return (List<Document>) first.get("subclusters"); } @Override public String getSPARQL(String qry, String f) { String k = getMd5(f + qry); String R = ""; MongoCursor<Document> find = sparqls.find(eq("_id", k)).iterator(); if (!find.hasNext()) { try { RepositoryConnection conn = sesameService2.getRepositoryConnetion(); StringWriter writter = new StringWriter(); RDFFormat extfrmt = RDFFormat.JSONLD; if (f.contains("application/rdf+json")){ extfrmt = RDFFormat.RDFJSON; } RDFWriter jsonldWritter = Rio.createWriter(extfrmt, writter); conn.prepareGraphQuery(QueryLanguage.SPARQL, qry).evaluate(jsonldWritter); // Model mm = new LinkedHashModel(); // while (evaluate.hasNext()){ // mm.add(evaluate.next()); // } // Rio.write(mm, jsonldWritter); //Object compact = JsonLdProcessor.compact(JsonUtils.fromString(writter.toString()), new HashMap(), new JsonLdOptions()); Map<String, Object> json = new HashMap<String, Object>(); json.put("_id", k); json.put("data", writter.toString()); sparqls.insertOne(new Document(json)); conn.close(); writter.getBuffer().setLength(0); find = sparqls.find(eq("_id", k)).iterator(); } catch (Exception ex) { ex.printStackTrace(); log.debug("Unexpected error cached-query {}", ex); } } Document next = find.next(); R = next.getString("data"); return R; } private String getMd5(String input) { try { // Static getInstance method is called with hashing MD5 MessageDigest md = MessageDigest.getInstance("MD5"); // digest() method is called to calculate message digest // of an input digest() return array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public void registerSession(String orcid, String token) { BasicDBObject key = new BasicDBObject(); key.put("orcid", orcid); key.put("token", token); BasicDBObject main = new BasicDBObject(); main.append("_id", key); Document parse = Document.parse(main.toJson()); sessions.insertOne(parse); } @Override public boolean checkSession(String orcid, String token) { BasicDBObject key = new BasicDBObject(); key.put("orcid", orcid); key.put("token", token); return sessions.find(eq("_id", key)).iterator().hasNext(); } @Override public JSONObject obtainNewProfiles(String org) throws Exception { BasicDBObject key = new BasicDBObject(); key.put("profile.org", org); BasicDBObject pro = new BasicDBObject(); pro.put("profile", 1); JSONObject main = new JSONObject(); JSONArray array = new JSONArray(); main.put("data", array); JSONParser parser = new JSONParser(); for (Document document : authors_val.find(key).projection(pro)) { JSONObject parse = (JSONObject) parser.parse(document.toJson()); array.add(parse); } return main; } @Override public Document getinstbyProject(String id) { return instbyProject.find(eq("_id", id)).first(); } @Override public String getStatisticsByArea(String id) { return documentbyarea.find(eq("_id", id)).first().toJson(); } }
thetlwinoo/keyist-ecommerce
resource_server/src/main/java/com/commerce/backend/service/CartServiceImpl.java
<filename>resource_server/src/main/java/com/commerce/backend/service/CartServiceImpl.java package com.commerce.backend.service; import com.commerce.backend.dao.CartItemRepository; import com.commerce.backend.dao.CartRepository; import com.commerce.backend.dao.ProductDisplayRepository; import com.commerce.backend.dao.UserRepository; import com.commerce.backend.model.Cart; import com.commerce.backend.model.CartItem; import com.commerce.backend.model.ProductDisplay; import com.commerce.backend.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.security.Principal; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class CartServiceImpl implements CartService { private final CartRepository cartRepository; private final CartItemRepository cartItemRepository; private final ProductDisplayRepository productDisplayRepository; private final PriceService priceService; private final UserRepository userRepository; @Autowired public CartServiceImpl(CartRepository cartRepository, CartItemRepository cartItemRepository, ProductDisplayRepository productDisplayRepository, PriceService priceService, UserRepository userRepository) { this.cartRepository = cartRepository; this.cartItemRepository = cartItemRepository; this.productDisplayRepository = productDisplayRepository; this.priceService = priceService; this.userRepository = userRepository; } @Override public Cart addToCart(Principal principal, Long id, Integer amount) { User user = getUserFromPrinciple(principal); if (amount <= 0 || id <= 0) { throw new IllegalArgumentException("Invalid parameters"); } Cart cart = user.getCart(); if (cart == null) { cart = new Cart(); cart.setCartUser(user); //usersRepository.save(user); deleted because it caused the cart to be saved twice } else if (cart.getCartItemList() != null || !cart.getCartItemList().isEmpty()) { for (CartItem i : cart.getCartItemList()) { if (i.getCartProduct().getId().equals(id)) { i.setAmount(i.getAmount() + amount); // CartItem ct = cartItemRepository.save(i); Cart returnCart = priceService.calculatePrice(cart); cartRepository.save(returnCart); // return new ResponseEntity<Cart>(returnCart,HttpStatus.OK); return returnCart; } } } Optional optional = productDisplayRepository.findById(id); if (!optional.isPresent()) { throw new IllegalArgumentException("Product not found."); } ProductDisplay product = (ProductDisplay) optional.get(); CartItem cartItem = new CartItem(); cartItem.setAmount(amount); cartItem.setCartProduct(product); //this will save the cart object as well because there is cascading from cartItem cartItem.setCart(cart); if (cart.getCartItemList() == null) { cart.setCartItemList(new ArrayList<>()); } cart.getCartItemList().add(cartItem); cart = priceService.calculatePrice(cart); cartItemRepository.save(cartItem); return cart; } @Override public Cart fetchCart(Principal principal) { System.out.println("FETCH CART"); User user = getUserFromPrinciple(principal); return user.getCart(); } @Override public Cart removeFromCart(Principal principal, Long id) { System.out.println("Remove CartItem id " + id); User user = getUserFromPrinciple(principal); Cart cart = user.getCart(); if (cart == null) { throw new IllegalArgumentException("Cart not found"); } List<CartItem> cartItemsList = cart.getCartItemList(); CartItem cartItemToDelete = null; for (CartItem i : cartItemsList) { if (i.getId().equals(id)) { cartItemToDelete = i; } } if (cartItemToDelete == null) { throw new IllegalArgumentException("CartItem not found"); } cartItemsList.remove(cartItemToDelete); if (cart.getCartItemList() == null || cart.getCartItemList().size() == 0) { //TODO make it so it can be deleted with online cartRepository.delete method // cartRepository.delete(cart); user.setCart(null); //setting it to null will delete it //because of the orphanRemove mark on the field userRepository.save(user); return null; } cart.setCartItemList(cartItemsList); cart = priceService.calculatePrice(cart); cartItemRepository.delete(cartItemToDelete); return cart; } @Override public Boolean confirmCart(Principal principal, Cart cart) { User user = getUserFromPrinciple(principal); Cart dbCart = user.getCart(); if (dbCart == null) { throw new IllegalArgumentException("Cart not found"); } List<CartItem> dbCartItemsList = dbCart.getCartItemList(); List<CartItem> cartItemsList = cart.getCartItemList(); if (dbCartItemsList.size() != cartItemsList.size()) { return false; } for (int i = 0; i < dbCartItemsList.size(); i++) { if (!dbCartItemsList.get(i).getId().equals(cartItemsList.get(i).getId()) && !dbCartItemsList.get(i).getAmount().equals(cartItemsList.get(i).getAmount()) && !dbCartItemsList.get(i).getCartProduct().getId().equals(cartItemsList.get(i).getCartProduct().getId())) { return false; } } if ( dbCart.getTotalPrice().equals(cart.getTotalPrice()) && dbCart.getTotalCargoPrice().equals(cart.getTotalCargoPrice()) && dbCart.getId().equals(cart.getId())) { if (dbCart.getCartDiscount() != null && cart.getCartDiscount() != null) { if (dbCart.getCartDiscount().getDiscountPercent().equals(cart.getCartDiscount().getDiscountPercent()) && dbCart.getCartDiscount().getCode().equals(cart.getCartDiscount().getCode())) { System.out.println("equals"); return true; } } else if (dbCart.getCartDiscount() == null && cart.getCartDiscount() == null) { System.out.println("equals"); return true; } } System.out.println("no u"); System.out.println(dbCart.getCartItemList().equals(cart.getCartItemList())); return false; } @Override public void emptyCart(Principal principal) { User user = getUserFromPrinciple(principal); user.setCart(null); userRepository.save(user); } private User getUserFromPrinciple(Principal principal) { if (principal == null || principal.getName() == null) { throw new IllegalArgumentException("Invalid access"); } User user = userRepository.findByEmail(principal.getName()); if (user == null) { throw new IllegalArgumentException("User not found"); } return user; } }
hmsgit/campvis
modules/vectorfield/pipelines/vectorfielddemo.h
// ================================================================================================ // // This file is part of the CAMPVis Software Framework. // // If not explicitly stated otherwise: Copyright (C) 2012-2015, all rights reserved, // <NAME> <<EMAIL>> // Chair for Computer Aided Medical Procedures // Technische Universitaet Muenchen // Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany // // For a full list of authors and contributors, please refer to the file "AUTHORS.txt". // // 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. // // ================================================================================================ #ifndef VECTORFIELDDEMO_H__ #define VECTORFIELDDEMO_H__ #include "core/pipeline/autoevaluationpipeline.h" #include "core/eventhandlers/mwheeltonumericpropertyeventlistener.h" #include "modules/modulesapi.h" #include "modules/base/processors/lightsourceprovider.h" #include "modules/base/processors/trackballcameraprovider.h" #include "modules/io/processors/mhdimagereader.h" #include "modules/vectorfield/processors/particleflowrenderer.h" #include "modules/vectorfield/processors/vectorfieldrenderer.h" #include "modules/vis/processors/slicerenderer3d.h" #include "modules/vis/processors/rendertargetcompositor.h" namespace campvis { class CAMPVIS_MODULES_API VectorFieldDemo : public AutoEvaluationPipeline { public: /** * Small demo pipeline for vector field visualization. * \param dataContainer Reference to the DataContainer containing local working set of data * for this pipeline, must be valid the whole lifetime of this pipeline. */ explicit VectorFieldDemo(DataContainer& dc); /** * Virtual Destructor **/ virtual ~VectorFieldDemo(); /// \see AutoEvaluationPipeline::init() virtual void init(); /// \see AutoEvaluationPipeline::deinit() virtual void deinit(); static const std::string getId() { return "VectorFieldDemo"; }; protected: /** * Slot getting called when one of the observed processors got validated. * Updates the camera properties, when the input image has changed. * \param processor The processor that emitted the signal */ virtual void onProcessorValidated(AbstractProcessor* processor); /// \see HasPropertyCollection::onPropertyChanged virtual void onPropertyChanged(const AbstractProperty* prop); TrackballCameraProvider _tcp; LightSourceProvider _lsp; MhdImageReader _imageReader; MhdImageReader _vectorFieldReader; ParticleFlowRenderer _pfr; VectorFieldRenderer _vectorFieldRenderer; SliceRenderer3D _sliceRenderer; RenderTargetCompositor _rtc; IntProperty p_sliceNumber; GenericOptionProperty<std::string> p_viewSelection; IntProperty p_time; }; } #endif // VECTORFIELDDEMO_H__