repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ua-eas/devops-automation-ksd-kc5.2.1-rice
impl/src/test/java/org/kuali/rice/krad/bo/BusinessObjectAttributeEntryTest.java
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.bo; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * This is a description of what this class does - chang don't forget to fill this in. * * @author K<NAME> (<EMAIL>) * */ public class BusinessObjectAttributeEntryTest { BusinessObjectAttributeEntry dummyBOAE; @Before public void setUp() throws Exception { dummyBOAE = new BusinessObjectAttributeEntry(); } /** * This method ... * * @throws java.lang.Exception */ @After public void tearDown() throws Exception { dummyBOAE = null; } @Test public void testAttributeControlType(){ dummyBOAE.setAttributeControlType("ControlType"); assertEquals("Testing AttributeControlType in BusiessObjectAtributeEntry","ControlType",dummyBOAE.getAttributeControlType()); } @Test public void testAttributeDescription(){ dummyBOAE.setAttributeDescription("attributeDescription"); assertEquals("Testing AttributeDescription in BusiessObjectAtributeEntry","attributeDescription",dummyBOAE.getAttributeDescription()); } @Test public void testAttributeFormatterClassName(){ dummyBOAE.setAttributeFormatterClassName("attributeFormatterClassName"); assertEquals("Testing AttributeFormatterClassName in BusiessObjectAtributeEntry", "attributeFormatterClassName",dummyBOAE.getAttributeFormatterClassName()); } @Test public void testAttributeLabel(){ dummyBOAE.setAttributeLabel("attributeLabel"); assertEquals("Testing AttributeLabel in BusiessObjectAtributeEntry","attributeLabel",dummyBOAE.getAttributeLabel()); } @Test public void testAttributeMaxLength(){ dummyBOAE.setAttributeMaxLength("100"); assertEquals("Testing AttributeMaxLength in BusiessObjectAtributeEntry","100",dummyBOAE.getAttributeMaxLength()); } @Test public void testAttributeName(){ dummyBOAE.setAttributeName("AttributeName"); assertEquals("Testing AttributeName in BusiessObjectAtributeEntry","AttributeName",dummyBOAE.getAttributeName()); } @Test public void testAttributeShortLabel(){ dummyBOAE.setAttributeShortLabel("AttributeShortLabel"); assertEquals("Testing AttributeShortLabel in BusiessObjectAtributeEntry","AttributeShortLabel",dummyBOAE.getAttributeShortLabel()); } @Test public void testAttributeSummary(){ dummyBOAE.setAttributeSummary("AttributeSummary"); assertEquals("Testing AttributeSummary in BusiessObjectAtributeEntry","AttributeSummary",dummyBOAE.getAttributeSummary()); } @Test public void testAttributeValidatingExpression(){ dummyBOAE.setAttributeValidatingExpression("AttributeValidatingExpression"); assertEquals("Testing AttributeValidatingExpression in BusiessObjectAtributeEntry","AttributeValidatingExpression",dummyBOAE.getAttributeValidatingExpression()); } @Test public void testDictionaryBusinessObjectName(){ dummyBOAE.setDictionaryBusinessObjectName("DictionaryBusinessObjectName"); assertEquals("Testing DictionaryBusinessObjectName in BusiessObjectAtributeEntry","DictionaryBusinessObjectName",dummyBOAE.getDictionaryBusinessObjectName()); } }
satish757/multiagent
pipeline-model-api/src/main/java/org/jenkinsci/plugins/pipeline/modeldefinition/validator/AbstractModelValidator.java
<gh_stars>100-1000 /* * The MIT License * * Copyright 2019 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.pipeline.modeldefinition.validator; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTAgent; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTAxis; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTAxisContainer; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTBranch; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTBuildCondition; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTBuildConditionsContainer; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTBuildParameter; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTBuildParameters; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTEnvironment; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTExclude; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTExcludeAxis; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTExcludes; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTInternalFunctionCall; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTLibraries; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTMatrix; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTMethodCall; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTOption; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTOptions; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTParallel; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTPipelineDef; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTPostBuild; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTPostStage; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTStage; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTStageBase; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTStageInput; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTStages; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTStep; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTTools; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTTrigger; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTTriggers; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTValue; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTWhen; import org.jenkinsci.plugins.pipeline.modeldefinition.ast.ModelASTWhenCondition; /** * Abstract implementation of {@link ModelValidator}. * * Use this class as a generic AST visitor instead of {@link ModelValidator} to prevent binary compatibility issues * in cases where it is fine to ignore any AST elements that were added to Declarative after you extended this class. */ public class AbstractModelValidator implements ModelValidator { @Override public boolean validateElement(ModelASTAgent agent) { return true; } @Override public boolean validateElement(ModelASTBranch branch) { return true; } @Override public boolean validateElement(ModelASTBuildConditionsContainer container) { return true; } @Override public boolean validateElement(ModelASTPostBuild postBuild) { return true; } @Override public boolean validateElement(ModelASTPostStage post) { return true; } @Override public boolean validateElement(ModelASTBuildCondition buildCondition) { return true; } @Override public boolean validateElement(ModelASTEnvironment environment) { return true; } @Override public boolean validateElement(ModelASTTools tools) { return true; } @Override public boolean validateElement(ModelASTStep step) { return true; } @Override public boolean validateElement(ModelASTWhen when) { return true; } @Override public boolean validateElement(ModelASTMethodCall methodCall) { return true; } @Override public boolean validateElement(ModelASTOptions properties) { return true; } @Override public boolean validateElement(ModelASTTriggers triggers) { return true; } @Override public boolean validateElement(ModelASTBuildParameters buildParameters) { return true; } @Override public boolean validateElement(ModelASTOption jobProperty) { return true; } @Override public boolean validateElement(ModelASTTrigger trigger) { return true; } @Override public boolean validateElement(ModelASTBuildParameter buildParameter) { return true; } @Override public boolean validateElement(ModelASTPipelineDef pipelineDef) { return true; } @Override public boolean validateElement(ModelASTStageBase stage) { return true; } @Override public boolean validateElement(ModelASTStage stage, boolean isWithinParallel) { return true; } @Override public boolean validateElement(ModelASTStages stages) { return true; } @Override public boolean validateElement(ModelASTParallel parallel) { return true; } @Override public boolean validateElement(ModelASTMatrix matrix) { return true; } @Override public boolean validateElement(ModelASTAxisContainer axes) { return true; } @Override public boolean validateElement(ModelASTAxis axis) { return true; } @Override public boolean validateElement(ModelASTExcludes excludes) { return true; } @Override public boolean validateElement(ModelASTExclude exclude) { return true; } @Override public boolean validateElement(ModelASTExcludeAxis axis) { return true; } @Override public boolean validateElement(ModelASTLibraries libraries) { return true; } @Override public boolean validateElement(ModelASTWhenCondition condition) { return true; } @Override public boolean validateElement(ModelASTInternalFunctionCall call) { return true; } @Override public boolean validateElement(ModelASTStageInput input) { return true; } @Override public boolean validateElement(ModelASTValue value) { return true; } }
AvadheshChamola/LeetCode
56_Merge_Intervals.cpp
/* 56. Merge Intervals Medium Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 104 */ class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { if(intervals.size()<=1) return intervals; vector<vector<int>> ans; sort(intervals.begin(),intervals.end()); ans.push_back(intervals[0]); int j=0; for(int i=1;i<intervals.size();i++){ if(ans[j][1] >=intervals[i][0]){ ans[j][1]=max(intervals[i][1],ans[j][1]); }else{ ans.push_back(intervals[i]); j++; } } return ans; } };
AlgorithmLX/IndustrialLevel
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/data/info/WorldgenRegistryDumpReport.java
package net.minecraft.data.info; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.Encoder; import com.mojang.serialization.JsonOps; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import java.util.Map.Entry; import net.minecraft.core.MappedRegistry; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; import net.minecraft.data.HashCache; import net.minecraft.resources.RegistryWriteOps; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.WorldGenSettings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class WorldgenRegistryDumpReport implements DataProvider { private static final Logger LOGGER = LogManager.getLogger(); private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().create(); private final DataGenerator generator; public WorldgenRegistryDumpReport(DataGenerator p_194679_) { this.generator = p_194679_; } public void run(HashCache p_194682_) { Path path = this.generator.getOutputFolder(); RegistryAccess registryaccess = RegistryAccess.builtin(); int i = 0; MappedRegistry<LevelStem> mappedregistry = DimensionType.defaultDimensions(registryaccess, 0L, false); ChunkGenerator chunkgenerator = WorldGenSettings.makeDefaultOverworld(registryaccess, 0L, false); MappedRegistry<LevelStem> mappedregistry1 = WorldGenSettings.withOverworld(registryaccess.ownedRegistryOrThrow(Registry.DIMENSION_TYPE_REGISTRY), mappedregistry, chunkgenerator); DynamicOps<JsonElement> dynamicops = RegistryWriteOps.create(JsonOps.INSTANCE, registryaccess); RegistryAccess.knownRegistries().forEach((p_194713_) -> { dumpRegistryCap(p_194682_, path, registryaccess, dynamicops, p_194713_); }); dumpRegistry(path, p_194682_, dynamicops, Registry.LEVEL_STEM_REGISTRY, mappedregistry1, LevelStem.CODEC); } private static <T> void dumpRegistryCap(HashCache p_194684_, Path p_194685_, RegistryAccess p_194686_, DynamicOps<JsonElement> p_194687_, RegistryAccess.RegistryData<T> p_194688_) { dumpRegistry(p_194685_, p_194684_, p_194687_, p_194688_.key(), p_194686_.ownedRegistryOrThrow(p_194688_.key()), p_194688_.codec()); } private static <E, T extends Registry<E>> void dumpRegistry(Path p_194698_, HashCache p_194699_, DynamicOps<JsonElement> p_194700_, ResourceKey<? extends T> p_194701_, T p_194702_, Encoder<E> p_194703_) { for(Entry<ResourceKey<E>, E> entry : p_194702_.entrySet()) { Path path = createPath(p_194698_, p_194701_.location(), entry.getKey().location()); dumpValue(path, p_194699_, p_194700_, p_194703_, entry.getValue()); } } private static <E> void dumpValue(Path p_194692_, HashCache p_194693_, DynamicOps<JsonElement> p_194694_, Encoder<E> p_194695_, E p_194696_) { try { Optional<JsonElement> optional = p_194695_.encodeStart(p_194694_, p_194696_).result(); if (optional.isPresent()) { DataProvider.save(GSON, p_194693_, optional.get(), p_194692_); } else { LOGGER.error("Couldn't serialize element {}", (Object)p_194692_); } } catch (IOException ioexception) { LOGGER.error("Couldn't save element {}", p_194692_, ioexception); } } private static Path createPath(Path p_194705_, ResourceLocation p_194706_, ResourceLocation p_194707_) { return resolveTopPath(p_194705_).resolve(p_194707_.getNamespace()).resolve(p_194706_.getPath()).resolve(p_194707_.getPath() + ".json"); } private static Path resolveTopPath(Path p_194690_) { return p_194690_.resolve("reports").resolve("worldgen"); } public String getName() { return "Worldgen"; } }
presly808/aco24
functional-tests/src/test/java/patterns/observer/NBUTest.java
package patterns.observer; import static org.junit.Assert.*; /** * Created by serhii on 31.03.18. */ public class NBUTest { public void test1(){ NBU nbu = new NBU(); nbu.addObserver(new PrivatBank()); nbu.addObserver(new Ukrsib()); nbu.addObserver(new AlfaBank()); nbu.notifyObservers(25.6); } }
jiegec/canokey-core
interfaces/USB/class/ctaphid/ctaphid.h
#ifndef __CTAPHID_H_INCLUDED__ #define __CTAPHID_H_INCLUDED__ #include <common.h> #define HID_RPT_SIZE 64 // Default size of raw HID report // Frame layout - command- and continuation frames #define CID_BROADCAST 0xffffffff // Broadcast channel id #define TYPE_MASK 0x80 // Frame type mask #define TYPE_INIT 0x80 // Initial frame identifier #define TYPE_CONT 0x00 // Continuation frame identifier typedef struct { uint32_t cid; // Channel identifier union { uint8_t type; // Frame type - b7 defines type struct { uint8_t cmd; // Command - b7 set uint8_t bcnth; // Message byte count - high part uint8_t bcntl; // Message byte count - low part uint8_t data[HID_RPT_SIZE - 7]; // Data payload } init; struct { uint8_t seq; // Sequence number - b7 cleared uint8_t data[HID_RPT_SIZE - 5]; // Data payload } cont; }; } CTAPHID_FRAME; #define FRAME_TYPE(f) ((f).type & TYPE_MASK) #define FRAME_CMD(f) ((f).init.cmd & ~TYPE_MASK) #define MSG_LEN(f) ((f).init.bcnth * 256 + (f).init.bcntl) #define FRAME_SEQ(f) ((f).cont.seq & ~TYPE_MASK) // General constants #define CTAPHID_IF_VERSION 2 // Current interface implementation version #define CTAPHID_TRANS_TIMEOUT 800 // Default message timeout in ms // CTAPHID native commands #define CTAPHID_PING (TYPE_INIT | 0x01) #define CTAPHID_MSG (TYPE_INIT | 0x03) #define CTAPHID_LOCK (TYPE_INIT | 0x04) #define CTAPHID_INIT (TYPE_INIT | 0x06) #define CTAPHID_WINK (TYPE_INIT | 0x08) #define CTAPHID_CBOR (TYPE_INIT | 0x10) #define CTAPHID_CANCEL (TYPE_INIT | 0x11) #define CTAPHID_KEEPALIVE (TYPE_INIT | 0x3b) #define CTAPHID_ERROR (TYPE_INIT | 0x3f) // CTAPHID_INIT command defines #define INIT_NONCE_SIZE 8 // Size of channel initialization challenge #define CAPABILITY_WINK 0x01 #define CAPABILITY_CBOR 0x04 #define CAPABILITY_NMSG 0x08 typedef struct { uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce } CTAPHID_INIT_REQ; typedef struct { uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce uint32_t cid; // Channel identifier uint8_t versionInterface; // Interface version uint8_t versionMajor; // Major version number uint8_t versionMinor; // Minor version number uint8_t versionBuild; // Build version number uint8_t capFlags; // Capabilities flags } __packed CTAPHID_INIT_RESP; // Low-level error codes. Return as negatives. #define ERR_NONE 0x00 // No error #define ERR_INVALID_CMD 0x01 // Invalid command #define ERR_INVALID_PAR 0x02 // Invalid parameter #define ERR_INVALID_LEN 0x03 // Invalid message length #define ERR_INVALID_SEQ 0x04 // Invalid message sequencing #define ERR_MSG_TIMEOUT 0x05 // Message has timed out #define ERR_CHANNEL_BUSY 0x06 // Channel busy #define ERR_LOCK_REQUIRED 0x0a // Command requires channel lock #define ERR_INVALID_CID 0x0b #define ERR_OTHER 0x7f // Other unspecified error #define KEEPALIVE_STATUS_PROCESSING 1 #define KEEPALIVE_STATUS_UPNEEDED 2 #define LOOP_SUCCESS 0x00 #define LOOP_CANCEL 0x01 #define MAX_CTAP_BUFSIZE 1280 typedef struct { uint32_t cid; uint16_t bcnt_total; uint16_t bcnt_current; uint32_t expire; uint8_t state; uint8_t cmd; uint8_t seq; alignas(4) uint8_t data[MAX_CTAP_BUFSIZE]; } CTAPHID_Channel; typedef struct _USBD_HandleTypeDef USBD_HandleTypeDef; uint8_t CTAPHID_Init(uint8_t (*send_report)(USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len)); uint8_t CTAPHID_OutEvent(uint8_t *data); void CTAPHID_SendKeepAlive(uint8_t status); uint8_t CTAPHID_Loop(uint8_t wait_for_user); #endif // __CTAPHID_H_INCLUDED__
kadiryetisen/Mern-eCommerce
frontend/src/screens/admin/AdminUserList.js
import { React, useEffect, useState, useContext, useRef } from 'react' import axios from 'axios' import { Button, Table } from 'react-bootstrap' import { AuthContext } from '../../context/AuthContext' import Loader from '../../components/layouts/Loader' const AdminUserList = () => { const componentMounted = useRef(true) const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState() const auth = useContext(AuthContext) axios.interceptors.request.use((config) => { config.headers['Content-Type'] = 'application/json' config.headers['Authorization'] = `Bearer ${auth.token}` return config }) useEffect(() => { const getUsers = async () => { try { setLoading(true) const { data } = await axios.get('/admin/user/all') if (componentMounted.current) { setUsers(data) setLoading(false) } return () => { componentMounted.current = false } } catch (err) { if (err.response.data.status === 401) { auth.logout() } setLoading(false) setError(err.response.data.message) } } getUsers() }, [auth]) const deleteHandler = async (user) => { if (window.confirm(`Are you sure to delete ${user._id} ?`)) { try { setLoading(true) const { data } = await axios.delete(`admin/user/delete/${user._id}`) const latestUsers = data.users setUsers(latestUsers) setLoading(false) } catch (err) { setLoading(false) setError(err) } } } return ( <div> {loading && <Loader />} {error ? ( error ) : ( <Table striped bordered hover responsive className='table-sm'> <thead> <tr> <th>ID</th> <th>NAME</th> <th>EMAIL</th> <th></th> </tr> </thead> <tbody> {users.map((user) => ( <tr key={user._id}> <td>{user._id}</td> <td>{user.name}</td> <td>{user.email}</td> <td> <Button variant='danger' className='btn-sm ' onClick={() => deleteHandler(user)} > <i className='fas fa-trash fa-xl'></i> </Button> </td> </tr> ))} </tbody> </Table> )} </div> ) } export default AdminUserList
rspozza/Java
java/TesteEstresse/src/main/java/utfpr/socket/testestress/socket/Servidor.java
<gh_stars>1-10 package utfpr.socket.testestress.socket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.ServerSocket; import java.net.Socket; public class Servidor { private static Socket conexao; private static ServerSocket servidor; private static DataInputStream entrada; private static DataOutputStream saida; public static void main(String[] args) { try { //Criar porta de recepção servidor = new ServerSocket(50000); System.out.println("Aguardando cliente..."); while (true) { conexao = servidor.accept(); //Criar os fluxos de entrada e saída entrada = new DataInputStream(conexao.getInputStream()); saida = new DataOutputStream(conexao.getOutputStream()); // Recebimento dos dados String dado = entrada.readUTF(); //Envio dos dados (resultado) saida.writeUTF(dado.toUpperCase()); // fecha conexão conexao.close(); } } catch (Exception e) { e.printStackTrace(); } } }
dn0000001/test-automation
taf/src/main/java/com/taf/automation/ui/support/conditional/MatchFactory.java
package com.taf.automation.ui.support.conditional; public class MatchFactory { /** * Based on criteria return appropriate match class * * @param criteria - Criteria to find a match for * @return Match class that can work with the criteria to determine if match * @throws RuntimeException if criteria type is not supported or null */ public Match getMatch(Criteria criteria) { if (criteria == null || criteria.getCriteriaType() == null) { throw new RuntimeException("Cannot get Match class for null"); } else if (criteria.getCriteriaType() == CriteriaType.ALERT) { return new AlertMatch(); } else if (criteria.getCriteriaType() == CriteriaType.READY) { return new ElementReadyMatch(); } else if (criteria.getCriteriaType() == CriteriaType.DISPLAYED) { return new ElementDisplayedMatch(); } else if (criteria.getCriteriaType() == CriteriaType.REMOVED) { return new ElementRemovedMatch(); } else if (criteria.getCriteriaType() == CriteriaType.ENABLED) { return new ElementEnabledMatch(); } else if (criteria.getCriteriaType() == CriteriaType.DISABLED) { return new ElementDisabledMatch(); } else if (criteria.getCriteriaType() == CriteriaType.EXISTS) { return new ElementExistsMatch(); } else if (criteria.getCriteriaType() == CriteriaType.SELECTED) { return new ElementSelectedMatch(); } else if (criteria.getCriteriaType() == CriteriaType.UNSELECTED) { return new ElementUnselectedMatch(); } else if (criteria.getCriteriaType() == CriteriaType.STALE) { return new ElementStaleMatch(); } else if (criteria.getCriteriaType() == CriteriaType.TEXT_EQUALS || criteria.getCriteriaType() == CriteriaType.TEXT_EQUALS_IGNORE_CASE || criteria.getCriteriaType() == CriteriaType.TEXT_REGEX || criteria.getCriteriaType() == CriteriaType.TEXT_NOT_EQUAL || criteria.getCriteriaType() == CriteriaType.TEXT_DOES_NOT_CONTAIN || criteria.getCriteriaType() == CriteriaType.TEXT_CONTAINS) { return new ElementTextMatch(); } else if (criteria.getCriteriaType() == CriteriaType.URL_EQUALS || criteria.getCriteriaType() == CriteriaType.URL_EQUALS_IGNORE_CASE || criteria.getCriteriaType() == CriteriaType.URL_REGEX || criteria.getCriteriaType() == CriteriaType.URL_NOT_EQUAL || criteria.getCriteriaType() == CriteriaType.URL_DOES_NOT_CONTAIN || criteria.getCriteriaType() == CriteriaType.URL_CONTAINS) { return new URL_Match(); } else if (criteria.getCriteriaType() == CriteriaType.ATTRIBUTE_EQUALS || criteria.getCriteriaType() == CriteriaType.ATTRIBUTE_EQUALS_IGNORE_CASE || criteria.getCriteriaType() == CriteriaType.ATTRIBUTE_REGEX || criteria.getCriteriaType() == CriteriaType.ATTRIBUTE_NOT_EQUAL || criteria.getCriteriaType() == CriteriaType.ATTRIBUTE_DOES_NOT_CONTAIN || criteria.getCriteriaType() == CriteriaType.ATTRIBUTE_CONTAINS) { return new ElementAttributeMatch(); } else if (criteria.getCriteriaType() == CriteriaType.POPUP) { return new PopupMatch(); } else if (criteria.getCriteriaType() == CriteriaType.DROPDOWN_EQUALS || criteria.getCriteriaType() == CriteriaType.DROPDOWN_EQUALS_IGNORE_CASE || criteria.getCriteriaType() == CriteriaType.DROPDOWN_REGEX || criteria.getCriteriaType() == CriteriaType.DROPDOWN_NOT_EQUAL || criteria.getCriteriaType() == CriteriaType.DROPDOWN_DOES_NOT_CONTAIN || criteria.getCriteriaType() == CriteriaType.DROPDOWN_CONTAINS || criteria.getCriteriaType() == CriteriaType.DROPDOWN_INDEX || criteria.getCriteriaType() == CriteriaType.DROPDOWN_HTML_EQUALS || criteria.getCriteriaType() == CriteriaType.DROPDOWN_HTML_EQUALS_IGNORE_CASE || criteria.getCriteriaType() == CriteriaType.DROPDOWN_HTML_REGEX || criteria.getCriteriaType() == CriteriaType.DROPDOWN_HTML_NOT_EQUAL || criteria.getCriteriaType() == CriteriaType.DROPDOWN_HTML_DOES_NOT_CONTAIN || criteria.getCriteriaType() == CriteriaType.DROPDOWN_HTML_CONTAINS) { return new ElementDropDownMatch(); } else if (criteria.getCriteriaType() == CriteriaType.RELATIVE_READY) { return new ElementReadyRelativeToMatch(); } else if (criteria.getCriteriaType() == CriteriaType.ELEMENTS_EQUAL || criteria.getCriteriaType() == CriteriaType.ELEMENTS_RANGE || criteria.getCriteriaType() == CriteriaType.ELEMENTS_LESS_THAN || criteria.getCriteriaType() == CriteriaType.ELEMENTS_MORE_THAN) { return new NumberOfElementsMatch(); } else if (criteria.getCriteriaType() == CriteriaType.LAMBDA_EXPRESSION) { return new LambdaExpressionMatch(); } else if (criteria.getCriteriaType() == CriteriaType.EXPECTED_CONDITIONS) { return new ExpectedConditionsMatch(); } throw new RuntimeException("Unsupported criteria type: " + criteria.getCriteriaType()); } }
gitter-badger/httpclient
httpclient/src/main/java/org/apache/http/impl/client/exec/BackoffStrategyExec.java
<filename>httpclient/src/main/java/org/apache/http/impl/client/exec/BackoffStrategyExec.java<gh_stars>1-10 /* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.client.exec; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import org.apache.http.HttpException; import org.apache.http.annotation.ThreadSafe; import org.apache.http.client.BackoffManager; import org.apache.http.client.ConnectionBackoffStrategy; import org.apache.http.client.methods.HttpExecutionAware; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.protocol.HttpContext; /** * @since 4.3 */ @ThreadSafe public class BackoffStrategyExec implements ClientExecChain { private final ClientExecChain requestExecutor; private final ConnectionBackoffStrategy connectionBackoffStrategy; private final BackoffManager backoffManager; public BackoffStrategyExec( final ClientExecChain requestExecutor, final ConnectionBackoffStrategy connectionBackoffStrategy, final BackoffManager backoffManager) { super(); if (requestExecutor == null) { throw new IllegalArgumentException("HTTP client request executor may not be null"); } if (connectionBackoffStrategy == null) { throw new IllegalArgumentException("Connection backoff strategy may not be null"); } if (backoffManager == null) { throw new IllegalArgumentException("Backoff manager may not be null"); } this.requestExecutor = requestExecutor; this.connectionBackoffStrategy = connectionBackoffStrategy; this.backoffManager = backoffManager; } public HttpResponseWrapper execute( final HttpRoute route, final HttpRequestWrapper request, final HttpContext context, final HttpExecutionAware execAware) throws IOException, HttpException { if (route == null) { throw new IllegalArgumentException("HTTP route may not be null"); } if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponseWrapper out = null; try { out = this.requestExecutor.execute(route, request, context, execAware); } catch (Exception ex) { if (out != null) { out.close(); } if (this.connectionBackoffStrategy.shouldBackoff(ex)) { this.backoffManager.backOff(route); } if (ex instanceof RuntimeException) throw (RuntimeException) ex; if (ex instanceof HttpException) throw (HttpException) ex; if (ex instanceof IOException) throw (IOException) ex; throw new UndeclaredThrowableException(ex); } if (this.connectionBackoffStrategy.shouldBackoff(out)) { this.backoffManager.backOff(route); } else { this.backoffManager.probe(route); } return out; } }
cameroncooke/XcodeHeaders
PlugIns/GPUDebuggerGLSupport/GPUFramebufferAttachmentInfo.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" __attribute__((visibility("hidden"))) @interface GPUFramebufferAttachmentInfo : NSObject { unsigned int _objectType; unsigned int _textureLevel; unsigned int _textureLayer; unsigned int _textureCubemapFace; } @property(readonly, nonatomic) unsigned int textureCubemapFace; // @synthesize textureCubemapFace=_textureCubemapFace; @property(readonly, nonatomic) unsigned int textureLayer; // @synthesize textureLayer=_textureLayer; @property(readonly, nonatomic) unsigned int textureLevel; // @synthesize textureLevel=_textureLevel; @property(readonly, nonatomic) unsigned int objectType; // @synthesize objectType=_objectType; - (id)initWithAttachmentEnum:(unsigned int)arg1 stateMirror:(id)arg2; @end
bowlofstew/omim
map/benchmark_tool/api.hpp
<gh_stars>1-10 #pragma once #include "std/vector.hpp" #include "std/string.hpp" #include "std/utility.hpp" namespace bench { struct Result { vector<double> m_time; public: double m_all, m_max, m_avg, m_med; public: void Add(double t) { m_time.push_back(t); } void Add(Result const & r) { m_time.insert(m_time.end(), r.m_time.begin(), r.m_time.end()); } void PrintAllTimes(); void CalcMetrics(); }; class AllResult { public: Result m_reading; double m_all; public: AllResult() : m_all(0.0) {} void Add(double t) { m_all += t; } void Print(); }; /// @param[in] count number of times to run benchmark void RunFeaturesLoadingBenchmark(string const & file, pair<int, int> scaleR, AllResult & res); }
MontiCore/monticore
monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoNestedGenericsInAdditionalAttributesTest.java
<reponame>MontiCore/monticore<gh_stars>10-100 /* (c) https://github.com/MontiCore/monticore */ package de.monticore.grammar.cocos; import de.monticore.grammar.grammar_withconcepts._cocos.Grammar_WithConceptsCoCoChecker; import de.se_rwth.commons.logging.LogStub; import org.junit.BeforeClass; import org.junit.Test; public class NoNestedGenericsInAdditionalAttributesTest extends CocoTest { public final String MESSAGE = " %srule does not allow the definition of nested generics. " + "Problem in grammar '%s', rule for '%s', with additional attribute: '%s'."; private static final Grammar_WithConceptsCoCoChecker checker = new Grammar_WithConceptsCoCoChecker(); @BeforeClass public static void disableFailQuick() { LogStub.enableFailQuick(false); checker.addCoCo(new NoNestedGenericsInAdditionalAttributes()); } @Test public void testInvalidNestedGeneric() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102a", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102a", "A", "b:List<Optional<String>>"), checker); } @Test public void testInvalidPlus() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102b", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102b", "A", "b:Optional<String>+"), checker); } @Test public void testInvalidQuestion() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102c", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102c", "A", "b:Optional<String>?"), checker); } @Test public void testInvalidMaxNumber() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102d", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102d", "A", "b:Optional<String> max=5"), checker); } @Test public void testInvalidStar() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102e", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102e", "A", "b:Optional<String>*"), checker); } @Test public void testInvalidMinNull() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102f", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102f", "A", "b:Optional<String> min=0"), checker); } @Test public void testInvalidSymbolRule() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102g", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Symbol", "A4102g", "A", "b:Set<Optional<String>>"), checker); } @Test public void testInvalidScopeRule() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102h", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Scope", "A4102h", "A4102hScope", "b:Optional<String> max=5"), checker); } @Test public void testInvalidMaxStar() { testInvalidGrammar("de.monticore.grammar.cocos.invalid.A4102.A4102i", NoNestedGenericsInAdditionalAttributes.ERROR_CODE, String.format(MESSAGE, "Ast", "A4102i", "A", "b:Optional<String> max=*"), checker); } @Test public void testCorrectASTRule() { testValidGrammar("de.monticore.grammar.cocos.valid.ASTRules", checker); } @Test public void testCorrectSymbolRule() { testValidGrammar("de.monticore.grammar.cocos.valid.SymbolRules", checker); } @Test public void testCorrectScopeRule() { testValidGrammar("de.monticore.grammar.cocos.valid.ScopeRule", checker); } }
travislondon/ciera
examples/GPS/GPS_Watch/src/main/java/gui/SwingWatchGui.java
<reponame>travislondon/ciera<filename>examples/GPS/GPS_Watch/src/main/java/gui/SwingWatchGui.java package gui; import io.ciera.runtime.summit.interfaces.IMessage; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import tracking.shared.Indicator; import tracking.shared.Unit; import ui.shared.IUI; public class SwingWatchGui extends JFrame implements WatchGui { public static final long serialVersionUID = 0; public static final int LARGE_Y = 355; public static final int SMALL_Y = 295; public static final int INDICATOR_Y = SMALL_Y + ((LARGE_Y - SMALL_Y) / 2); public static final String[] UNIT_LABELS = new String[] { "km", "meters", "min/km", "km/h", "miles", "yds", "ft", "min/mile", "mph", "bpm", "laps" }; public static final int UNIT_KM = 0; public static final int UNIT_METERS = 1; public static final int UNIT_MIN_PER_KM = 2; public static final int UNIT_KM_PER_HOUR = 3; public static final int UNIT_MILES = 4; public static final int UNIT_YDS = 5; public static final int UNIT_FT = 6; public static final int UNIT_MIN_PER_MILE = 7; public static final int UNIT_MPH = 8; public static final int UNIT_BPM = 9; public static final int UNIT_LAPS = 10; public static final int INDICATOR_BLANK = 0; public static final int INDICATOR_DOWN = 1; public static final int INDICATOR_FLAT = 2; public static final int INDICATOR_UP = 3; private Gui signalHandler; private JPanel holdAll = new JPanel(); protected ImageIcon watch; protected ImageIcon watchIcon; protected ImageIcon lightHover; protected ImageIcon powerPressed; protected ImageIcon displayHover; protected ImageIcon displayPressed; protected ImageIcon modeHover; protected ImageIcon modePressed; protected ImageIcon lapResetHover; protected ImageIcon lapResetPressed; protected ImageIcon startStopHover; protected ImageIcon startStopPressed; protected ImageIcon smallSeparator; protected ImageIcon largeDots; protected ImageIcon upArrow; protected ImageIcon downArrow; protected ImageIcon flat; protected ImageIcon blank; protected ImageIcon smallDigit[] = new ImageIcon[10]; protected ImageIcon largeDigit[] = new ImageIcon[10]; private JLabel watchLabel = new JLabel(); private JLabel lightLabel = new JLabel(); private JLabel displayLabel = new JLabel(); private JLabel modeLabel = new JLabel(); private JLabel lapResetLabel = new JLabel(); private JLabel startStopLabel = new JLabel(); private JLabel smallSeparatorLabel = new JLabel(); private JLabel largeDotsLabel = new JLabel(); private JLabel unitsLabel = new JLabel(); private JLabel indicatorLabel = new JLabel(); private JLabel[] smallDigitLabel = new JLabel[4]; private JLabel[] largeDigitLabel = new JLabel[4]; protected ImageIcon createStandaloneImageIcon(String path) { URL imgURL = ClassLoader.getSystemResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } protected void createImageIcons() { watch = createStandaloneImageIcon("gui/img/watch.png"); watchIcon = createStandaloneImageIcon("gui/img/app_icon.gif"); lightHover = createStandaloneImageIcon("gui/img/light_hover.png"); powerPressed = createStandaloneImageIcon("gui/img/light_pressed.png"); displayHover = createStandaloneImageIcon("gui/img/display_hover.png"); displayPressed = createStandaloneImageIcon("gui/img/display_pressed.png"); modeHover = createStandaloneImageIcon("gui/img/mode_hover.png"); modePressed = createStandaloneImageIcon("gui/img/mode_pressed.png"); lapResetHover = createStandaloneImageIcon("gui/img/lap_reset_hover.png"); lapResetPressed = createStandaloneImageIcon("gui/img/lap_reset_pressed.png"); startStopHover = createStandaloneImageIcon("gui/img/start_stop_hover.png"); startStopPressed = createStandaloneImageIcon("gui/img/start_stop_pressed.png"); smallSeparator = createStandaloneImageIcon("gui/img/dots_small.png"); largeDots = createStandaloneImageIcon("gui/img/dots_large.png"); upArrow = createStandaloneImageIcon("gui/img/up.png"); downArrow = createStandaloneImageIcon("gui/img/down.png"); blank = createStandaloneImageIcon("gui/img/blank.png"); flat = createStandaloneImageIcon("gui/img/flat.png"); for (int i = 0; i < largeDigit.length; i++) { largeDigit[i] = createStandaloneImageIcon("gui/img/" + i + "_large.png"); smallDigit[i] = createStandaloneImageIcon("gui/img/" + i + "_small.png"); } } public SwingWatchGui(Gui gui) { // set signal handler signalHandler = gui; // load images that make up the GUI createImageIcons(); // container holding all button/display images JLayeredPane pane = new JLayeredPane(); // background image watchLabel.setIcon(watch); watchLabel.setBounds(0, 0, 487, 756); lightLabel.setBounds(0, 190, 75, 122); lightLabel.addMouseListener(new ButtonListener(lightHover, powerPressed) { public void buttonPressed() { SwingWatchGui.this.sendSignal(new IUI.SetTargetPressed()); } }); startStopLabel.setBounds(165, 499, 164, 70); startStopLabel.addMouseListener(new ButtonListener(startStopHover, startStopPressed) { public void buttonPressed() { SwingWatchGui.this.sendSignal(new IUI.StartStopPressed()); } }); lapResetLabel.setBounds(420, 434, 83, 121); lapResetLabel.addMouseListener(new ButtonListener(lapResetHover, lapResetPressed) { public void buttonPressed() { SwingWatchGui.this.sendSignal(new IUI.LapResetPressed()); } }); displayLabel.setBounds(412, 190, 75, 122); displayLabel.addMouseListener(new ButtonListener(displayHover, displayPressed) { public void buttonPressed() { SwingWatchGui.this.sendSignal(new IUI.LightPressed()); } }); modeLabel.setBounds(0, 434, 81, 121); modeLabel.addMouseListener(new ButtonListener(modeHover, modePressed) { public void buttonPressed() { SwingWatchGui.this.sendSignal(new IUI.ModePressed()); } }); // configure and position display images smallSeparatorLabel.setBounds(210, SMALL_Y + 15, 8, 21); smallSeparatorLabel.setIcon(smallSeparator); largeDotsLabel.setBounds(242, LARGE_Y + 28, 13, 35); largeDotsLabel.setIcon(largeDots); indicatorLabel.setBounds(120, INDICATOR_Y, 26, 51); indicatorLabel.setIcon(blank); unitsLabel.setText(""); unitsLabel.setBounds(275, SMALL_Y + 28, 100, 25); unitsLabel.setForeground(Color.DARK_GRAY); unitsLabel.setFont(new Font("verdana", 0, 25)); // add button/display images to a layer where they are visible pane.add(watchLabel, JLayeredPane.PALETTE_LAYER); pane.add(lightLabel, JLayeredPane.POPUP_LAYER); pane.add(displayLabel, JLayeredPane.POPUP_LAYER); pane.add(modeLabel, JLayeredPane.POPUP_LAYER); pane.add(lapResetLabel, JLayeredPane.POPUP_LAYER); pane.add(startStopLabel, JLayeredPane.POPUP_LAYER); pane.add(smallSeparatorLabel, JLayeredPane.POPUP_LAYER); pane.add(largeDotsLabel, JLayeredPane.POPUP_LAYER); pane.add(unitsLabel, JLayeredPane.POPUP_LAYER); pane.add(indicatorLabel, JLayeredPane.POPUP_LAYER); for (int i = 0; i < largeDigitLabel.length; i++) { smallDigitLabel[i] = new JLabel(); setSmallDigit(i, 0); smallDigitLabel[i].setBounds(160 + i * 26 + (i > 1 ? 5 : 0), SMALL_Y, 26, 51); pane.add(smallDigitLabel[i], JLayeredPane.POPUP_LAYER); largeDigitLabel[i] = new JLabel(); setLargeDigit(i, 0); largeDigitLabel[i].setBounds(150 + i * 49 + (i > 1 ? 8 : 0), LARGE_Y, 43, 94); pane.add(largeDigitLabel[i], JLayeredPane.POPUP_LAYER); } holdAll.setLayout(new BorderLayout()); holdAll.add(pane, BorderLayout.CENTER); getContentPane().add(pane, BorderLayout.CENTER); setLocation(10, 10); setSize(496, 790); setAlwaysOnTop(true); setIconImage(watchIcon.getImage()); setTitle("Gps Watch"); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void setSmallDigit(int index, int value) { smallDigitLabel[index].setIcon(smallDigit[value]); } private void setLargeDigit(int index, int value) { largeDigitLabel[index].setIcon(largeDigit[value]); } private void setUnit(String unit) { unitsLabel.setText(unit); } private void showSeparator(boolean show) { if (show) { smallSeparatorLabel.setIcon(smallSeparator); } else { smallSeparatorLabel.setIcon(null); } } @Override public void setTime(int time) { int min = (time % 3600) / 60; int sec = time % 60; setLargeDigit(0, min / 10); setLargeDigit(1, min % 10); setLargeDigit(2, sec / 10); setLargeDigit(3, sec % 10); } private void setFloatingPointValue(float value) { setSmallDigit(0, (int)(value / 10f) % 10); setSmallDigit(1, (int)(value) % 10); setSmallDigit(2, (int)(value * 10f) % 10); setSmallDigit(3, (int)(value * 100f) % 10); } private void setDiscreteValue(float value) { setSmallDigit(0, (int)(value / 1000f) % 10); setSmallDigit(1, (int)(value / 100f) % 10); setSmallDigit(2, (int)(value / 10f) % 10); setSmallDigit(3, (int)(value) % 10); } private void setTimex(float value) { int min = (int)value % 60; // this will truncate the hour value int sec = (int)(60 * value) % 60; setSmallDigit(0, min / 10); setSmallDigit(1, min % 10); setSmallDigit(2, sec / 10); setSmallDigit(3, sec % 10); } @Override public void setData(float value, Unit unit) { switch (unit.getValue()) { case UNIT_KM: case UNIT_MILES: case UNIT_KM_PER_HOUR: case UNIT_MPH: setFloatingPointValue(value); showSeparator(true); break; case UNIT_METERS: case UNIT_YDS: case UNIT_FT: case UNIT_BPM: case UNIT_LAPS: setDiscreteValue(value); showSeparator(false); break; case UNIT_MIN_PER_KM: case UNIT_MIN_PER_MILE: setTimex(value); showSeparator(true); break; default: break; } setUnit(UNIT_LABELS[unit.getValue()]); } @Override public void setIndicator(Indicator value){ switch (value.getValue()) { case INDICATOR_DOWN: indicatorLabel.setIcon(downArrow); break; case INDICATOR_FLAT: indicatorLabel.setIcon(flat); break; case INDICATOR_UP: indicatorLabel.setIcon(upArrow); break; case INDICATOR_BLANK: indicatorLabel.setIcon(blank); default: break; } } /** * A generic button listener that will switch images when * buttons are hovered/pressed/released */ public abstract class ButtonListener implements MouseListener { private ImageIcon hover; private ImageIcon pressed; private ImageIcon cached; private boolean inside = false; public ButtonListener(ImageIcon hover, ImageIcon pressed) { this.hover = hover; this.pressed = pressed; cached = hover; } public void mouseExited(MouseEvent me) { ((JLabel)me.getSource()).setIcon(null); inside = false; } public void mousePressed(MouseEvent me) { cached = pressed; ((JLabel)me.getSource()).setIcon(pressed); } public void mouseEntered(MouseEvent me) { ((JLabel)me.getSource()).setIcon(cached); inside = true; } public void mouseReleased(MouseEvent me) { cached = hover; if (inside) { ((JLabel)me.getSource()).setIcon(cached); buttonPressed(); } else { ((JLabel)me.getSource()).setIcon(null); } } public void mouseClicked(MouseEvent me) {} public abstract void buttonPressed(); } private void sendSignal(IMessage message) { signalHandler.sendSignal(message); } @Override public void display() { setVisible(true); } }
dualword/pymol-open-source
layerCTest/Test_Event.cpp
#include "Test.h" #include "Event.h" static int x = 2; static void some_func(int inc) { x += inc; x += 100; } TEST_CASE("Event Test", "[Event]") { auto callback = [&](int inc) { x += inc; x += 10; }; pymol::Event<int> event_publisher{}; REQUIRE(event_publisher.size() == 0); event_publisher.add_listener(callback); REQUIRE(event_publisher.size() == 1); event_publisher.invoke(5); // 2 + 5 + 10 REQUIRE(x == 17); event_publisher.add_listener(some_func); event_publisher.invoke(-5); REQUIRE(x == 117); // 17 + (- 5 + 10) + (- 5 + 100) }
pdibenedetto/Axon4Example
src/main/java/nl/avthart/todo/app/common/exceptions/CantRestoreException.java
<filename>src/main/java/nl/avthart/todo/app/common/exceptions/CantRestoreException.java package nl.avthart.todo.app.common.exceptions; public class CantRestoreException extends BadRequestException { public CantRestoreException( String message, Throwable... cause ) { super( message, cause ); } }
asmuratbek/oobamarket
apps/index/models.py
from ckeditor_uploader.fields import RichTextUploadingField from django.db import models from apps.utils.models import PublishBaseModel # Create your models here. COLUMNS_TYPES = ( ("first_col", "Первая колонка"), ("second_col", "Вторая колонка"), ("third_col", "Третья колонка") ) BLOCK_TYPES = ( ("big_up_block", "Большой верхний блок"), ("big_down_block", "Большой нижний блок"), ("up_left_corner_1", "Верхняя левая сторона верхний блок"), ("up_left_corner_2", "Верхняя левая сторона нижний блок"), ("up_right_corner_1", "Верхняя правая сторона верхний блок"), ("up_right_corner_2", "Верхняя правая сторона нижний блок"), ("down_right_corner_1", "Нижняя правая сторона верхний блок"), ("down_right_corner_2", "Нижняя правая сторона нижний блок"), ) BANNERS_TYPES = ( ("offer", "Рекламное предложение"), ("slider", "Банер на слайдер"), ) class IndexBlocks(PublishBaseModel): title = models.CharField(max_length=400, verbose_name="Название блока", null=True, blank=True) url = models.CharField(max_length=450, verbose_name="Урл") image = models.ImageField(upload_to="images/index/") column = models.CharField(max_length=50, verbose_name="Колонка", choices=COLUMNS_TYPES) row = models.PositiveSmallIntegerField(verbose_name="Ряд") class Meta: verbose_name = "Блок на главной странице" verbose_name_plural = "Блоки на главной странице" def __str__(self): return "{col} - {row} ряд.".format(col=self.get_column_display(), row=self.row) class PremiumIndexBlocks(PublishBaseModel): title = models.CharField(max_length=300, verbose_name='Наименование блока', null=True, blank=True) url = models.CharField(max_length=450, verbose_name='Ссылка') block_type = models.CharField(max_length=100, verbose_name='Тип блока', choices=BLOCK_TYPES, unique=True) image = models.ImageField(upload_to='images/index/premium/', verbose_name="Изображение блока") class Meta: verbose_name = "Премиум блок" verbose_name_plural = "Премиум блоки на главной странице" def __str__(self): return self.get_block_type_display() class IndexBanner(PublishBaseModel): image = models.ImageField(upload_to='images/index/banners/', verbose_name='Изображение банера') banner_type = models.CharField(max_length=50, verbose_name='Тип банера', choices=BANNERS_TYPES) url = models.CharField(max_length=450, verbose_name='Ссылка') class Meta: verbose_name = 'Банер' verbose_name_plural = 'Банера на главной странице' def __str__(self): return self.get_banner_type_display() class Help(models.Model): class Meta: verbose_name = 'Помощь' verbose_name_plural = 'Помощь' title = models.CharField(max_length=1000, verbose_name='Заголовок', null=False) description = RichTextUploadingField(verbose_name='Описание', null=True) def __str__(self): return self.title
daver32/Minecraft-Clone
src/renderEngine/binds/MouseDragBind.java
package renderEngine.binds; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; public class MouseDragBind extends Bind { private int key; private boolean isMouseBind, isPressed; private int[] startingPoint, currentPoint; public MouseDragBind(int key, boolean isMouseBind) { this.key = key; this.isMouseBind = isMouseBind; startingPoint = new int[2]; currentPoint = new int[2]; } @Override public void update(double time) { boolean buttonIsPressed = isMouseBind ? Mouse.isButtonDown(key) : Keyboard.isKeyDown(key); if(buttonIsPressed){ int mouseX = Mouse.getX(); int mouseY = Mouse.getY(); if(!isPressed){ isPressed = true; startingPoint[0] = mouseX; startingPoint[1] = mouseY; }else{ currentPoint[0] = mouseX; currentPoint[1] = mouseY; } }else{ isPressed = false; } } public int[] getDrag(){ if(isPressed){ return new int[]{currentPoint[0] - startingPoint[0], currentPoint[1] - startingPoint[1]}; }else{ return null; } } }
Cindia-blue/openairenb
cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14/LTE_SL-DiscTxResourceInfoPerFreq-r13.c
<reponame>Cindia-blue/openairenb /* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "/home/lixh/enb_folder/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1" * `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/lixh/enb_folder/cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14` */ #include "LTE_SL-DiscTxResourceInfoPerFreq-r13.h" asn_TYPE_member_t asn_MBR_LTE_SL_DiscTxResourceInfoPerFreq_r13_1[] = { { ATF_NOFLAGS, 0, offsetof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13, discTxCarrierFreq_r13), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_ARFCN_ValueEUTRA_r9, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "discTxCarrierFreq-r13" }, { ATF_POINTER, 4, offsetof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13, discTxResources_r13), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), +1, /* EXPLICIT tag at current level */ &asn_DEF_LTE_SL_DiscTxResource_r13, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "discTxResources-r13" }, { ATF_POINTER, 3, offsetof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13, discTxResourcesPS_r13), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), +1, /* EXPLICIT tag at current level */ &asn_DEF_LTE_SL_DiscTxResource_r13, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "discTxResourcesPS-r13" }, { ATF_POINTER, 2, offsetof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13, discTxRefCarrierDedicated_r13), (ASN_TAG_CLASS_CONTEXT | (3 << 2)), +1, /* EXPLICIT tag at current level */ &asn_DEF_LTE_SL_DiscTxRefCarrierDedicated_r13, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "discTxRefCarrierDedicated-r13" }, { ATF_POINTER, 1, offsetof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13, discCellSelectionInfo_r13), (ASN_TAG_CLASS_CONTEXT | (4 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CellSelectionInfoNFreq_r13, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "discCellSelectionInfo-r13" }, }; static const int asn_MAP_LTE_SL_DiscTxResourceInfoPerFreq_r13_oms_1[] = { 1, 2, 3, 4 }; static const ber_tlv_tag_t asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_SL_DiscTxResourceInfoPerFreq_r13_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* discTxCarrierFreq-r13 */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* discTxResources-r13 */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* discTxResourcesPS-r13 */ { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 }, /* discTxRefCarrierDedicated-r13 */ { (ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0 } /* discCellSelectionInfo-r13 */ }; asn_SEQUENCE_specifics_t asn_SPC_LTE_SL_DiscTxResourceInfoPerFreq_r13_specs_1 = { sizeof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13), offsetof(struct LTE_SL_DiscTxResourceInfoPerFreq_r13, _asn_ctx), asn_MAP_LTE_SL_DiscTxResourceInfoPerFreq_r13_tag2el_1, 5, /* Count of tags in the map */ asn_MAP_LTE_SL_DiscTxResourceInfoPerFreq_r13_oms_1, /* Optional members */ 4, 0, /* Root/Additions */ 5, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13 = { "SL-DiscTxResourceInfoPerFreq-r13", "SL-DiscTxResourceInfoPerFreq-r13", &asn_OP_SEQUENCE, asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1, sizeof(asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1) /sizeof(asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1[0]), /* 1 */ asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1, /* Same as above */ sizeof(asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1) /sizeof(asn_DEF_LTE_SL_DiscTxResourceInfoPerFreq_r13_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_SL_DiscTxResourceInfoPerFreq_r13_1, 5, /* Elements count */ &asn_SPC_LTE_SL_DiscTxResourceInfoPerFreq_r13_specs_1 /* Additional specs */ };
AbdouTlili/onos-e2-em
servicemodels/e2sm_rc_pre/rcprectypes/E2SM-RC-PRE-ControlHeader-RCPRE.h
<filename>servicemodels/e2sm_rc_pre/rcprectypes/E2SM-RC-PRE-ControlHeader-RCPRE.h /* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "E2SM-RC-PRE-IEs" * found in "../v2/e2sm-rc-pre_v2_rsys.asn" * `asn1c -fcompound-names -fincludes-quoted -fno-include-deps -findirect-choice -gen-PER -no-gen-OER -D.` */ #ifndef _E2SM_RC_PRE_ControlHeader_RCPRE_H_ #define _E2SM_RC_PRE_ControlHeader_RCPRE_H_ #include "asn_application.h" /* Including external dependencies */ #include "constr_CHOICE.h" #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum E2SM_RC_PRE_ControlHeader_RCPRE_PR { E2SM_RC_PRE_ControlHeader_RCPRE_PR_NOTHING, /* No components present */ E2SM_RC_PRE_ControlHeader_RCPRE_PR_controlHeader_Format1 /* Extensions may appear below */ } E2SM_RC_PRE_ControlHeader_RCPRE_PR; /* Forward declarations */ struct E2SM_RC_PRE_ControlHeader_Format1_RCPRE; /* E2SM-RC-PRE-ControlHeader-RCPRE */ typedef struct E2SM_RC_PRE_ControlHeader_RCPRE { E2SM_RC_PRE_ControlHeader_RCPRE_PR present; union E2SM_RC_PRE_ControlHeader_RCPRE_u { struct E2SM_RC_PRE_ControlHeader_Format1_RCPRE *controlHeader_Format1; /* * This type is extensible, * possible extensions are below. */ } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } E2SM_RC_PRE_ControlHeader_RCPRE_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_E2SM_RC_PRE_ControlHeader_RCPRE; #ifdef __cplusplus } #endif #endif /* _E2SM_RC_PRE_ControlHeader_RCPRE_H_ */ #include "asn_internal.h"
jmuseri/got
src/test/java/ar/com/bbva/got/service/funcional/TramiteServiceTests.java
<filename>src/test/java/ar/com/bbva/got/service/funcional/TramiteServiceTests.java package ar.com.bbva.got.service.funcional; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.Assert; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Optional; import java.util.stream.Collectors; import ar.com.bbva.got.model.Autorizado; import ar.com.bbva.got.model.EstadoTramite; import ar.com.bbva.got.model.Sector; import ar.com.bbva.got.model.SectorKey; import ar.com.bbva.got.model.TipoTramite; import ar.com.bbva.got.model.Tramite; import ar.com.bbva.got.model.TramiteAutorizado; import ar.com.bbva.got.repository.TramiteRepository; @RunWith(SpringRunner.class) @SpringBootTest public class TramiteServiceTests { private static List<Tramite> listaTramites = new ArrayList<Tramite>(); @Mock private TramiteRepository tramiteRepository; @InjectMocks private TramiteServiceImpl tramiteService; @BeforeClass public static void setUp() { listaTramites.add(new Tramite()); listaTramites.get(0).setId(1); listaTramites.get(0).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(0).setNroClienteEmpresa(123); listaTramites.get(0).setCuitEmpresa("123"); listaTramites.get(0).setUsuModif("usuario1"); listaTramites.get(0).setTipoTramite(new TipoTramite()); listaTramites.get(0).getTipoTramite().setId(1); listaTramites.get(0).setSectorActual(new Sector()); listaTramites.get(0).getSectorActual().setId(new SectorKey()); listaTramites.get(0).getSectorActual().getId().setSector("sector1"); listaTramites.get(0).setSectorInicio(new Sector()); listaTramites.get(0).getSectorInicio().setId(new SectorKey()); listaTramites.get(0).getSectorInicio().getId().setSector("sector"); listaTramites.get(0).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(0).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(0).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(0).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(0).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(1).setId(2); listaTramites.get(1).setEstado(EstadoTramite.RECHAZADO); listaTramites.get(1).setNroClienteEmpresa(1234); listaTramites.get(1).setCuitEmpresa("123"); listaTramites.get(1).setTipoTramite(new TipoTramite()); listaTramites.get(1).getTipoTramite().setId(1); listaTramites.get(1).setSectorActual(new Sector()); listaTramites.get(1).getSectorActual().setId(new SectorKey()); listaTramites.get(1).getSectorActual().getId().setSector("sector1"); listaTramites.get(1).setSectorInicio(new Sector()); listaTramites.get(1).getSectorInicio().setId(new SectorKey()); listaTramites.get(1).getSectorInicio().getId().setSector("sector"); listaTramites.get(1).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(1).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(1).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(1).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(1).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(2).setId(3); listaTramites.get(2).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(2).setNroClienteEmpresa(123); listaTramites.get(2).setCuitEmpresa("123"); listaTramites.get(2).setTipoTramite(new TipoTramite()); listaTramites.get(2).getTipoTramite().setId(2); listaTramites.get(2).setSectorActual(new Sector()); listaTramites.get(2).getSectorActual().setId(new SectorKey()); listaTramites.get(2).getSectorActual().getId().setSector("sector2"); listaTramites.get(2).setSectorInicio(new Sector()); listaTramites.get(2).getSectorInicio().setId(new SectorKey()); listaTramites.get(2).getSectorInicio().getId().setSector("sector"); listaTramites.get(2).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(2).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(2).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(2).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(2).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(3).setId(4); listaTramites.get(3).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(3).setNroClienteEmpresa(222); listaTramites.get(3).setCuitEmpresa("1233"); listaTramites.get(3).setTipoTramite(new TipoTramite()); listaTramites.get(3).getTipoTramite().setId(3); listaTramites.get(3).setSectorActual(new Sector()); listaTramites.get(3).getSectorActual().setId(new SectorKey()); listaTramites.get(3).getSectorActual().getId().setSector("sector4"); listaTramites.get(3).setSectorInicio(new Sector()); listaTramites.get(3).getSectorInicio().setId(new SectorKey()); listaTramites.get(3).getSectorInicio().getId().setSector("sectorotro"); listaTramites.get(3).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(3).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(3).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(3).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(3).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(4).setId(5); listaTramites.get(4).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(4).setNroClienteEmpresa(123); listaTramites.get(4).setCuitEmpresa("123"); listaTramites.get(4).setTipoTramite(new TipoTramite()); listaTramites.get(4).getTipoTramite().setId(1); listaTramites.get(4).setSectorActual(new Sector()); listaTramites.get(4).getSectorActual().setId(new SectorKey()); listaTramites.get(4).getSectorActual().getId().setSector("sector4"); listaTramites.get(4).setSectorInicio(new Sector()); listaTramites.get(4).getSectorInicio().setId(new SectorKey()); listaTramites.get(4).getSectorInicio().getId().setSector("sectorotro"); listaTramites.get(4).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(4).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(4).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(4).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(4).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(5).setId(1); listaTramites.get(5).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(5).setNroClienteEmpresa(123); listaTramites.get(5).setCuitEmpresa("123"); listaTramites.get(5).setTipoTramite(new TipoTramite()); listaTramites.get(5).getTipoTramite().setId(1); listaTramites.get(5).setSectorActual(new Sector()); listaTramites.get(5).getSectorActual().setId(new SectorKey()); listaTramites.get(5).getSectorActual().getId().setSector("sector1"); listaTramites.get(5).setSectorInicio(new Sector()); listaTramites.get(5).getSectorInicio().setId(new SectorKey()); listaTramites.get(5).getSectorInicio().getId().setSector("sector"); listaTramites.get(5).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(5).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(5).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(5).getAutorizado().iterator().next().getAutorizado().setNroDocumento("1231234"); listaTramites.get(5).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI2"); listaTramites.add(new Tramite()); listaTramites.get(6).setId(1); listaTramites.get(6).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(6).setNroClienteEmpresa(123); listaTramites.get(6).setCuitEmpresa("123"); listaTramites.get(6).setTipoTramite(new TipoTramite()); listaTramites.get(6).getTipoTramite().setId(1); listaTramites.get(6).setSectorActual(new Sector()); listaTramites.get(6).getSectorActual().setId(new SectorKey()); listaTramites.get(6).getSectorActual().getId().setSector("sector1"); listaTramites.get(6).setSectorInicio(new Sector()); listaTramites.get(6).getSectorInicio().setId(new SectorKey()); listaTramites.get(6).getSectorInicio().getId().setSector("sector"); listaTramites.get(6).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(6).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(6).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(6).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(6).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI2"); listaTramites.add(new Tramite()); listaTramites.get(7).setId(1); listaTramites.get(7).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(7).setNroClienteEmpresa(123); listaTramites.get(7).setCuitEmpresa("123"); listaTramites.get(7).setTipoTramite(new TipoTramite()); listaTramites.get(7).getTipoTramite().setId(1); listaTramites.get(7).setSectorActual(new Sector()); listaTramites.get(7).getSectorActual().setId(new SectorKey()); listaTramites.get(7).getSectorActual().getId().setSector("sector1"); listaTramites.get(7).setSectorInicio(new Sector()); listaTramites.get(7).getSectorInicio().setId(new SectorKey()); listaTramites.get(7).getSectorInicio().getId().setSector("sector"); listaTramites.get(7).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(7).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(7).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(7).getAutorizado().iterator().next().getAutorizado().setNroDocumento("1231234"); listaTramites.get(7).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(8).setId(1); listaTramites.get(8).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(8).setNroClienteEmpresa(123); listaTramites.get(8).setCuitEmpresa("123"); listaTramites.get(8).setTipoTramite(new TipoTramite()); listaTramites.get(8).getTipoTramite().setId(1); listaTramites.get(8).setSectorActual(new Sector()); listaTramites.get(8).getSectorActual().setId(new SectorKey()); listaTramites.get(8).getSectorActual().getId().setSector("sector1"); listaTramites.get(8).setSectorInicio(new Sector()); listaTramites.get(8).getSectorInicio().setId(new SectorKey()); listaTramites.get(8).getSectorInicio().getId().setSector("sectorotro"); listaTramites.get(8).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(8).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(8).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(8).getAutorizado().iterator().next().getAutorizado().setNroDocumento("1231234"); listaTramites.get(8).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(9).setId(10); listaTramites.get(9).setEstado(EstadoTramite.FINALIZADO); listaTramites.get(9).setNroClienteEmpresa(123); listaTramites.get(9).setCuitEmpresa("123"); listaTramites.get(9).setTipoTramite(new TipoTramite()); listaTramites.get(9).getTipoTramite().setId(1); listaTramites.get(9).setSectorActual(new Sector()); listaTramites.get(9).getSectorActual().setId(new SectorKey()); listaTramites.get(9).getSectorActual().getId().setSector("sector1"); listaTramites.get(9).setSectorInicio(new Sector()); listaTramites.get(9).getSectorInicio().setId(new SectorKey()); listaTramites.get(9).getSectorInicio().getId().setSector("sector"); listaTramites.get(9).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(9).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(9).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(9).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(9).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(10).setId(11); listaTramites.get(10).setEstado(EstadoTramite.GESTION); listaTramites.get(10).setNroClienteEmpresa(123); listaTramites.get(10).setCuitEmpresa("123"); listaTramites.get(10).setTipoTramite(new TipoTramite()); listaTramites.get(10).getTipoTramite().setId(1); listaTramites.get(10).setSectorActual(new Sector()); listaTramites.get(10).getSectorActual().setId(new SectorKey()); listaTramites.get(10).getSectorActual().getId().setSector("sector1"); listaTramites.get(10).setSectorInicio(new Sector()); listaTramites.get(10).getSectorInicio().setId(new SectorKey()); listaTramites.get(10).getSectorInicio().getId().setSector("sector"); listaTramites.get(10).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(10).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(10).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(10).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(10).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(11).setId(11); listaTramites.get(11).setEstado(EstadoTramite.FINALIZADO); listaTramites.get(11).setNroClienteEmpresa(123); listaTramites.get(11).setCuitEmpresa("123"); listaTramites.get(11).setUsuModif("otrousuario"); listaTramites.get(11).setTipoTramite(new TipoTramite()); listaTramites.get(11).getTipoTramite().setId(1); listaTramites.get(11).setSectorActual(new Sector()); listaTramites.get(11).getSectorActual().setId(new SectorKey()); listaTramites.get(11).getSectorActual().getId().setSector("sector1"); listaTramites.get(11).setSectorInicio(new Sector()); listaTramites.get(11).getSectorInicio().setId(new SectorKey()); listaTramites.get(11).getSectorInicio().getId().setSector("sector"); listaTramites.get(11).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(11).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(11).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(11).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(11).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(12).setId(11); listaTramites.get(12).setEstado(EstadoTramite.GESTION); listaTramites.get(12).setNroClienteEmpresa(123); listaTramites.get(12).setCuitEmpresa("123"); listaTramites.get(12).setUsuModif("otrousuario"); listaTramites.get(12).setTipoTramite(new TipoTramite()); listaTramites.get(12).getTipoTramite().setId(1); listaTramites.get(12).setSectorActual(new Sector()); listaTramites.get(12).getSectorActual().setId(new SectorKey()); listaTramites.get(12).getSectorActual().getId().setSector("sector1"); listaTramites.get(12).setSectorInicio(new Sector()); listaTramites.get(12).getSectorInicio().setId(new SectorKey()); listaTramites.get(12).getSectorInicio().getId().setSector("sector"); listaTramites.get(12).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(12).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(12).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(12).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(12).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(13).setId(11); listaTramites.get(13).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(13).setNroClienteEmpresa(123); listaTramites.get(13).setCuitEmpresa("123"); listaTramites.get(13).setUsuModif("otrousuario"); listaTramites.get(13).setTipoTramite(new TipoTramite()); listaTramites.get(13).getTipoTramite().setId(1); listaTramites.get(13).setSectorActual(new Sector()); listaTramites.get(13).getSectorActual().setId(new SectorKey()); listaTramites.get(13).getSectorActual().getId().setSector("sector1"); listaTramites.get(13).setSectorInicio(new Sector()); listaTramites.get(13).getSectorInicio().setId(new SectorKey()); listaTramites.get(13).getSectorInicio().getId().setSector("sector"); listaTramites.get(13).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(13).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(13).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(13).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(13).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(14).setId(11); listaTramites.get(14).setEstado(EstadoTramite.PENDIENTE); listaTramites.get(14).setNroClienteEmpresa(123); listaTramites.get(14).setCuitEmpresa("123"); listaTramites.get(14).setTipoTramite(new TipoTramite()); listaTramites.get(14).getTipoTramite().setId(1); listaTramites.get(14).setSectorActual(new Sector()); listaTramites.get(14).getSectorActual().setId(new SectorKey()); listaTramites.get(14).getSectorActual().getId().setSector("sector1"); listaTramites.get(14).setSectorInicio(new Sector()); listaTramites.get(14).getSectorInicio().setId(new SectorKey()); listaTramites.get(14).getSectorInicio().getId().setSector("sector"); listaTramites.get(14).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(14).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(14).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(14).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(14).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); listaTramites.add(new Tramite()); listaTramites.get(15).setId(11); listaTramites.get(15).setEstado(EstadoTramite.RECHAZADO); listaTramites.get(15).setNroClienteEmpresa(123); listaTramites.get(15).setCuitEmpresa("123"); listaTramites.get(15).setUsuModif("usuario1"); listaTramites.get(15).setTipoTramite(new TipoTramite()); listaTramites.get(15).getTipoTramite().setId(1); listaTramites.get(15).setSectorActual(new Sector()); listaTramites.get(15).getSectorActual().setId(new SectorKey()); listaTramites.get(15).getSectorActual().getId().setSector("sector1"); listaTramites.get(15).setSectorInicio(new Sector()); listaTramites.get(15).getSectorInicio().setId(new SectorKey()); listaTramites.get(15).getSectorInicio().getId().setSector("sector"); listaTramites.get(15).setAutorizado(new HashSet<TramiteAutorizado>()); listaTramites.get(15).getAutorizado().add(new TramiteAutorizado()); listaTramites.get(15).getAutorizado().iterator().next().setAutorizado(new Autorizado()); listaTramites.get(15).getAutorizado().iterator().next().getAutorizado().setNroDocumento("123123"); listaTramites.get(15).getAutorizado().iterator().next().getAutorizado().setTipoDocumento("DNI"); } @Test public void testListAll() { Mockito.when(tramiteRepository.findAll()).thenReturn(listaTramites); Iterable<Tramite> tramitesRecibidos = tramiteService.listAll(); Assert.assertEquals(listaTramites, tramitesRecibidos); } @Test public void testListBySector() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); Sector sectorAFiltrar = new Sector(); sectorAFiltrar.setId(new SectorKey()); sectorAFiltrar.getId().setSector("sector1"); for (Tramite tramite : listaTramites) { if (tramite.getSectorActual().getId().getSector() == sectorAFiltrar.getId().getSector()) tramitesFiltrados.add(tramite); } Mockito.when(tramiteRepository.findBySectorActual(sectorAFiltrar)).thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.listBySectorActual(sectorAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testListByEstado() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); EstadoTramite estadoAFiltrar = EstadoTramite.PENDIENTE; for (Tramite tramite : listaTramites) { if (tramite.getEstado() == estadoAFiltrar) tramitesFiltrados.add(tramite); } Mockito.when(tramiteRepository.findByEstado(estadoAFiltrar)).thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.listByEstado(estadoAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testListByEmpresaEstadoAndTipoTramiteAndSectorInicio() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); EstadoTramite estadoAFiltrar = EstadoTramite.PENDIENTE; Integer nroClienteAFiltrar = 123; Integer idTipoTramiteAFiltrar = 1; String sectorInicioIdAFiltrar = "sector"; for(Tramite tramite : listaTramites) { if (tramite.getEstado() == estadoAFiltrar && tramite.getNroClienteEmpresa() == nroClienteAFiltrar && tramite.getTipoTramite().getId() == idTipoTramiteAFiltrar && tramite.getSectorInicio().getId().getSector().equals(sectorInicioIdAFiltrar)) tramitesFiltrados.add(tramite); } Mockito.when(tramiteRepository.findByNroClienteEmpresaAndEstadoAndTipoTramiteIdAndSectorInicioId(nroClienteAFiltrar,estadoAFiltrar,idTipoTramiteAFiltrar,sectorInicioIdAFiltrar)).thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.listByEmpresaEstadoAndTipoTramiteAndSectorInicio(nroClienteAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, sectorInicioIdAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testListByEmpresaEstadoAndTipoTramiteAndSectorInicioVacio() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); EstadoTramite estadoAFiltrar = null; Integer nroClienteAFiltrar = 123; Integer idTipoTramiteAFiltrar = 1; String sectorInicioIdAFiltrar = "sector"; Mockito.when(tramiteRepository.findByNroClienteEmpresaAndEstadoAndTipoTramiteIdAndSectorInicioId(nroClienteAFiltrar,estadoAFiltrar,idTipoTramiteAFiltrar,sectorInicioIdAFiltrar)).thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.listByEmpresaEstadoAndTipoTramiteAndSectorInicio(nroClienteAFiltrar, null, idTipoTramiteAFiltrar, sectorInicioIdAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testListByCuitEmpresaEstadoAndTipoTramiteAndSectorInicio() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); EstadoTramite estadoAFiltrar = EstadoTramite.PENDIENTE; String cuitEmpresaAFiltrar = "123"; Integer idTipoTramiteAFiltrar = 1; String sectorInicioIdAFiltrar = "sector"; for(Tramite tramite : listaTramites) { if (tramite.getEstado() == estadoAFiltrar && tramite.getCuitEmpresa() == cuitEmpresaAFiltrar && tramite.getTipoTramite().getId() == idTipoTramiteAFiltrar && tramite.getSectorInicio().getId().getSector().equals(sectorInicioIdAFiltrar)) tramitesFiltrados.add(tramite); } Mockito.when(tramiteRepository.findByCuitEmpresaAndEstadoAndTipoTramiteIdAndSectorInicioId(cuitEmpresaAFiltrar,estadoAFiltrar,idTipoTramiteAFiltrar,sectorInicioIdAFiltrar)).thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.listByCuitEmpresaEstadoAndTipoTramiteAndSectorInicio(cuitEmpresaAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, sectorInicioIdAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testListByCuitEmpresaEstadoAndTipoTramiteAndSectorInicioVacio() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); EstadoTramite estadoAFiltrar = null; String cuitEmpresaAFiltrar = "123"; Integer idTipoTramiteAFiltrar = 1; String sectorInicioIdAFiltrar = "sector"; Mockito.when(tramiteRepository.findByCuitEmpresaAndEstadoAndTipoTramiteIdAndSectorInicioId(cuitEmpresaAFiltrar,estadoAFiltrar,idTipoTramiteAFiltrar,sectorInicioIdAFiltrar)).thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.listByCuitEmpresaEstadoAndTipoTramiteAndSectorInicio(cuitEmpresaAFiltrar, null, idTipoTramiteAFiltrar, sectorInicioIdAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testFindById() { Integer idAFiltrar = 1; Tramite tramiteFiltrado = null; for (Tramite tramite : listaTramites) { if (tramite.getId() == idAFiltrar) tramiteFiltrado = tramite; } Mockito.when(tramiteRepository.findById(idAFiltrar)).thenReturn(Optional.of(tramiteFiltrado)); Tramite tramiteRecibido = tramiteService.getById(idAFiltrar); Assert.assertEquals(tramiteFiltrado, tramiteRecibido); } @Test public void testSave() { Tramite tramiteAGuardar = listaTramites.get(0); tramiteService.save(tramiteAGuardar); ArgumentCaptor<Tramite> argumentCaptor = ArgumentCaptor.forClass(Tramite.class); Mockito.verify(tramiteRepository).save(argumentCaptor.capture()); Assert.assertEquals(tramiteAGuardar, argumentCaptor.getValue()); } @Test public void testDelete() { Integer idABorrar = listaTramites.get(0).getId(); tramiteService.delete(idABorrar); ArgumentCaptor<Integer> argumentCaptor = ArgumentCaptor.forClass(Integer.class); Mockito.verify(tramiteRepository).deleteById(argumentCaptor.capture()); Assert.assertEquals(idABorrar, argumentCaptor.getValue()); } @Test public void testBuscarTramites() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); String cuitAFiltrar = "123"; EstadoTramite estadoAFiltrar = EstadoTramite.PENDIENTE; Integer idTipoTramiteAFiltrar = 1; String idSectorAFiltrar = "sector"; String DniAutorizadoAFiltrar = "123123"; String tipoDocAutorizadoAFiltrar = "DNI"; for (Tramite tramite : listaTramites) { if (tramite.getEstado() == estadoAFiltrar && tramite.getCuitEmpresa() == cuitAFiltrar && tramite.getTipoTramite().getId() == idTipoTramiteAFiltrar && tramite.getSectorInicio().getId().getSector().equals(idSectorAFiltrar) && !(tramite.getAutorizado().stream().filter(autorizado -> autorizado.getAutorizado().getTipoDocumento().equals(tipoDocAutorizadoAFiltrar) && autorizado.getAutorizado().getNroDocumento().equals(DniAutorizadoAFiltrar)).collect(Collectors.toSet()).isEmpty())) tramitesFiltrados.add(tramite); } Mockito.when(tramiteRepository.findByCuitAndEstadoAndTipoTramiteIdAndSectorInicioId(cuitAFiltrar, estadoAFiltrar, idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar)) .thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.buscarTramites(cuitAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testBuscarTramitesSinEstado() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); String cuitAFiltrar = "123"; EstadoTramite estadoAFiltrar = null; Integer idTipoTramiteAFiltrar = 1; String idSectorAFiltrar = "sector"; String DniAutorizadoAFiltrar = "123123"; String tipoDocAutorizadoAFiltrar = "DNI"; Mockito.when(tramiteRepository.findByCuitAndEstadoAndTipoTramiteIdAndSectorInicioId(cuitAFiltrar, estadoAFiltrar, idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar)) .thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.buscarTramites(cuitAFiltrar, null, idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar); Assert.assertEquals(tramitesFiltrados, tramitesRecibidos); } @Test public void testBuscarTramitesAACC() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); List<Tramite> tramitesFiltrados2 = new ArrayList<Tramite>(); String cuitAFiltrar = "123"; EstadoTramite estadoAFiltrar = EstadoTramite.PENDIENTE; Integer idTipoTramiteAFiltrar = 1; String idSectorAFiltrar = "sector"; String DniAutorizadoAFiltrar = "123123"; String tipoDocAutorizadoAFiltrar = "DNI"; String usuario = "usuario1"; for (Tramite tramite : listaTramites) { if ((tramite.getEstado() == estadoAFiltrar || tramite.getEstado() == EstadoTramite.FINALIZADO || tramite.getEstado() == EstadoTramite.GESTION) && tramite.getCuitEmpresa() == cuitAFiltrar && tramite.getTipoTramite().getId() == idTipoTramiteAFiltrar && tramite.getSectorInicio().getId().getSector().equals(idSectorAFiltrar) && !(tramite.getAutorizado().stream().filter(autorizado -> autorizado.getAutorizado().getTipoDocumento().equals(tipoDocAutorizadoAFiltrar) && autorizado.getAutorizado().getNroDocumento().equals(DniAutorizadoAFiltrar)).collect(Collectors.toSet()).isEmpty())) tramitesFiltrados.add(tramite); } tramitesFiltrados.add(listaTramites.get(15)); tramitesFiltrados2 = tramitesFiltrados.stream() .filter(tramite -> (EstadoTramite.PENDIENTE.equals(tramite.getEstado()) || EstadoTramite.FINALIZADO.equals(tramite.getEstado()) || EstadoTramite.GESTION.equals(tramite.getEstado())) && (usuario.equals(tramite.getUsuModif()) || null == tramite.getUsuModif())) .collect(Collectors.toList()); Mockito.when(tramiteService.buscarTramites(cuitAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar)) .thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.buscarTramites(usuario, cuitAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar); Assert.assertEquals(tramitesFiltrados2, tramitesRecibidos); } @Test public void testBuscarTramitesAACCUsuarioFNC() { List<Tramite> tramitesFiltrados = new ArrayList<Tramite>(); List<Tramite> tramitesFiltrados2 = new ArrayList<Tramite>(); String cuitAFiltrar = "123"; EstadoTramite estadoAFiltrar = EstadoTramite.PENDIENTE; Integer idTipoTramiteAFiltrar = 1; String idSectorAFiltrar = "sector"; String DniAutorizadoAFiltrar = "123123"; String tipoDocAutorizadoAFiltrar = "DNI"; String usuario = "FNC"; for (Tramite tramite : listaTramites) { if ((tramite.getEstado() == estadoAFiltrar || tramite.getEstado() == EstadoTramite.FINALIZADO || tramite.getEstado() == EstadoTramite.GESTION) && tramite.getCuitEmpresa() == cuitAFiltrar && tramite.getTipoTramite().getId() == idTipoTramiteAFiltrar && tramite.getSectorInicio().getId().getSector().equals(idSectorAFiltrar) && !(tramite.getAutorizado().stream().filter(autorizado -> autorizado.getAutorizado().getTipoDocumento().equals(tipoDocAutorizadoAFiltrar) && autorizado.getAutorizado().getNroDocumento().equals(DniAutorizadoAFiltrar)).collect(Collectors.toSet()).isEmpty())) tramitesFiltrados.add(tramite); } tramitesFiltrados.add(listaTramites.get(15)); tramitesFiltrados2 = tramitesFiltrados.stream() .filter(tramite -> (EstadoTramite.PENDIENTE.equals(tramite.getEstado()) || EstadoTramite.FINALIZADO.equals(tramite.getEstado()) || EstadoTramite.GESTION.equals(tramite.getEstado()))) .collect(Collectors.toList()); Mockito.when(tramiteService.buscarTramites(cuitAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar)) .thenReturn(tramitesFiltrados); List<Tramite> tramitesRecibidos = tramiteService.buscarTramites(usuario, cuitAFiltrar, estadoAFiltrar.toString(), idTipoTramiteAFiltrar, idSectorAFiltrar, DniAutorizadoAFiltrar, tipoDocAutorizadoAFiltrar); Assert.assertEquals(tramitesFiltrados2, tramitesRecibidos); } }
benrobson/Website
db/migrate/20160928231835_add_hidden_to_objectives.rb
class AddHiddenToObjectives < ActiveRecord::Migration[5.1] def change add_column :objectives, :hidden, :boolean, :default => false end end
pcsanwald/kibana
x-pack/plugins/canvas/public/components/loading/__tests__/loading.js
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import React from 'react'; import expect from 'expect.js'; import { shallow } from 'enzyme'; import { EuiLoadingSpinner, EuiIcon } from '@elastic/eui'; import { Loading } from '../loading'; describe('<Loading />', () => { it('uses EuiIcon by default', () => { const wrapper = shallow(<Loading />); expect(wrapper.contains(<EuiIcon />)).to.be.ok; expect(wrapper.contains(<EuiLoadingSpinner />)).to.not.be.ok; }); it('uses EuiLoadingSpinner when animating', () => { const wrapper = shallow(<Loading animated />); expect(wrapper.contains(<EuiIcon />)).to.not.be.ok; expect(wrapper.contains(<EuiLoadingSpinner />)).to.be.ok; }); });
khromiumos/chromiumos-chromite
api/gen/test_platform/common/task_pb2.py
<reponame>khromiumos/chromiumos-chromite # Generated by the protocol buffer compiler. DO NOT EDIT! # source: test_platform/common/task.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='test_platform/common/task.proto', package='test_platform.common', syntax='proto3', serialized_options=_b('Z>go.chromium.org/chromiumos/infra/proto/go/test_platform/common'), serialized_pb=_b('\n\x1ftest_platform/common/task.proto\x12\x14test_platform.common\"4\n\x0bTaskLogData\x12\x0e\n\x06gs_url\x18\x01 \x01(\t\x12\x15\n\rstainless_url\x18\x02 \x01(\tB@Z>go.chromium.org/chromiumos/infra/proto/go/test_platform/commonb\x06proto3') ) _TASKLOGDATA = _descriptor.Descriptor( name='TaskLogData', full_name='test_platform.common.TaskLogData', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='gs_url', full_name='test_platform.common.TaskLogData.gs_url', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='stainless_url', full_name='test_platform.common.TaskLogData.stainless_url', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=57, serialized_end=109, ) DESCRIPTOR.message_types_by_name['TaskLogData'] = _TASKLOGDATA _sym_db.RegisterFileDescriptor(DESCRIPTOR) TaskLogData = _reflection.GeneratedProtocolMessageType('TaskLogData', (_message.Message,), dict( DESCRIPTOR = _TASKLOGDATA, __module__ = 'test_platform.common.task_pb2' # @@protoc_insertion_point(class_scope:test_platform.common.TaskLogData) )) _sym_db.RegisterMessage(TaskLogData) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
blinkist/rack-oauth2
lib/rack/oauth2/server/abstract.rb
require 'rack/oauth2/server/abstract/handler' require 'rack/oauth2/server/abstract/request' require 'rack/oauth2/server/abstract/response' require 'rack/oauth2/server/abstract/error'
fossabot/hull-node
src/types/hull-object-attributes.js
/* @flow */ import type { THullUserAttributes, THullAccountAttributes } from "./"; /** * Object which is passed to `hullClient.asAccount().traits(traits: THullObjectAttributes)` call * @public * @memberof Types */ export type THullObjectAttributes = THullUserAttributes | THullAccountAttributes;
jaypipes/sqlb
pkg/schema/column.go
<filename>pkg/schema/column.go // // Use and distribution licensed under the Apache license version 2. // // See the COPYING file in the root project directory for full text. // package schema // Column describes a column in a Table type Column struct { Alias string Name string Table *Table }
NCTU-AUV/stm32_write_data_to_rpi
firmware/freertos/semaphore/lib/FreeRTOSV8.2.3/FreeRTOS/Demo/SuperH_SH7216_Renesas/RTOSDemo/intprg.c
<gh_stars>100-1000 /***********************************************************************/ /* */ /* FILE :intprg.c */ /* DATE :Sun, Dec 27, 2009 */ /* DESCRIPTION :Interrupt Program */ /* CPU TYPE :Other */ /* */ /* This file is generated by Renesas Project Generator (Ver.4.16). */ /* */ /***********************************************************************/ #include <machine.h> #include "vect.h" #pragma section IntPRG // 4 Illegal code void INT_Illegal_code(void){for( ;; ); /* sleep(); */} // 5 Reserved // 6 Illegal slot void INT_Illegal_slot(void){for( ;; ); /* sleep(); */} // 7 Reserved // 8 Reserved // 9 CPU Address error void INT_CPU_Address(void){for( ;; ); /* sleep(); */} // 10 DMAC Address error void INT_DMAC_Address(void){for( ;; ); /* sleep(); */} // 11 NMI void INT_NMI(void){for( ;; ); /* sleep(); */} // 12 User breakpoint trap void INT_User_Break(void){for( ;; ); /* sleep(); */} // 13 Reserved // 14 H-UDI void INT_HUDI(void){for( ;; ); /* sleep(); */} // 15 Register bank over void INT_Bank_Overflow(void){for( ;; ); /* sleep(); */} // 16 Register bank under void INT_Bank_Underflow(void){for( ;; ); /* sleep(); */} // 17 ZERO DIV void INT_Divide_by_Zero(void){for( ;; ); /* sleep(); */} // 18 OVER DIV void INT_Divide_Overflow(void){for( ;; ); /* sleep(); */} // 19 Reserved // 20 Reserved // 21 Reserved // 22 Reserved // 23 Reserved // 24 Reserved // 25 Reserved // 26 Reserved // 27 Reserved // 28 Reserved // 29 Reserved // 30 Reserved // 31 Reserved // 32 TRAPA (User Vecter) void INT_TRAPA32(void){ for( ;; ); /* sleep(); */ } // 33 TRAPA (User Vecter) void INT_TRAPA33(void){for( ;; ); /* sleep(); */} // 34 TRAPA (User Vecter) void INT_TRAPA34(void){for( ;; ); /* sleep(); */} // 35 TRAPA (User Vecter) void INT_TRAPA35(void){for( ;; ); /* sleep(); */} // 36 TRAPA (User Vecter) void INT_TRAPA36(void){for( ;; ); /* sleep(); */} // 37 TRAPA (User Vecter) void INT_TRAPA37(void){for( ;; ); /* sleep(); */} // 38 TRAPA (User Vecter) void INT_TRAPA38(void){for( ;; ); /* sleep(); */} // 39 TRAPA (User Vecter) void INT_TRAPA39(void){for( ;; ); /* sleep(); */} // 40 TRAPA (User Vecter) void INT_TRAPA40(void){for( ;; ); /* sleep(); */} // 41 TRAPA (User Vecter) void INT_TRAPA41(void){for( ;; ); /* sleep(); */} // 42 TRAPA (User Vecter) void INT_TRAPA42(void){for( ;; ); /* sleep(); */} // 43 TRAPA (User Vecter) void INT_TRAPA43(void){for( ;; ); /* sleep(); */} // 44 TRAPA (User Vecter) void INT_TRAPA44(void){for( ;; ); /* sleep(); */} // 45 TRAPA (User Vecter) void INT_TRAPA45(void){for( ;; ); /* sleep(); */} // 46 TRAPA (User Vecter) void INT_TRAPA46(void){for( ;; ); /* sleep(); */} // 47 TRAPA (User Vecter) void INT_TRAPA47(void){for( ;; ); /* sleep(); */} // 48 TRAPA (User Vecter) void INT_TRAPA48(void){for( ;; ); /* sleep(); */} // 49 TRAPA (User Vecter) void INT_TRAPA49(void){for( ;; ); /* sleep(); */} // 50 TRAPA (User Vecter) void INT_TRAPA50(void){for( ;; ); /* sleep(); */} // 51 TRAPA (User Vecter) void INT_TRAPA51(void){for( ;; ); /* sleep(); */} // 52 TRAPA (User Vecter) void INT_TRAPA52(void){for( ;; ); /* sleep(); */} // 53 TRAPA (User Vecter) void INT_TRAPA53(void){for( ;; ); /* sleep(); */} // 54 TRAPA (User Vecter) void INT_TRAPA54(void){for( ;; ); /* sleep(); */} // 55 TRAPA (User Vecter) void INT_TRAPA55(void){for( ;; ); /* sleep(); */} // 56 TRAPA (User Vecter) void INT_TRAPA56(void){for( ;; ); /* sleep(); */} // 57 TRAPA (User Vecter) void INT_TRAPA57(void){for( ;; ); /* sleep(); */} // 58 TRAPA (User Vecter) void INT_TRAPA58(void){for( ;; ); /* sleep(); */} // 59 TRAPA (User Vecter) void INT_TRAPA59(void){for( ;; ); /* sleep(); */} // 60 TRAPA (User Vecter) void INT_TRAPA60(void){for( ;; ); /* sleep(); */} // 61 TRAPA (User Vecter) void INT_TRAPA61(void){for( ;; ); /* sleep(); */} // 62 TRAPA (User Vecter) void INT_TRAPA62(void){for( ;; ); /* sleep(); */} // 63 TRAPA (User Vecter) void INT_TRAPA63(void){for( ;; ); /* sleep(); */} // 64 Interrupt IRQ0 void INT_IRQ0(void){for( ;; ); /* sleep(); */} // 65 Interrupt IRQ1 void INT_IRQ1(void){for( ;; ); /* sleep(); */} // 66 Interrupt IRQ2 void INT_IRQ2(void){for( ;; ); /* sleep(); */} // 67 Interrupt IRQ3 void INT_IRQ3(void){for( ;; ); /* sleep(); */} // 68 Interrupt IRQ4 void INT_IRQ4(void){for( ;; ); /* sleep(); */} // 69 Interrupt IRQ5 void INT_IRQ5(void){for( ;; ); /* sleep(); */} // 70 Interrupt IRQ6 void INT_IRQ6(void){for( ;; ); /* sleep(); */} // 71 Interrupt IRQ7 void INT_IRQ7(void){for( ;; ); /* sleep(); */} // 72 Reserved // 73 Reserved // 74 Reserved // 75 Reserved // 76 Reserved // 77 Reserved // 78 Reserved // 79 Reserved // 80 Interrupt PINT0 void INT_PINT0(void){for( ;; ); /* sleep(); */} // 81 Interrupt PINT1 void INT_PINT1(void){for( ;; ); /* sleep(); */} // 82 Interrupt PINT2 void INT_PINT2(void){for( ;; ); /* sleep(); */} // 83 Interrupt PINT3 void INT_PINT3(void){for( ;; ); /* sleep(); */} // 84 Interrupt PINT4 void INT_PINT4(void){for( ;; ); /* sleep(); */} // 85 Interrupt PINT5 void INT_PINT5(void){for( ;; ); /* sleep(); */} // 86 Interrupt PINT6 void INT_PINT6(void){for( ;; ); /* sleep(); */} // 87 Interrupt PINT7 void INT_PINT7(void){for( ;; ); /* sleep(); */} // 88 Reserved // 89 Reserved // 90 Reserved // 91 ROM FIFE void INT_ROM_FIFE(void){for( ;; ); /* sleep(); */} // 92 A/D ADI0 void INT_AD_ADI0(void){for( ;; ); /* sleep(); */} // 93 Reserved // 94 Reserved // 95 Reserved // 96 A/D ADI1 void INT_AD_ADI1(void){for( ;; ); /* sleep(); */} // 97 Reserved // 98 Reserved // 99 Reserved // 100 Reserved // 101 Reserved // 102 Reserved // 103 Reserved // 104 RCANET0 ERS_0 void INT_RCANET0_ERS_0(void){for( ;; ); /* sleep(); */} // 105 RCANET0 OVR_0 void INT_RCANET0_OVR_0(void){for( ;; ); /* sleep(); */} // 106 RCANET0 RM01_0 void INT_RCANET0_RM01_0(void){for( ;; ); /* sleep(); */} // 107 RCANET0 SLE_0 void INT_RCANET0_SLE_0(void){for( ;; ); /* sleep(); */} // 108 DMAC0 DEI0 void INT_DMAC0_DEI0(void){for( ;; ); /* sleep(); */} // 109 DMAC0 HEI0 void INT_DMAC0_HEI0(void){for( ;; ); /* sleep(); */} // 110 Reserved // 111 Reserved // 112 DMAC1 DEI1 void INT_DMAC1_DEI1(void){for( ;; ); /* sleep(); */} // 113 DMAC1 HEI1 void INT_DMAC1_HEI1(void){for( ;; ); /* sleep(); */} // 114 Reserved // 115 Reserved // 116 DMAC2 DEI2 void INT_DMAC2_DEI2(void){for( ;; ); /* sleep(); */} // 117 DMAC2 HEI2 void INT_DMAC2_HEI2(void){for( ;; ); /* sleep(); */} // 118 Reserved // 119 Reserved // 120 DMAC3 DEI3 void INT_DMAC3_DEI3(void){for( ;; ); /* sleep(); */} // 121 DMAC3 HEI3 void INT_DMAC3_HEI3(void){for( ;; ); /* sleep(); */} // 122 Reserved // 123 Reserved // 124 DMAC4 DEI4 void INT_DMAC4_DEI4(void){for( ;; ); /* sleep(); */} // 125 DMAC4 HEI4 void INT_DMAC4_HEI4(void){for( ;; ); /* sleep(); */} // 126 Reserved // 127 Reserved // 128 DMAC5 DEI5 void INT_DMAC5_DEI5(void){for( ;; ); /* sleep(); */} // 129 DMAC5 HEI5 void INT_DMAC5_HEI5(void){for( ;; ); /* sleep(); */} // 130 Reserved // 131 Reserved // 132 DMAC6 DEI6 void INT_DMAC6_DEI6(void){for( ;; ); /* sleep(); */} // 133 DMAC6 HEI6 void INT_DMAC6_HEI6(void){for( ;; ); /* sleep(); */} // 134 Reserved // 135 Reserved // 136 DMAC7 DEI7 void INT_DMAC7_DEI7(void){for( ;; ); /* sleep(); */} // 137 DMAC7 HEI7 void INT_DMAC7_HEI7(void){for( ;; ); /* sleep(); */} // 138 Reserved // 139 Reserved // 140 CMT CMI0 //void INT_CMT_CMI0(void){for( ;; ); /* sleep(); */} // 141 Reserved // 142 Reserved // 143 Reserved // 144 CMT CMI1 void INT_CMT_CMI1(void){for( ;; ); /* sleep(); */} // 145 Reserved // 146 Reserved // 147 Reserved // 148 BSC CMTI void INT_BSC_CMTI(void){for( ;; ); /* sleep(); */} // 149 Reserved // 150 USB EP4FULL void INT_USB_EP4FULL(void){for( ;; ); /* sleep(); */} // 151 USB EP5EMPTY void INT_USB_EP5EMPTY(void){for( ;; ); /* sleep(); */} // 152 WDT ITI void INT_WDT_ITI(void){for( ;; ); /* sleep(); */} // 153 E-DMAC EINT0 void INT_EDMAC_EINT0(void){for( ;; ); /* sleep(); */} // 154 USB EP1FULL void INT_USB_EP1FULL(void){for( ;; ); /* sleep(); */} // 155 USB EP2EMPTY void INT_USB_EP2EMPTY(void){for( ;; ); /* sleep(); */} // 156 MTU2 MTU0 TGI0A void INT_MTU2_MTU0_TGI0A(void){for( ;; ); /* sleep(); */} // 157 MTU2 MTU0 TGI0B void INT_MTU2_MTU0_TGI0B(void){for( ;; ); /* sleep(); */} // 158 MTU2 MTU0 TGI0C void INT_MTU2_MTU0_TGI0C(void){for( ;; ); /* sleep(); */} // 159 MTU2 MTU0 TGI0D void INT_MTU2_MTU0_TGI0D(void){for( ;; ); /* sleep(); */} // 160 MTU2 MTU0 TGI0V void INT_MTU2_MTU0_TGI0V(void){for( ;; ); /* sleep(); */} // 161 MTU2 MTU0 TGI0E void INT_MTU2_MTU0_TGI0E(void){for( ;; ); /* sleep(); */} // 162 MTU2 MTU0 TGI0F void INT_MTU2_MTU0_TGI0F(void){for( ;; ); /* sleep(); */} // 163 Reserved // 164 MTU2 MTU1 TGI1A void INT_MTU2_MTU1_TGI1A(void){for( ;; ); /* sleep(); */} // 165 MTU2 MTU1 TGI1B void INT_MTU2_MTU1_TGI1B(void){for( ;; ); /* sleep(); */} // 166 Reserved // 167 Reserved // 168 MTU2 MTU1 TGI1V void INT_MTU2_MTU1_TGI1V(void){for( ;; ); /* sleep(); */} // 169 MTU2 MTU1 TGI1U void INT_MTU2_MTU1_TGI1U(void){for( ;; ); /* sleep(); */} // 170 Reserved // 171 Reserved // 172 MTU2 MTU2 TGI2A void INT_MTU2_MTU2_TGI2A(void){for( ;; ); /* sleep(); */} // 173 MTU2 MTU2 TGI2B void INT_MTU2_MTU2_TGI2B(void){for( ;; ); /* sleep(); */} // 174 Reserved // 175 Reserved // 176 MTU2 MTU2 TGI2V void INT_MTU2_MTU2_TGI2V(void){for( ;; ); /* sleep(); */} // 177 MTU2 MTU2 TGI2U void INT_MTU2_MTU2_TGI2U(void){for( ;; ); /* sleep(); */} // 178 Reserved // 179 Reserved // 180 MTU2 MTU3 TGI3A void INT_MTU2_MTU3_TGI3A(void){for( ;; ); /* sleep(); */} // 181 MTU2 MTU3 TGI3B void INT_MTU2_MTU3_TGI3B(void){for( ;; ); /* sleep(); */} // 182 MTU2 MTU3 TGI3C void INT_MTU2_MTU3_TGI3C(void){for( ;; ); /* sleep(); */} // 183 MTU2 MTU3 TGI3D void INT_MTU2_MTU3_TGI3D(void){for( ;; ); /* sleep(); */} // 184 MTU2 MTU3 TGI3V void INT_MTU2_MTU3_TGI3V(void){for( ;; ); /* sleep(); */} // 185 Reserved // 186 Reserved // 187 Reserved // 188 MTU2 MTU4 TGI4A void INT_MTU2_MTU4_TGI4A(void){for( ;; ); /* sleep(); */} // 189 MTU2 MTU4 TGI4B void INT_MTU2_MTU4_TGI4B(void){for( ;; ); /* sleep(); */} // 190 MTU2 MTU4 TGI4C void INT_MTU2_MTU4_TGI4C(void){for( ;; ); /* sleep(); */} // 191 MTU2 MTU4 TGI4D void INT_MTU2_MTU4_TGI4D(void){for( ;; ); /* sleep(); */} // 192 MTU2 MTU4 TGI4V void INT_MTU2_MTU4_TGI4V(void){for( ;; ); /* sleep(); */} // 193 Reserved // 194 Reserved // 195 Reserved // 196 MTU2 MTU5 TGI5U void INT_MTU2_MTU5_TGI5U(void){for( ;; ); /* sleep(); */} // 197 MTU2 MTU5 TGI5V void INT_MTU2_MTU5_TGI5V(void){for( ;; ); /* sleep(); */} // 198 MTU2 MTU5 TGI5W void INT_MTU2_MTU5_TGI5W(void){for( ;; ); /* sleep(); */} // 199 Reserved // 200 POE2 OEI1 void INT_POE2_OEI1(void){for( ;; ); /* sleep(); */} // 201 POE2 OEI2 void INT_POE2_OEI2(void){for( ;; ); /* sleep(); */} // 202 Reserved // 203 Reserved // 204 MTU2S MTU3S TGI3A void INT_MTU2S_MTU3S_TGI3A(void){for( ;; ); /* sleep(); */} // 205 MTU2S MTU3S TGI3B void INT_MTU2S_MTU3S_TGI3B(void){for( ;; ); /* sleep(); */} // 206 MTU2S MTU3S TGI3C void INT_MTU2S_MTU3S_TGI3C(void){for( ;; ); /* sleep(); */} // 207 MTU2S MTU3S TGI3D void INT_MTU2S_MTU3S_TGI3D(void){for( ;; ); /* sleep(); */} // 208 MTU2S MTU3S TGI3V void INT_MTU2S_MTU3S_TGI3V(void){for( ;; ); /* sleep(); */} // 209 Reserved // 210 Reserved // 211 Reserved // 212 MTU2S MTU4S TGI4A void INT_MTU2S_MTU4S_TGI4A(void){for( ;; ); /* sleep(); */} // 213 MTU2S MTU4S TGI4B void INT_MTU2S_MTU4S_TGI4B(void){for( ;; ); /* sleep(); */} // 214 MTU2S MTU4S TGI4C void INT_MTU2S_MTU4S_TGI4C(void){for( ;; ); /* sleep(); */} // 215 MTU2S MTU4S TGI4D void INT_MTU2S_MTU4S_TGI4D(void){for( ;; ); /* sleep(); */} // 216 MTU2S MTU4S TGI4V void INT_MTU2S_MTU4S_TGI4V(void){for( ;; ); /* sleep(); */} // 217 Reserved // 218 Reserved // 219 Reserved // 220 MTU2S MTU5S TGI5U void INT_MTU2S_MTU5S_TGI5U(void){for( ;; ); /* sleep(); */} // 221 MTU2S MTU5S TGI5V void INT_MTU2S_MTU5S_TGI5V(void){for( ;; ); /* sleep(); */} // 222 MTU2S MTU5S TGI5W void INT_MTU2S_MTU5S_TGI5W(void){for( ;; ); /* sleep(); */} // 223 Reserved // 224 POE2 OEI3 void INT_POE2_OEI3(void){for( ;; ); /* sleep(); */} // 225 Reserved // 226 USB USI0 void INT_USB_USI0(void){for( ;; ); /* sleep(); */} // 227 USB USI1 void INT_USB_USI1(void){for( ;; ); /* sleep(); */} // 228 IIC3 STPI void INT_IIC3_STPI(void){for( ;; ); /* sleep(); */} // 229 IIC3 NAKI void INT_IIC3_NAKI(void){for( ;; ); /* sleep(); */} // 230 IIC3 RXI void INT_IIC3_RXI(void){for( ;; ); /* sleep(); */} // 231 IIC3 TXI void INT_IIC3_TXI(void){for( ;; ); /* sleep(); */} // 232 IIC3 TEI void INT_IIC3_TEI(void){for( ;; ); /* sleep(); */} // 233 RSPI SPERI void INT_RSPI_SPERI(void){for( ;; ); /* sleep(); */} // 234 RSPI SPRXI void INT_RSPI_SPRXI(void){for( ;; ); /* sleep(); */} // 235 RSPI SPTXI void INT_RSPI_SPTXI(void){for( ;; ); /* sleep(); */} // 236 SCI SCI4 ERI4 void INT_SCI_SCI4_ERI4(void){for( ;; ); /* sleep(); */} // 237 SCI SCI4 RXI4 void INT_SCI_SCI4_RXI4(void){for( ;; ); /* sleep(); */} // 238 SCI SCI4 TXI4 void INT_SCI_SCI4_TXI4(void){for( ;; ); /* sleep(); */} // 239 SCI SCI4 TEI4 void INT_SCI_SCI4_TEI4(void){for( ;; ); /* sleep(); */} // 240 SCI SCI0 ERI0 void INT_SCI_SCI0_ERI0(void){for( ;; ); /* sleep(); */} // 241 SCI SCI0 RXI0 void INT_SCI_SCI0_RXI0(void){for( ;; ); /* sleep(); */} // 242 SCI SCI0 TXI0 void INT_SCI_SCI0_TXI0(void){for( ;; ); /* sleep(); */} // 243 SCI SCI0 TEI0 void INT_SCI_SCI0_TEI0(void){for( ;; ); /* sleep(); */} // 244 SCI SCI1 ERI1 void INT_SCI_SCI1_ERI1(void){for( ;; ); /* sleep(); */} // 245 SCI SCI1 RXI1 void INT_SCI_SCI1_RXI1(void){for( ;; ); /* sleep(); */} // 246 SCI SCI1 TXI1 void INT_SCI_SCI1_TXI1(void){for( ;; ); /* sleep(); */} // 247 SCI SCI1 TEI1 void INT_SCI_SCI1_TEI1(void){for( ;; ); /* sleep(); */} // 248 SCI SCI2 ERI2 void INT_SCI_SCI2_ERI2(void){for( ;; ); /* sleep(); */} // 249 SCI SCI2 RXI2 void INT_SCI_SCI2_RXI2(void){for( ;; ); /* sleep(); */} // 250 SCI SCI2 TXI2 void INT_SCI_SCI2_TXI2(void){for( ;; ); /* sleep(); */} // 251 SCI SCI2 TEI2 void INT_SCI_SCI2_TEI2(void){for( ;; ); /* sleep(); */} // 252 SCIF SCIF3 BRI3 void INT_SCIF_SCIF3_BRI3(void){for( ;; ); /* sleep(); */} // 253 SCIF SCIF3 ERI3 void INT_SCIF_SCIF3_ERI3(void){for( ;; ); /* sleep(); */} // 254 SCIF SCIF3 RXI3 void INT_SCIF_SCIF3_RXI3(void){for( ;; ); /* sleep(); */} // 255 SCIF SCIF3 TXI3 void INT_SCIF_SCIF3_TXI3(void){for( ;; ); /* sleep(); */} // Dummy void Dummy(void){ for( ;; ); sleep(); } /* End of File */
red61/webstart
webstart-maven-plugin/src/main/java/org/codehaus/mojo/webstart/AbstractBaseJnlpMojo.java
package org.codehaus.mojo.webstart; /* * 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. */ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.mojo.webstart.dependency.filenaming.DependencyFilenameStrategy; import org.codehaus.mojo.webstart.pack200.Pack200Config; import org.codehaus.mojo.webstart.pack200.Pack200Tool; import org.codehaus.mojo.webstart.sign.SignConfig; import org.codehaus.mojo.webstart.sign.SignTool; import org.codehaus.mojo.webstart.util.ArtifactUtil; import org.codehaus.mojo.webstart.util.IOUtil; import org.codehaus.mojo.webstart.util.JarUtil; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * The superclass for all JNLP generating MOJOs. * * @author <NAME> * @author $LastChangedBy$ * @version $Revision$ * @since 28 May 2007 */ public abstract class AbstractBaseJnlpMojo extends AbstractMojo { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String DEFAULT_RESOURCES_DIR = "src/main/jnlp/resources"; /** * unprocessed files (that will be signed) are prefixed with this */ private static final String UNPROCESSED_PREFIX = "unprocessed_"; /** * Suffix extension of a jar file. */ public static final String JAR_SUFFIX = ".jar"; // ---------------------------------------------------------------------- // Mojo Parameters // ---------------------------------------------------------------------- /** * Local repository. */ @Parameter( defaultValue = "${localRepository}", required = true, readonly = true ) private ArtifactRepository localRepository; /** * The collection of remote artifact repositories. */ @Parameter( defaultValue = "${project.remoteArtifactRepositories}", required = true, readonly = true ) private List<ArtifactRepository> remoteRepositories; /** * The directory in which files will be stored prior to processing. */ @Parameter( property = "jnlp.workDirectory", defaultValue = "${project.build.directory}/jnlp", required = true ) private File workDirectory; /** * The path where the libraries are placed within the jnlp structure. */ @Parameter( property = "jnlp.libPath", defaultValue = "" ) protected String libPath; /** * The location of the directory (relative or absolute) containing non-jar resources that * are to be included in the JNLP bundle. */ @Parameter( property = "jnlp.resourcesDirectory" ) private File resourcesDirectory; /** * The location where the JNLP Velocity template files are stored. */ @Parameter( property = "jnlp.templateDirectory", defaultValue = "${project.basedir}/src/main/jnlp", required = true ) private File templateDirectory; /** * The Pack200 Config. * * @since 1.0-beta-4 */ @Parameter private Pack200Config pack200; /** * The Sign Config. */ @Parameter private SignConfig sign; /** * Indicates whether or not gzip archives will be created for each of the jar * files included in the webstart bundle. */ @Parameter( property = "jnlp.gzip", defaultValue = "false" ) private boolean gzip; /** * Enable verbose output. */ @Parameter( property = "webstart.verbose", alias = "verbose", defaultValue = "false" ) private boolean verbose; /** * Set to true to exclude all transitive dependencies. * * @parameter */ @Parameter( property = "jnlp.excludeTransitive" ) private boolean excludeTransitive; /** * The code base to use on the generated jnlp files. * * @since 1.0-beta-2 */ @Parameter( property = "jnlp.codebase", defaultValue = "${project.url}/jnlp" ) private String codebase; /** * Encoding used to read and write jnlp files. * <p/> * <strong>Note:</strong> If this property is not defined, then will use a default value {@code utf-8}. * * @since 1.0-beta-2 */ @Parameter( property = "jnlp.encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * Define whether to remove existing signatures. */ @Parameter( property = "jnlp.unsign", alias = "unsign", defaultValue = "false" ) private boolean unsignAlreadySignedJars; /** * To authorize or not to unsign some already signed jar. * <p/> * If set to false and the {@code unsign} parameter is set to {@code true} then the build will fail if there is * a jar to unsign, to avoid this use then the extension jnlp component. * * @since 1.0-beta-2 */ @Parameter( property = "jnlp.canUnsign", defaultValue = "true" ) private boolean canUnsign; /** * To update manifest entries of all jar resources. * <p/> * Since jdk 1.7u45, you need to add some entries to be able to open jnlp files in High security level. * See http://www.oracle.com/technetwork/java/javase/7u45-relnotes-2016950.html * <p/> * <strong>Note:</strong> Won't affect any already signed jar resources if you configuration does not authorize it. * <p/> * Si parameters {@link #unsignAlreadySignedJars} and {@link #canUnsign}. * * @since 1.0-beta-4 */ @Parameter private Map<String, String> updateManifestEntries; /** * Compile class-path elements used to search for the keystore * (if kestore location was prefixed by {@code classpath:}). * * @since 1.0-beta-4 */ @Parameter( defaultValue = "${project.compileClasspathElements}", required = true, readonly = true ) private List<?> compileClassPath; /** * Naming strategy for dependencies of a jnlp application. * * The strategy purpose is to transform the name of the dependency file. * * The actual authorized values are: * <ul> * <li><strong>simple</strong>: artifactId[-classifier]-version.jar</li> * <li><strong>full</strong>: groupId-artifactId[-classifier]-version.jar</li> * </ul> * * Default value is {@code full} which avoid any colision of naming. * * @since 1.0-beta-5 */ @Parameter( property = "jnlp.filenameMapping", defaultValue = "simple", required = true) private String filenameMapping; /** * Use unique version for any snapshot dependency, or just use the {@code -SNAPSHOT} version suffix. * * @since 1.0-beta-7 */ @Parameter( property = "jnlp.useUniqueVersions", defaultValue = "false" ) private boolean useUniqueVersions; // ---------------------------------------------------------------------- // Components // ---------------------------------------------------------------------- /** * Sign tool. */ @Component private SignTool signTool; /** * All available pack200 tools. * <p/> * We use a plexus list injection instead of a direct component injection since for a jre 1.4, we will at the * moment have no implementation of this tool. * <p/> * Later in the execute of mojo, we will check if at least one implementation is available if required. * * @since 1.0-beta-2 */ @Component( role = Pack200Tool.class ) private Pack200Tool pack200Tool; /** * Artifact helper. * * @since 1.0-beta-4 */ @Component private ArtifactUtil artifactUtil; /** * io helper. * * @since 1.0-beta-4 */ @Component private IOUtil ioUtil; /** * Jar util. * * @since 1.0-beta-4 */ @Component( hint = "default" ) private JarUtil jarUtil; /** * All dependency filename strategy indexed by theire role-hint. * * @since 1.0-beta-5 */ @Component( role = DependencyFilenameStrategy.class ) private Map<String, DependencyFilenameStrategy> dependencyFilenameStrategyMap; // ---------------------------------------------------------------------- // Fields // ---------------------------------------------------------------------- /** * List of detected modified artifacts (will then re-apply stuff on them). */ private final List<String> modifiedJnlpArtifacts = new ArrayList<String>(); // the jars to sign and pack are selected if they are prefixed by UNPROCESSED_PREFIX. // as the plugin copies the new versions locally before signing/packing them // we just need to see if the plugin copied a new version // We achieve that by only filtering files modified after the plugin was started // Note: if other files (the pom, the keystore config) have changed, one needs to clean private final FileFilter unprocessedJarFileFilter; /** * Filter of processed jar files. */ private final FileFilter processedJarFileFilter; /** * Filter of jar files that need to be pack200. */ private final FileFilter unprocessedPack200FileFilter; /** * The dependency filename strategy. */ private DependencyFilenameStrategy dependencyFilenameStrategy; /** * Creates a new {@code AbstractBaseJnlpMojo}. */ public AbstractBaseJnlpMojo() { processedJarFileFilter = new FileFilter() { /** * {@inheritDoc} */ public boolean accept( File pathname ) { return pathname.isFile() && pathname.getName().endsWith( JAR_SUFFIX ) && !pathname.getName().startsWith( UNPROCESSED_PREFIX ); } }; unprocessedJarFileFilter = new FileFilter() { /** * {@inheritDoc} */ public boolean accept( File pathname ) { return pathname.isFile() && pathname.getName().startsWith( UNPROCESSED_PREFIX ) && pathname.getName().endsWith( JAR_SUFFIX ); } }; unprocessedPack200FileFilter = new FileFilter() { /** * {@inheritDoc} */ public boolean accept( File pathname ) { return pathname.isFile() && pathname.getName().startsWith( UNPROCESSED_PREFIX ) && ( pathname.getName().endsWith( JAR_SUFFIX + Pack200Tool.PACK_GZ_EXTENSION ) || pathname.getName().endsWith( JAR_SUFFIX + Pack200Tool.PACK_EXTENSION ) ); } }; } // ---------------------------------------------------------------------- // Public Methods // ---------------------------------------------------------------------- public abstract MavenProject getProject(); /** * Returns the library path. This is ths subpath within the working directory, where the libraries are placed. * If the path is not configured it is <code>null</code>. * * @return the library path or <code>null</code> if not configured. */ public String getLibPath() { if ( StringUtils.isBlank( libPath ) ) { return null; } return libPath; } /** * Returns the flag that indicates whether or not jar resources * will be compressed using pack200. * * @return Returns the value of the pack200.enabled field. */ public boolean isPack200() { return pack200 != null && pack200.isEnabled(); } /** * Returns the files to be passed without pack200 compression. * * @return Returns the list value of the pack200.passFiles. */ public List<String> getPack200PassFiles() { return pack200 == null ? null : pack200.getPassFiles(); } // ---------------------------------------------------------------------- // Protected Methods // ---------------------------------------------------------------------- /** * Returns the working directory. This is the directory in which files and resources * will be placed in order to be processed prior to packaging. * * @return Returns the value of the workDirectory field. */ protected File getWorkDirectory() { return workDirectory; } /** * Returns the library directory. If not libPath is configured, the working directory is returned. * * @return Returns the value of the libraryDirectory field. */ protected File getLibDirectory() { if ( getLibPath() != null ) { return new File( getWorkDirectory(), getLibPath() ); } return getWorkDirectory(); } /** * Returns the location of the directory containing * non-jar resources that are to be included in the JNLP bundle. * * @return Returns the value of the resourcesDirectory field, never null. */ protected File getResourcesDirectory() { if ( resourcesDirectory == null ) { resourcesDirectory = new File( getProject().getBasedir(), DEFAULT_RESOURCES_DIR ); } return resourcesDirectory; } /** * Returns the file handle to the directory containing the Velocity templates for the JNLP * files to be generated. * * @return Returns the value of the templateDirectory field. */ protected File getTemplateDirectory() { return templateDirectory; } /** * Returns the local artifact repository. * * @return Returns the value of the localRepository field. */ protected ArtifactRepository getLocalRepository() { return localRepository; } /** * Returns the collection of remote artifact repositories for the current * Maven project. * * @return Returns the value of the remoteRepositories field. */ protected List<ArtifactRepository> getRemoteRepositories() { return remoteRepositories; } /** * Returns jar signing configuration element. * * @return Returns the value of the sign field. */ protected SignConfig getSign() { return sign; } /** * Returns the code base to inject in the generated jnlp. * * @return Returns the value of codebase field. */ protected String getCodebase() { return codebase; } /** * Returns the flag that indicates whether or not a gzip should be * created for each jar resource. * * @return Returns the value of the gzip field. */ protected boolean isGzip() { return gzip; } /** * Returns the flag that indicates whether or not to provide verbose output. * * @return Returns the value of the verbose field. */ protected boolean isVerbose() { return verbose; } /** * Returns the flag that indicates whether or not all transitive dependencies will be excluded * from the generated JNLP bundle. * * @return Returns the value of the excludeTransitive field. */ protected boolean isExcludeTransitive() { return this.excludeTransitive; } /** * Returns the collection of artifacts that have been modified * since the last time this mojo was run. * * @return Returns the value of the modifiedJnlpArtifacts field. */ protected List<String> getModifiedJnlpArtifacts() { return modifiedJnlpArtifacts; } /** * @return the mojo encoding to use to write files. */ protected String getEncoding() { if ( StringUtils.isEmpty( encoding ) ) { encoding = "utf-8"; getLog().warn( "No encoding defined, will use the default one : " + encoding ); } return encoding; } protected DependencyFilenameStrategy getDependencyFilenameStrategy() { if ( dependencyFilenameStrategy == null ) { dependencyFilenameStrategy = dependencyFilenameStrategyMap.get(filenameMapping ); } return dependencyFilenameStrategy; } protected boolean isUseUniqueVersions() { return useUniqueVersions; } protected void checkDependencyFilenameStrategy() throws MojoExecutionException { if ( getDependencyFilenameStrategy() == null ) { dependencyFilenameStrategy = dependencyFilenameStrategyMap.get(filenameMapping ); if (dependencyFilenameStrategy==null) { throw new MojoExecutionException( "Could not find filenameMapping named '"+filenameMapping+"', use one of the following one: "+ dependencyFilenameStrategyMap.keySet()); } } } /** * Conditionally copy the jar file into the target directory. * The operation is not performed when a signed target file exists and is up to date. * The signed target file name is taken from the <code>sourceFile</code> name.E * The unsigned target file name is taken from the <code>sourceFile</code> name prefixed with UNPROCESSED_PREFIX. * TODO this is confusing if the sourceFile is already signed. By unsigned we really mean 'unsignedbyus' * * @param sourceFile source file to copy * @param targetDirectory location of the target directory where to copy file * @param targetFilename [optional] to change the target filename to use (if {@code null} will * use the sourceFile name). * @return <code>true</code> when the file was copied, <code>false</code> otherwise. * @throws IllegalArgumentException if sourceFile is <code>null</code> or * <code>sourceFile.getName()</code> is <code>null</code> * @throws MojoExecutionException if an error occurs attempting to copy the file. */ protected boolean copyJarAsUnprocessedToDirectoryIfNecessary( File sourceFile, File targetDirectory, String targetFilename ) throws MojoExecutionException { if ( sourceFile == null ) { throw new IllegalArgumentException( "sourceFile is null" ); } if ( targetFilename == null ) { targetFilename = sourceFile.getName(); } File signedTargetFile = new File( targetDirectory, targetFilename ); File unsignedTargetFile = toUnprocessFile( targetDirectory, targetFilename ); boolean shouldCopy = !signedTargetFile.exists() || ( signedTargetFile.lastModified() < sourceFile.lastModified() ); shouldCopy &= ( !unsignedTargetFile.exists() || ( unsignedTargetFile.lastModified() < sourceFile.lastModified() ) ); if ( shouldCopy ) { getIoUtil().copyFile( sourceFile, unsignedTargetFile ); } else { getLog().debug( "Source file hasn't changed. Do not reprocess " + signedTargetFile + " with " + sourceFile + "." ); } return shouldCopy; } /** * If sign is enabled, sign the jars, otherwise rename them into final jars * * @throws MojoExecutionException if can not sign or rename jars */ protected void signOrRenameJars() throws MojoExecutionException { if ( sign != null ) { try { ClassLoader loader = getCompileClassLoader(); sign.init( getWorkDirectory(), getLog().isDebugEnabled(), signTool, loader ); } catch ( MalformedURLException e ) { throw new MojoExecutionException( "Could not create classloader", e ); } if ( unsignAlreadySignedJars ) { removeExistingSignatures( getLibDirectory() ); } if ( isPack200() ) { //TODO tchemit use a temporary directory to pack-unpack // http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html // we need to pack then unpack the files before signing them unpackJars( getLibDirectory() ); // As out current Pack200 ant tasks don't give us the ability to use a temporary area for // creating those temporary packing, we have to delete the temporary files. ioUtil.deleteFiles( getLibDirectory(), unprocessedPack200FileFilter ); // specs says that one should do it twice when there are unsigned jars?? // Pack200.unpackJars( applicationDirectory, updatedPack200FileFilter ); } if ( MapUtils.isNotEmpty( updateManifestEntries ) ) { updateManifestEntries( getLibDirectory() ); } int signedJars = signJars( getLibDirectory() ); if ( signedJars != getModifiedJnlpArtifacts().size() ) { throw new IllegalStateException( "The number of signed artifacts (" + signedJars + ") differ from the number of modified " + "artifacts (" + getModifiedJnlpArtifacts().size() + "). Implementation error" ); } } else { makeUnprocessedFilesFinal( getLibDirectory() ); } if ( isPack200() ) { verboseLog( "-- Pack jars" ); pack200Jars( getLibDirectory(), processedJarFileFilter ); } } protected void pack200Jars( File directory, FileFilter filter ) throws MojoExecutionException { try { getPack200Tool().packJars( directory, filter, isGzip(), getPack200PassFiles() ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not pack200 jars: ", e ); } } protected URL findDefaultTemplateURL(JnlpFileType fileType) { return getClass().getClassLoader().getResource( fileType.getDefaultTemplateName() ); } /** * @return something of the form jar:file:..../webstart-maven-plugin-.....jar!/ */ protected String getWebstartJarURLForVelocity() { String url = findDefaultTemplateURL(JnlpFileType.application).toString(); return url.substring( 0, url.indexOf( "!" ) + 2 ); } protected boolean isJarSigned( File jarFile ) throws MojoExecutionException { return signTool.isJarSigned( jarFile ); } protected ArtifactUtil getArtifactUtil() { return artifactUtil; } protected IOUtil getIoUtil() { return ioUtil; } protected Pack200Tool getPack200Tool() { return pack200Tool; } /** * Log as info when verbose or info is enabled, as debug otherwise. * * @param msg the message to display */ protected void verboseLog( String msg ) { if ( isVerbose() ) { getLog().info( msg ); } else { getLog().debug( msg ); } } // ---------------------------------------------------------------------- // Private Methods // ---------------------------------------------------------------------- private void unpackJars( File directory ) throws MojoExecutionException { getLog().info( "-- Unpack jars before sign operation " ); verboseLog( "see http://docs.oracle.com/javase/7/docs/technotes/guides/deployment/deployment-guide/pack200.html" ); // pack pack200Jars( directory, unprocessedJarFileFilter ); // then unpack try { getPack200Tool().unpackJars( directory, unprocessedPack200FileFilter ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not unpack200 jars: ", e ); } } private int makeUnprocessedFilesFinal( File directory ) throws MojoExecutionException { File[] jarFiles = directory.listFiles( unprocessedJarFileFilter ); getLog().debug( "makeUnprocessedFilesFinal in " + directory + " found " + jarFiles.length + " file(s) to rename" ); if ( jarFiles.length == 0 ) { return 0; } for ( File unprocessedJarFile : jarFiles ) { File finalJar = toProcessFile( unprocessedJarFile ); ioUtil.deleteFile( finalJar ); ioUtil.renameTo( unprocessedJarFile, finalJar ); } return jarFiles.length; } /** * @param directory location of directory where to update manifest entries jars * @throws MojoExecutionException if can not update manifest entries jars */ private void updateManifestEntries( File directory ) throws MojoExecutionException { File[] jarFiles = directory.listFiles( unprocessedJarFileFilter ); getLog().info( "-- Update manifest entries" ); getLog().debug( "updateManifestEntries in " + directory + " found " + jarFiles.length + " jar(s) to treat" ); if ( jarFiles.length == 0 ) { return; } for ( File unprocessedJarFile : jarFiles ) { verboseLog( "Update manifest " + toProcessFile( unprocessedJarFile ).getName() ); jarUtil.updateManifestEntries( unprocessedJarFile, updateManifestEntries ); } } /** * @param directory location of directory where to sign jars * @return the number of signed jars * @throws MojoExecutionException if can not sign jars */ private int signJars( File directory ) throws MojoExecutionException { File[] jarFiles = directory.listFiles( unprocessedJarFileFilter ); getLog().info( "-- Sign jars" ); getLog().debug( "signJars in " + directory + " found " + jarFiles.length + " jar(s) to sign" ); if ( jarFiles.length == 0 ) { return 0; } boolean signVerify = sign.isVerify(); for ( File unprocessedJarFile : jarFiles ) { File signedJar = toProcessFile( unprocessedJarFile ); ioUtil.deleteFile( signedJar ); verboseLog( "Sign " + signedJar.getName() ); signTool.sign( sign, unprocessedJarFile, signedJar ); getLog().debug( "lastModified signedJar:" + signedJar.lastModified() + " unprocessed signed Jar:" + unprocessedJarFile.lastModified() ); if ( signVerify ) { verboseLog( "Verify signature of " + signedJar.getName() ); signTool.verify( sign, signedJar, isVerbose() ); } // remove unprocessed files // TODO wouldn't have to do that if we copied the unprocessed jar files in a temporary area ioUtil.deleteFile( unprocessedJarFile ); } return jarFiles.length; } /** * Removes the signature of the files in the specified directory which satisfy the * specified filter. * * @param workDirectory working directory used to unsign jars * @return the number of unsigned jars * @throws MojoExecutionException if could not remove signatures */ private int removeExistingSignatures( File workDirectory ) throws MojoExecutionException { getLog().info( "-- Remove existing signatures" ); // cleanup tempDir if exists File tempDir = new File( workDirectory, "temp_extracted_jars" ); ioUtil.removeDirectory( tempDir ); // recreate temp dir ioUtil.makeDirectoryIfNecessary( tempDir ); // process jars File[] jarFiles = workDirectory.listFiles( unprocessedJarFileFilter ); for ( File jarFile : jarFiles ) { if ( isJarSigned( jarFile ) ) { if ( !canUnsign ) { throw new MojoExecutionException( "neverUnsignAlreadySignedJar is set to true and a jar file [" + jarFile + " was asked to be unsign,\n please prefer use in this case an extension for " + "signed jars or not set to true the neverUnsignAlreadySignedJar parameter, Make " + "your choice:)" ); } verboseLog( "Remove signature " + toProcessFile( jarFile ).getName() ); signTool.unsign( jarFile, isVerbose() ); } else { verboseLog( "Skip not signed " + toProcessFile( jarFile ).getName() ); } } // cleanup tempDir ioUtil.removeDirectory( tempDir ); return jarFiles.length; // FIXME this is wrong. Not all jars are signed. } private ClassLoader getCompileClassLoader() throws MalformedURLException { URL[] urls = new URL[compileClassPath.size()]; for ( int i = 0; i < urls.length; i++ ) { String spec = compileClassPath.get( i ).toString(); URL url = new File( spec ).toURI().toURL(); urls[i] = url; } return new URLClassLoader( urls ); } private File toUnprocessFile( File targetDirectory, String sourceName ) { if ( sourceName.startsWith( UNPROCESSED_PREFIX ) ) { throw new IllegalStateException( sourceName + " does start with " + UNPROCESSED_PREFIX ); } String targetFilename = UNPROCESSED_PREFIX + sourceName; return new File( targetDirectory, targetFilename ); } private File toProcessFile( File source ) { if ( !source.getName().startsWith( UNPROCESSED_PREFIX ) ) { throw new IllegalStateException( source.getName() + " does not start with " + UNPROCESSED_PREFIX ); } String targetFilename = source.getName().substring( UNPROCESSED_PREFIX.length() ); return new File( source.getParentFile(), targetFilename ); } }
friskluft/nyx
src/nyx/features/convex_hull_nontriv.cpp
#define _USE_MATH_DEFINES // For M_PI, etc. #include <cmath> #include "../feature_method.h" #include "image_matrix_nontriv.h" #include "convex_hull.h" ConvexHullFeature::ConvexHullFeature() { provide_features ({CONVEX_HULL_AREA, SOLIDITY, CIRCULARITY}); } void ConvexHullFeature::save_value(std::vector<std::vector<double>>& fvals) { fvals [CONVEX_HULL_AREA][0] = area; fvals[SOLIDITY][0] = solidity; fvals [CIRCULARITY][0] = circularity; } void ConvexHullFeature::cleanup_instance() { area = solidity = circularity = 0.0; } void ConvexHullFeature::calculate (LR& r) { build_convex_hull(r.raw_pixels, r.convHull_CH); double s_hull = polygon_area(r.convHull_CH), s_roi = r.raw_pixels.size(), p = r.fvals[PERIMETER][0]; area = s_hull; solidity = s_roi / s_hull; circularity = 4.0 * M_PI * s_roi / (p*p); } void ConvexHullFeature::build_convex_hull (const std::vector<Pixel2>& roi_cloud, std::vector<Pixel2>& convhull) { convhull.clear(); // Skip calculation if the ROI is too small if (roi_cloud.size() < 2) return; std::vector<Pixel2>& upperCH = convhull; std::vector<Pixel2> lowerCH; size_t n = roi_cloud.size(); // Sorting points std::vector<Pixel2> cloud = roi_cloud; // Safely copy the ROI for fear of changing the original pixels order std::sort (cloud.begin(), cloud.end(), compare_locations); // Computing upper convex hull upperCH.push_back (cloud[0]); upperCH.push_back (cloud[1]); for (size_t i = 2; i < n; i++) { while (upperCH.size() > 1 && (!right_turn(upperCH[upperCH.size() - 2], upperCH[upperCH.size() - 1], cloud[i]))) upperCH.pop_back(); upperCH.push_back(cloud[i]); } // Computing lower convex hull lowerCH.push_back(cloud[n - 1]); lowerCH.push_back(cloud[n - 2]); for (size_t i = 2; i < n; i++) { while (lowerCH.size() > 1 && (!right_turn(lowerCH[lowerCH.size() - 2], lowerCH[lowerCH.size() - 1], cloud[n - i - 1]))) lowerCH.pop_back(); lowerCH.push_back(cloud[n - i - 1]); } // We could use // upperCH.insert (upperCH.end(), lowerCH.begin(), lowerCH.end()); // but we don't need duplicate points in the result contour for (auto& p : lowerCH) if (std::find(upperCH.begin(), upperCH.end(), p) == upperCH.end()) upperCH.push_back(p); } // Sort criterion: points are sorted with respect to their x-coordinate. // If two points have the same x-coordinate then we compare // their y-coordinates bool ConvexHullFeature::compare_locations (const Pixel2& lhs, const Pixel2& rhs) { return (lhs.x < rhs.x) || (lhs.x == rhs.x && lhs.y < rhs.y); } // Check if three points make a right turn using cross product bool ConvexHullFeature::right_turn (const Pixel2& P1, const Pixel2& P2, const Pixel2& P3) { return ((P3.x - P1.x) * (P2.y - P1.y) - (P3.y - P1.y) * (P2.x - P1.x)) > 0; } double ConvexHullFeature::polygon_area (const std::vector<Pixel2>& vertices) { // Blank polygon? if (vertices.size() == 0) return 0.0; // Normal polygon double area = 0.0; int n = (int)vertices.size(); for (int i = 0; i < n - 1; i++) { const Pixel2& p_i = vertices[i], & p_ii = vertices[i + 1]; area += p_i.x * p_ii.y - p_i.y * p_ii.x; } area += vertices[n - 1].x * vertices[0].y - vertices[0].x * vertices[n - 1].y; area = std::abs(area) / 2.0; return area; } void ConvexHullFeature::osized_calculate (LR& r, ImageLoader& imloader) { r.convHull_CH.clear(); size_t n = r.osized_pixel_cloud.get_size(); // Skip calculation if the ROI is too small if (n < 2) return; std::vector<Pixel2>& upperCH = r.convHull_CH; std::vector<Pixel2> lowerCH; // Computing upper convex hull upperCH.push_back(r.osized_pixel_cloud.get_at(0)); upperCH.push_back(r.osized_pixel_cloud.get_at(1)); for (size_t i = 2; i < n; i++) { while (upperCH.size() > 1 && (!right_turn(upperCH[upperCH.size() - 2], upperCH[upperCH.size() - 1], r.osized_pixel_cloud.get_at(i)))) upperCH.pop_back(); upperCH.push_back(r.osized_pixel_cloud.get_at(i)); } // Computing lower convex hull lowerCH.push_back(r.osized_pixel_cloud.get_at(n - 1)); lowerCH.push_back(r.osized_pixel_cloud.get_at(n - 2)); for (size_t i = 2; i < n; i++) { while (lowerCH.size() > 1 && (!right_turn(lowerCH[lowerCH.size() - 2], lowerCH[lowerCH.size() - 1], r.osized_pixel_cloud.get_at(n - i - 1)))) lowerCH.pop_back(); lowerCH.push_back(r.osized_pixel_cloud.get_at(n - i - 1)); } // We could use // upperCH.insert (upperCH.end(), lowerCH.begin(), lowerCH.end()); // but we don't need duplicate points in the result contour for (auto& p : lowerCH) if (std::find(upperCH.begin(), upperCH.end(), p) == upperCH.end()) upperCH.push_back(p); } namespace Nyxus { void parallelReduceConvHull (size_t start, size_t end, std::vector<int>* ptrLabels, std::unordered_map <int, LR>* ptrLabelData) { for (auto i = start; i < end; i++) { int lab = (*ptrLabels)[i]; LR& r = (*ptrLabelData)[lab]; if (r.has_bad_data()) continue; ConvexHullFeature fea; fea.calculate (r); fea.save_value (r.fvals); } } }
arthurb123/Lynx2D
modules/objects/scene.js
<filename>modules/objects/scene.js /** * Lynx2D Scene * @constructor * @param {function} callback - The callback that gets executed once the Scene loads, all code should go in here. */ this.Scene = class { constructor (callback) { this.SAVED_STATE_AVAILABLE = false; this.CALLBACK = callback; }; /** * Saves the Scene's current state and content * in memory. */ Save() { //Create a snapshot of the current state let snapshot = lx.GAME.CREATE_SNAPSHOT(); //Save to memory this.SAVE_DATA = snapshot; this.SAVED_STATE_AVAILABLE = true; }; /** * Restores the Scene's current state and content * from memory. * @returns {boolean} - Indicates if the restoration was successful. */ Restore() { //Check if a saved state is available if (!this.SAVED_STATE_AVAILABLE) return false; //Reset game lx.GAME.RESET(); //Restore saved state lx.GAME.RESTORE_SNAPSHOT(this.SAVE_DATA); //Return successful return true; }; };
supensour/supensour
supensour-core/src/main/java/com/supensour/core/thread/task/ContextAwareThreadTask.java
package com.supensour.core.thread.task; import com.supensour.core.thread.setting.ContextAwareThreadSetting; import org.springframework.lang.NonNull; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.Callable; /** * @author <NAME> * @since 0.1.0 */ public class ContextAwareThreadTask<T> { @NonNull private final Callable<T> task; @NonNull private final Map<Object, Object> context; @NonNull private final List<ContextAwareThreadSetting<Object>> settings; public ContextAwareThreadTask(@NonNull Callable<T> task, @NonNull List<ContextAwareThreadSetting<Object>> settings) { this.task = task; this.context = new HashMap<>(); this.settings = settings; storeContext(); } public final T execute() throws Exception { initializeContext(); try { return task.call(); } finally { clearContext(); } } private void storeContext() { for (ContextAwareThreadSetting<Object> setting : settings) { Object key = setting.getKey(); Optional.ofNullable(setting.getGetter()) .map(getter -> getter.get(context, key)) .ifPresent(data -> context.put(key, data)); } } private void initializeContext() { for (ContextAwareThreadSetting<Object> setting : settings) { Object key = setting.getKey(); Object data = context.get(key); Optional.ofNullable(setting.getSetter()) .ifPresent(setter -> setter.set(data, context, key)); } } private void clearContext() { for (ContextAwareThreadSetting<Object> setting : settings) { Object key = setting.getKey(); Object data = context.get(key); Optional.ofNullable(setting.getDestroyer()) .ifPresent(destroyer -> destroyer.destroy(data, context, key)); } } }
heaths/azure-sdk-for-go
sdk/resourcemanager/sql/armsql/zz_generated_sensitivitylabels_client.go
//go:build go1.16 // +build go1.16 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package armsql import ( "context" "errors" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "net/http" "net/url" "strconv" "strings" ) // SensitivityLabelsClient contains the methods for the SensitivityLabels group. // Don't use this type directly, use NewSensitivityLabelsClient() instead. type SensitivityLabelsClient struct { host string subscriptionID string pl runtime.Pipeline } // NewSensitivityLabelsClient creates a new instance of SensitivityLabelsClient with the specified values. // subscriptionID - The subscription ID that identifies an Azure subscription. // credential - used to authorize requests. Usually a credential from azidentity. // options - pass nil to accept the default values. func NewSensitivityLabelsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *SensitivityLabelsClient { cp := arm.ClientOptions{} if options != nil { cp = *options } if len(cp.Endpoint) == 0 { cp.Endpoint = arm.AzurePublicCloud } client := &SensitivityLabelsClient{ subscriptionID: subscriptionID, host: string(cp.Endpoint), pl: armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, &cp), } return client } // CreateOrUpdate - Creates or updates the sensitivity label of a given column // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // schemaName - The name of the schema. // tableName - The name of the table. // columnName - The name of the column. // parameters - The column sensitivity label resource. // options - SensitivityLabelsClientCreateOrUpdateOptions contains the optional parameters for the SensitivityLabelsClient.CreateOrUpdate // method. func (client *SensitivityLabelsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, parameters SensitivityLabel, options *SensitivityLabelsClientCreateOrUpdateOptions) (SensitivityLabelsClientCreateOrUpdateResponse, error) { req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, parameters, options) if err != nil { return SensitivityLabelsClientCreateOrUpdateResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return SensitivityLabelsClientCreateOrUpdateResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { return SensitivityLabelsClientCreateOrUpdateResponse{}, runtime.NewResponseError(resp) } return client.createOrUpdateHandleResponse(resp) } // createOrUpdateCreateRequest creates the CreateOrUpdate request. func (client *SensitivityLabelsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, parameters SensitivityLabel, options *SensitivityLabelsClientCreateOrUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}/columns/{columnName}/sensitivityLabels/{sensitivityLabelSource}" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if schemaName == "" { return nil, errors.New("parameter schemaName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{schemaName}", url.PathEscape(schemaName)) if tableName == "" { return nil, errors.New("parameter tableName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) if columnName == "" { return nil, errors.New("parameter columnName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{columnName}", url.PathEscape(columnName)) urlPath = strings.ReplaceAll(urlPath, "{sensitivityLabelSource}", url.PathEscape("current")) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, runtime.MarshalAsJSON(req, parameters) } // createOrUpdateHandleResponse handles the CreateOrUpdate response. func (client *SensitivityLabelsClient) createOrUpdateHandleResponse(resp *http.Response) (SensitivityLabelsClientCreateOrUpdateResponse, error) { result := SensitivityLabelsClientCreateOrUpdateResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.SensitivityLabel); err != nil { return SensitivityLabelsClientCreateOrUpdateResponse{}, err } return result, nil } // Delete - Deletes the sensitivity label of a given column // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // schemaName - The name of the schema. // tableName - The name of the table. // columnName - The name of the column. // options - SensitivityLabelsClientDeleteOptions contains the optional parameters for the SensitivityLabelsClient.Delete // method. func (client *SensitivityLabelsClient) Delete(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, options *SensitivityLabelsClientDeleteOptions) (SensitivityLabelsClientDeleteResponse, error) { req, err := client.deleteCreateRequest(ctx, resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, options) if err != nil { return SensitivityLabelsClientDeleteResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return SensitivityLabelsClientDeleteResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return SensitivityLabelsClientDeleteResponse{}, runtime.NewResponseError(resp) } return SensitivityLabelsClientDeleteResponse{RawResponse: resp}, nil } // deleteCreateRequest creates the Delete request. func (client *SensitivityLabelsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, options *SensitivityLabelsClientDeleteOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}/columns/{columnName}/sensitivityLabels/{sensitivityLabelSource}" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if schemaName == "" { return nil, errors.New("parameter schemaName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{schemaName}", url.PathEscape(schemaName)) if tableName == "" { return nil, errors.New("parameter tableName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) if columnName == "" { return nil, errors.New("parameter columnName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{columnName}", url.PathEscape(columnName)) urlPath = strings.ReplaceAll(urlPath, "{sensitivityLabelSource}", url.PathEscape("current")) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } // DisableRecommendation - Disables sensitivity recommendations on a given column // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // schemaName - The name of the schema. // tableName - The name of the table. // columnName - The name of the column. // options - SensitivityLabelsClientDisableRecommendationOptions contains the optional parameters for the SensitivityLabelsClient.DisableRecommendation // method. func (client *SensitivityLabelsClient) DisableRecommendation(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, options *SensitivityLabelsClientDisableRecommendationOptions) (SensitivityLabelsClientDisableRecommendationResponse, error) { req, err := client.disableRecommendationCreateRequest(ctx, resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, options) if err != nil { return SensitivityLabelsClientDisableRecommendationResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return SensitivityLabelsClientDisableRecommendationResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return SensitivityLabelsClientDisableRecommendationResponse{}, runtime.NewResponseError(resp) } return SensitivityLabelsClientDisableRecommendationResponse{RawResponse: resp}, nil } // disableRecommendationCreateRequest creates the DisableRecommendation request. func (client *SensitivityLabelsClient) disableRecommendationCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, options *SensitivityLabelsClientDisableRecommendationOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}/columns/{columnName}/sensitivityLabels/{sensitivityLabelSource}/disable" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if schemaName == "" { return nil, errors.New("parameter schemaName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{schemaName}", url.PathEscape(schemaName)) if tableName == "" { return nil, errors.New("parameter tableName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) if columnName == "" { return nil, errors.New("parameter columnName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{columnName}", url.PathEscape(columnName)) urlPath = strings.ReplaceAll(urlPath, "{sensitivityLabelSource}", url.PathEscape("recommended")) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } // EnableRecommendation - Enables sensitivity recommendations on a given column (recommendations are enabled by default on // all columns) // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // schemaName - The name of the schema. // tableName - The name of the table. // columnName - The name of the column. // options - SensitivityLabelsClientEnableRecommendationOptions contains the optional parameters for the SensitivityLabelsClient.EnableRecommendation // method. func (client *SensitivityLabelsClient) EnableRecommendation(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, options *SensitivityLabelsClientEnableRecommendationOptions) (SensitivityLabelsClientEnableRecommendationResponse, error) { req, err := client.enableRecommendationCreateRequest(ctx, resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, options) if err != nil { return SensitivityLabelsClientEnableRecommendationResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return SensitivityLabelsClientEnableRecommendationResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return SensitivityLabelsClientEnableRecommendationResponse{}, runtime.NewResponseError(resp) } return SensitivityLabelsClientEnableRecommendationResponse{RawResponse: resp}, nil } // enableRecommendationCreateRequest creates the EnableRecommendation request. func (client *SensitivityLabelsClient) enableRecommendationCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, options *SensitivityLabelsClientEnableRecommendationOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}/columns/{columnName}/sensitivityLabels/{sensitivityLabelSource}/enable" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if schemaName == "" { return nil, errors.New("parameter schemaName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{schemaName}", url.PathEscape(schemaName)) if tableName == "" { return nil, errors.New("parameter tableName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) if columnName == "" { return nil, errors.New("parameter columnName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{columnName}", url.PathEscape(columnName)) urlPath = strings.ReplaceAll(urlPath, "{sensitivityLabelSource}", url.PathEscape("recommended")) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } // Get - Gets the sensitivity label of a given column // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // schemaName - The name of the schema. // tableName - The name of the table. // columnName - The name of the column. // sensitivityLabelSource - The source of the sensitivity label. // options - SensitivityLabelsClientGetOptions contains the optional parameters for the SensitivityLabelsClient.Get method. func (client *SensitivityLabelsClient) Get(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, sensitivityLabelSource SensitivityLabelSource, options *SensitivityLabelsClientGetOptions) (SensitivityLabelsClientGetResponse, error) { req, err := client.getCreateRequest(ctx, resourceGroupName, serverName, databaseName, schemaName, tableName, columnName, sensitivityLabelSource, options) if err != nil { return SensitivityLabelsClientGetResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return SensitivityLabelsClientGetResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return SensitivityLabelsClientGetResponse{}, runtime.NewResponseError(resp) } return client.getHandleResponse(resp) } // getCreateRequest creates the Get request. func (client *SensitivityLabelsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, schemaName string, tableName string, columnName string, sensitivityLabelSource SensitivityLabelSource, options *SensitivityLabelsClientGetOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/schemas/{schemaName}/tables/{tableName}/columns/{columnName}/sensitivityLabels/{sensitivityLabelSource}" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if schemaName == "" { return nil, errors.New("parameter schemaName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{schemaName}", url.PathEscape(schemaName)) if tableName == "" { return nil, errors.New("parameter tableName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) if columnName == "" { return nil, errors.New("parameter columnName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{columnName}", url.PathEscape(columnName)) if sensitivityLabelSource == "" { return nil, errors.New("parameter sensitivityLabelSource cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{sensitivityLabelSource}", url.PathEscape(string(sensitivityLabelSource))) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // getHandleResponse handles the Get response. func (client *SensitivityLabelsClient) getHandleResponse(resp *http.Response) (SensitivityLabelsClientGetResponse, error) { result := SensitivityLabelsClientGetResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.SensitivityLabel); err != nil { return SensitivityLabelsClientGetResponse{}, err } return result, nil } // ListCurrentByDatabase - Gets the sensitivity labels of a given database // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // options - SensitivityLabelsClientListCurrentByDatabaseOptions contains the optional parameters for the SensitivityLabelsClient.ListCurrentByDatabase // method. func (client *SensitivityLabelsClient) ListCurrentByDatabase(resourceGroupName string, serverName string, databaseName string, options *SensitivityLabelsClientListCurrentByDatabaseOptions) *SensitivityLabelsClientListCurrentByDatabasePager { return &SensitivityLabelsClientListCurrentByDatabasePager{ client: client, requester: func(ctx context.Context) (*policy.Request, error) { return client.listCurrentByDatabaseCreateRequest(ctx, resourceGroupName, serverName, databaseName, options) }, advancer: func(ctx context.Context, resp SensitivityLabelsClientListCurrentByDatabaseResponse) (*policy.Request, error) { return runtime.NewRequest(ctx, http.MethodGet, *resp.SensitivityLabelListResult.NextLink) }, } } // listCurrentByDatabaseCreateRequest creates the ListCurrentByDatabase request. func (client *SensitivityLabelsClient) listCurrentByDatabaseCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, options *SensitivityLabelsClientListCurrentByDatabaseOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/currentSensitivityLabels" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() if options != nil && options.SkipToken != nil { reqQP.Set("$skipToken", *options.SkipToken) } if options != nil && options.Count != nil { reqQP.Set("$count", strconv.FormatBool(*options.Count)) } if options != nil && options.Filter != nil { reqQP.Set("$filter", *options.Filter) } reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // listCurrentByDatabaseHandleResponse handles the ListCurrentByDatabase response. func (client *SensitivityLabelsClient) listCurrentByDatabaseHandleResponse(resp *http.Response) (SensitivityLabelsClientListCurrentByDatabaseResponse, error) { result := SensitivityLabelsClientListCurrentByDatabaseResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.SensitivityLabelListResult); err != nil { return SensitivityLabelsClientListCurrentByDatabaseResponse{}, err } return result, nil } // ListRecommendedByDatabase - Gets the sensitivity labels of a given database // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // options - SensitivityLabelsClientListRecommendedByDatabaseOptions contains the optional parameters for the SensitivityLabelsClient.ListRecommendedByDatabase // method. func (client *SensitivityLabelsClient) ListRecommendedByDatabase(resourceGroupName string, serverName string, databaseName string, options *SensitivityLabelsClientListRecommendedByDatabaseOptions) *SensitivityLabelsClientListRecommendedByDatabasePager { return &SensitivityLabelsClientListRecommendedByDatabasePager{ client: client, requester: func(ctx context.Context) (*policy.Request, error) { return client.listRecommendedByDatabaseCreateRequest(ctx, resourceGroupName, serverName, databaseName, options) }, advancer: func(ctx context.Context, resp SensitivityLabelsClientListRecommendedByDatabaseResponse) (*policy.Request, error) { return runtime.NewRequest(ctx, http.MethodGet, *resp.SensitivityLabelListResult.NextLink) }, } } // listRecommendedByDatabaseCreateRequest creates the ListRecommendedByDatabase request. func (client *SensitivityLabelsClient) listRecommendedByDatabaseCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, options *SensitivityLabelsClientListRecommendedByDatabaseOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/recommendedSensitivityLabels" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() if options != nil && options.SkipToken != nil { reqQP.Set("$skipToken", *options.SkipToken) } if options != nil && options.IncludeDisabledRecommendations != nil { reqQP.Set("includeDisabledRecommendations", strconv.FormatBool(*options.IncludeDisabledRecommendations)) } if options != nil && options.Filter != nil { reqQP.Set("$filter", *options.Filter) } reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // listRecommendedByDatabaseHandleResponse handles the ListRecommendedByDatabase response. func (client *SensitivityLabelsClient) listRecommendedByDatabaseHandleResponse(resp *http.Response) (SensitivityLabelsClientListRecommendedByDatabaseResponse, error) { result := SensitivityLabelsClientListRecommendedByDatabaseResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.SensitivityLabelListResult); err != nil { return SensitivityLabelsClientListRecommendedByDatabaseResponse{}, err } return result, nil } // Update - Update sensitivity labels of a given database using an operations batch. // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure // Resource Manager API or the portal. // serverName - The name of the server. // databaseName - The name of the database. // options - SensitivityLabelsClientUpdateOptions contains the optional parameters for the SensitivityLabelsClient.Update // method. func (client *SensitivityLabelsClient) Update(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters SensitivityLabelUpdateList, options *SensitivityLabelsClientUpdateOptions) (SensitivityLabelsClientUpdateResponse, error) { req, err := client.updateCreateRequest(ctx, resourceGroupName, serverName, databaseName, parameters, options) if err != nil { return SensitivityLabelsClientUpdateResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return SensitivityLabelsClientUpdateResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return SensitivityLabelsClientUpdateResponse{}, runtime.NewResponseError(resp) } return SensitivityLabelsClientUpdateResponse{RawResponse: resp}, nil } // updateCreateRequest creates the Update request. func (client *SensitivityLabelsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters SensitivityLabelUpdateList, options *SensitivityLabelsClientUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/currentSensitivityLabels" if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if serverName == "" { return nil, errors.New("parameter serverName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{serverName}", url.PathEscape(serverName)) if databaseName == "" { return nil, errors.New("parameter databaseName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-11-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() return req, runtime.MarshalAsJSON(req, parameters) }
leandcesar/tmdb-python
tmdb/schema/find.py
<gh_stars>0 # -*- coding: utf-8 -*- from dataclasses import dataclass from typing import Optional from .media import Media from .person import PersonPartial @dataclass class Find: movie_results: Optional[list[Media]] person_results: Optional[list[PersonPartial]] tv_episode_results: Optional[list[Media]] tv_results: Optional[list[Media]] tv_season_results: Optional[list[Media]] def __bool__(self) -> bool: return bool( self.movie_results or self.person_results or self.tv_episode_results or self.tv_results or self.tv_season_results )
george-zhang-work/dove
Reader/src/com/dove/reader/content/CursorCreator.java
<gh_stars>1-10 package com.dove.reader.content; import android.database.Cursor; /** * An object that knows how to create its implementing class using a single row * of a cursor alone. * * @param <T> */ public interface CursorCreator<T> { /** * Creates an object using the current row of the cursor given here. The * implementation should not advance/rewind the cursor, and is only allowed * to read the existing row. * * @param c * @return a real object of the implementing class. */ T createFromCursor(Cursor c); }
dram/metasfresh
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/X_PP_Order_ExportAudit.java
<reponame>dram/metasfresh<gh_stars>1000+ /** Generated Model - DO NOT CHANGE */ package org.eevolution.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for PP_Order_ExportAudit * @author metasfresh (generated) */ @SuppressWarnings("javadoc") public class X_PP_Order_ExportAudit extends org.compiere.model.PO implements I_PP_Order_ExportAudit, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1413133859L; /** Standard Constructor */ public X_PP_Order_ExportAudit (Properties ctx, int PP_Order_ExportAudit_ID, String trxName) { super (ctx, PP_Order_ExportAudit_ID, trxName); } /** Load Constructor */ public X_PP_Order_ExportAudit (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Issue getAD_Issue() { return get_ValueAsPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class); } @Override public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue) { set_ValueFromPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class, AD_Issue); } @Override public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } /** * ExportStatus AD_Reference_ID=541161 * Reference name: API_ExportStatus */ public static final int EXPORTSTATUS_AD_Reference_ID=541161; /** PENDING = PENDING */ public static final String EXPORTSTATUS_PENDING = "PENDING"; /** EXPORTED = EXPORTED */ public static final String EXPORTSTATUS_EXPORTED = "EXPORTED"; /** EXPORTED_AND_FORWARDED = EXPORTED_AND_FORWARDED */ public static final String EXPORTSTATUS_EXPORTED_AND_FORWARDED = "EXPORTED_AND_FORWARDED"; /** EXPORTED_FORWARD_ERROR = EXPORTED_FORWARD_ERROR */ public static final String EXPORTSTATUS_EXPORTED_FORWARD_ERROR = "EXPORTED_FORWARD_ERROR"; /** EXPORT_ERROR = EXPORT_ERROR */ public static final String EXPORTSTATUS_EXPORT_ERROR = "EXPORT_ERROR"; /** DONT_EXPORT = DONT_EXPORT */ public static final String EXPORTSTATUS_DONT_EXPORT = "DONT_EXPORT"; @Override public void setExportStatus (java.lang.String ExportStatus) { set_Value (COLUMNNAME_ExportStatus, ExportStatus); } @Override public java.lang.String getExportStatus() { return (java.lang.String)get_Value(COLUMNNAME_ExportStatus); } @Override public void setJsonRequest (java.lang.String JsonRequest) { set_Value (COLUMNNAME_JsonRequest, JsonRequest); } @Override public java.lang.String getJsonRequest() { return (java.lang.String)get_Value(COLUMNNAME_JsonRequest); } @Override public void setPP_Order_ExportAudit_ID (int PP_Order_ExportAudit_ID) { if (PP_Order_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ExportAudit_ID, Integer.valueOf(PP_Order_ExportAudit_ID)); } @Override public int getPP_Order_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ExportAudit_ID); } @Override public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
hrvojekindl/pocket-cube-optimal-solver
src/hashes.js
<gh_stars>1-10 exports.hash5 = function({p2, p1, p0, o}) { //avg 7.599925518689986 len 373248 373248 let v = o - ((o & 0b1010101010101010) >> 1); return (p2&0b111 | (p1&0b11100)<<2 | (p0&0b110001)<<3) * 729 + (v&0b11) + (v&0b1100)*3/4 + (v&0b110000)*9/16 + (v&0b11000000)*27/64 + (v&0b1100000000)*81/256 + (v&0b110000000000)*243/1024; }; exports.hash6 = function({p2, p1, p0, o}) { //avg 6.288299560546875 len 32768 32768 let g = ((o & 0b010101010101) * 0b100001 >> 5) & 0b111111; return (p2&0b111 | (p1&0b11100)<<2 | (p0&0b110001)<<3)<<6 | g; }; exports.hash7 = function({p2, p1, p0, o}) { //avg 3.677734375 len 512 512 let g = ((o & 0b010101010101) * 0b100001 >> 5) & 0b111111; return (p2&0b111 | (p1&0b11100)<<2 | (p0&0b110001)<<3); }; exports.hash8 = function({p2, p1, p0, o}) { let v = o - ((o & 0b1010101010101010) >> 1); return (p2&0b1111 | (p1&0b11110)<<3 | (p0&0b111100)<<6) * 729 + (v&0b11) + (v&0b1100)*3/4 + (v&0b110000)*9/16 + (v&0b11000000)*27/64 + (v&0b1100000000)*81/256 + (v&0b110000000000)*243/1024; }; exports.hash9 = function({p2, p1, p0, o}) { // transform orientation 2 from 11 to 01, leave the rest let v = o - ((o & 0b1010101010101010) >> 1); return (p2&0b111 | (p1&0b11100)<<2 | (p0&0b110001)<<3) * 243 + ((v&0b000000000011) ) + ((v&0b000000001100) >> 2) * 3 + ((v&0b000000110000) >> 4) * 9 + ((v&0b000011000000) >> 6) * 27+ ((v&0b001100000000) >> 8) * 81; };
pniekamp/datum-studio
src/plugins/edit/editormanager.cpp
<reponame>pniekamp/datum-studio // // Editor Management // // // Copyright (C) 2016 <NAME> // #include "editormanager.h" #include <QMessageBox> #include <QtDebug> using namespace std; //|---------------------- EditorManager ------------------------------------- //|-------------------------------------------------------------------------- //| Editor Manager //| ///////////////////////// EditorManager::Constructor //////////////////////// EditorManager::EditorManager() { m_currentview = nullptr; } ///////////////////////// EditorManager::open_editor //////////////////////// void EditorManager::open_editor(QString const &type, QString const &path) { m_currentview->open_editor(type, path); } ///////////////////////// EditorManager::register_editor //////////////////// void EditorManager::register_editor(EditorView *editor) { m_views.push_back(editor); } ///////////////////////// EditorManager::set_current_editor ///////////////// void EditorManager::set_current_editor(EditorView *editor) { m_currentview = editor; } ///////////////////////// EditorManager::save_all /////////////////////////// int EditorManager::save_all() { for(auto &view : m_views) { view->save_all(); } return QMessageBox::Ok; } ///////////////////////// EditorManager::close_all ////////////////////////// int EditorManager::close_all() { int reply = QMessageBox::Ok; for(auto &view : m_views) { if (view->close_all() == QMessageBox::Cancel) { reply = QMessageBox::Cancel; break; } } return reply; }
mitchellolsthoorn/SSBSE-Research-2021-crossover-replication
subjects/components/code/commons-statistics/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/BinomialDistribution.java
<filename>subjects/components/code/commons-statistics/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/BinomialDistribution.java<gh_stars>1-10 /* * 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.commons.statistics.distribution; import org.apache.commons.numbers.gamma.RegularizedBeta; /** * Implementation of the <a href="http://en.wikipedia.org/wiki/Binomial_distribution">binomial distribution</a>. */ public class BinomialDistribution extends AbstractDiscreteDistribution { /** The number of trials. */ private final int numberOfTrials; /** The probability of success. */ private final double probabilityOfSuccess; /** * Creates a binomial distribution. * * @param trials Number of trials. * @param p Probability of success. * @throws IllegalArgumentException if {@code trials < 0}, or if * {@code p < 0} or {@code p > 1}. */ public BinomialDistribution(int trials, double p) { if (trials < 0) { throw new DistributionException(DistributionException.NEGATIVE, trials); } if (p < 0 || p > 1) { throw new DistributionException(DistributionException.INVALID_PROBABILITY, p); } probabilityOfSuccess = p; numberOfTrials = trials; } /** * Access the number of trials for this distribution. * * @return the number of trials. */ public int getNumberOfTrials() { return numberOfTrials; } /** * Access the probability of success for this distribution. * * @return the probability of success. */ public double getProbabilityOfSuccess() { return probabilityOfSuccess; } /** {@inheritDoc} */ @Override public double probability(int x) { final double logProbability = logProbability(x); return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); } /** {@inheritDoc} **/ @Override public double logProbability(int x) { if (numberOfTrials == 0) { return (x == 0) ? 0. : Double.NEGATIVE_INFINITY; } double ret; if (x < 0 || x > numberOfTrials) { ret = Double.NEGATIVE_INFINITY; } else { ret = SaddlePointExpansionUtils.logBinomialProbability(x, numberOfTrials, probabilityOfSuccess, 1.0 - probabilityOfSuccess); } return ret; } /** {@inheritDoc} */ @Override public double cumulativeProbability(int x) { double ret; if (x < 0) { ret = 0.0; } else if (x >= numberOfTrials) { ret = 1.0; } else { ret = 1.0 - RegularizedBeta.value(probabilityOfSuccess, x + 1.0, (double) numberOfTrials - x); } return ret; } /** * {@inheritDoc} * * For {@code n} trials and probability parameter {@code p}, the mean is * {@code n * p}. */ @Override public double getMean() { return numberOfTrials * probabilityOfSuccess; } /** * {@inheritDoc} * * For {@code n} trials and probability parameter {@code p}, the variance is * {@code n * p * (1 - p)}. */ @Override public double getVariance() { final double p = probabilityOfSuccess; return numberOfTrials * p * (1 - p); } /** * {@inheritDoc} * * The lower bound of the support is always 0 except for the probability * parameter {@code p = 1}. * * @return lower bound of the support (0 or the number of trials) */ @Override public int getSupportLowerBound() { return probabilityOfSuccess < 1.0 ? 0 : numberOfTrials; } /** * {@inheritDoc} * * The upper bound of the support is the number of trials except for the * probability parameter {@code p = 0}. * * @return upper bound of the support (number of trials or 0) */ @Override public int getSupportUpperBound() { return probabilityOfSuccess > 0.0 ? numberOfTrials : 0; } /** * {@inheritDoc} * * The support of this distribution is connected. * * @return {@code true} */ @Override public boolean isSupportConnected() { return true; } }
vehicle-history/vehicle-history-android
app/src/main/java/io/vehiclehistory/api/model/Name.java
package io.vehiclehistory.api.model; import java.io.Serializable; /** * Created by dudvar on 2015-03-13. */ public class Name implements Serializable { private CarMake make; private String carName; private String model; public CarMake getMake() { return make; } public String getCarName() { return carName; } public String getModel() { return model; } }
kwery/kwery
src/test/java/com/kwery/tests/controllers/apis/integration/jobapicontroller/JobApiControllerExecuteJobTest.java
<reponame>kwery/kwery<filename>src/test/java/com/kwery/tests/controllers/apis/integration/jobapicontroller/JobApiControllerExecuteJobTest.java<gh_stars>10-100 package com.kwery.tests.controllers.apis.integration.jobapicontroller; import com.google.common.collect.ImmutableMap; import com.kwery.controllers.apis.JobApiController; import com.kwery.models.JobModel; import com.kwery.tests.controllers.apis.integration.userapicontroller.AbstractPostLoginApiTest; import ninja.Router; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath; import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJson; import static com.kwery.tests.fluentlenium.utils.DbUtil.jobDbSetUp; import static com.kwery.tests.util.TestUtil.jobModelWithoutDependents; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertThat; public class JobApiControllerExecuteJobTest extends AbstractPostLoginApiTest { private JobModel jobModel; @Before public void setUp() { jobModel = jobModelWithoutDependents(); jobDbSetUp(jobModel); } @Test public void test() { String url = getInjector().getInstance(Router.class).getReverseRoute(JobApiController.class, "executeJob", ImmutableMap.of("jobId", jobModel.getId())); String response = ninjaTestBrowser.postJson(getUrl(url), new HashMap<>()); assertThat(response, isJson()); assertThat(response, hasJsonPath("$.executionId", notNullValue())); } }
bigbigx/HFish
core/protocol/vnc/vnc.go
package vnc import ( "io" "log" "net" "fmt" "strings" "HFish/utils/is" "HFish/core/rpc/client" "HFish/core/report" "HFish/core/pool" ) const VERSION = "RFB 003.008\n" const CHALLENGE = "\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00" // 5900 func Start(address string) { l, err := net.Listen("tcp", address) if nil != err { } log.Printf("Listening on %v", l.Addr()) wg, poolX := pool.New(10) defer poolX.Release() /* Accept and handle clients */ for { wg.Add(1) poolX.Submit(func() { c, err := l.Accept() if nil != err { log.Fatalf("Error accepting connection: %v", err) } arr := strings.Split(c.RemoteAddr().String(), ":") // 判断是否为 RPC 客户端 if is.Rpc() { go client.ReportResult("VNC", "VNC蜜罐", arr[0], "存在VNC扫描!", "0") } else { go report.ReportVnc("VNC蜜罐", "本机", arr[0], "存在VNC扫描!") } go handle(c, ) wg.Done() }) } } func handle(c net.Conn) { defer c.Close() /* Send our version */ if _, err := c.Write([]byte(VERSION)); nil != err { log.Printf( "%v Error before server version: %v", c.RemoteAddr(), err, ) return } /* Get his version */ ver := make([]byte, len(VERSION)) n, err := io.ReadFull(c, ver) ver = ver[:n] if nil != err { log.Printf( "%v Disconnected before client version: %v", c.RemoteAddr(), err, ) return } /* Handle versions 3 and 8 */ var cver = string(ver) switch cver { case "RFB 003.008\n": /* Protocol version 3.8 */ cver = "RFB 3.8" /* Send number of security types (1) and the offered type (2, VNC Auth) */ /* TODO: Also, offer ALL the auths */ if _, err := c.Write([]byte{ 0x01, /* We will send one offered auth type */ 0x02, /* VNC Auth */ }); nil != err { log.Printf( "%v Unable to offer auth type (%v): %v", c.RemoteAddr(), cver, err, ) return } /* Get security type client wants, which should be 2 for now */ buf := make([]byte, 1) _, err = io.ReadFull(c, buf) if nil != err { log.Printf( "%v Unable to read accepted security type "+ "(%v): %v", c.RemoteAddr(), cver, err, ) return } if 0x02 != buf[0] { log.Printf( "%v Accepted unsupported security type "+ "%v (%v)", c.RemoteAddr(), cver, buf[0], ) return } case "RFB 003.003\n": /* Protocol version 3.3, which is ancient */ cver = "RFB 3.3" /* Tell the client to use VNC auth */ if _, err := c.Write([]byte{0, 0, 0, 2}); nil != err { log.Printf( "%v Unable to specify VNC auth (%v): %v", c.RemoteAddr(), cver, err, ) } default: /* Send an error message */ if _, err := c.Write(append( []byte{ 0, /* 0 security types */ 0, 0, 0, 20, /* 20-character message */ }, /* Failure message */ []byte("Unsupported RFB version.")..., )); nil != err { log.Printf( "%v Unable to send unsupported version "+ "message: %v", c.RemoteAddr(), err, ) } return } if _, err := c.Write([]byte(CHALLENGE)); nil != err { log.Printf( "%v Unable to send challenge: %v", c.RemoteAddr(), err, ) return } /* Get response */ buf := make([]byte, 16) n, err = io.ReadFull(c, buf) buf = buf[:n] if nil != err { if 0 == n { log.Printf( "%v Unable to read auth response: %v", c.RemoteAddr(), err, ) } else { log.Printf( "%v Received incomplete auth response: "+ "%q (%v)", c.RemoteAddr(), buf, err, ) } return } fmt.Print(c.RemoteAddr()) /* Tell client auth failed */ c.Write(append( []byte{ 0, 0, 0, 1, /* Failure word */ 0, 0, 0, 29, /* Message length */ }, /* Failure message */ []byte("Invalid username or password.")..., )) }
avedensky/JavaRushCore
1.JavaSyntax/src/com/javarush/task/task04/task0422/Solution.java
<reponame>avedensky/JavaRushCore<gh_stars>10-100 package com.javarush.task.task04.task0422; /* 18+ */ import javax.swing.plaf.synth.SynthTextAreaUI; import java.io.*; public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); String name = br.readLine(); int age = Integer.parseInt(br.readLine()); if (age<18) System.out.println("Подрасти еще"); } }
nwillc/simplecache
src/main/java/com/github/nwillc/simplecache/SCacheManager.java
<filename>src/main/java/com/github/nwillc/simplecache/SCacheManager.java /* * Copyright 2019 <EMAIL> * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.github.nwillc.simplecache; import com.github.nwillc.simplecache.spi.SCachingProvider; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.configuration.Configuration; import javax.cache.spi.CachingProvider; import java.net.URI; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; public class SCacheManager implements CacheManager { private final Map<String, Cache> cacheMap = new ConcurrentHashMap<>(); private final Properties properties; private final SCachingProvider cachingProvider; private final AtomicBoolean closed = new AtomicBoolean(true); public SCacheManager(SCachingProvider cachingProvider, Properties properties) { this.cachingProvider = cachingProvider; this.properties = properties == null ? new Properties() : properties; closed.set(false); } @Override public CachingProvider getCachingProvider() { return cachingProvider; } @Override public URI getURI() { throw new UnsupportedOperationException(); } @Override public ClassLoader getClassLoader() { return ClassLoader.getSystemClassLoader(); } @Override public Properties getProperties() { return properties; } @Override public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(String cacheName, C configuration) throws IllegalArgumentException { exceptionIfClosed(); Cache<K, V> cache = new SCache<>(this, cacheName, configuration); cacheMap.put(cacheName, cache); return cache; } @Override public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyType, Class<V> valueType) { return getCache(cacheName); } @SuppressWarnings("unchecked") @Override public <K, V> Cache<K, V> getCache(String cacheName) { exceptionIfClosed(); return cacheMap.get(cacheName); } @Override public Iterable<String> getCacheNames() { exceptionIfClosed(); return cacheMap.keySet(); } @Override public void destroyCache(String cacheName) { exceptionIfClosed(); cacheMap.remove(cacheName); } @Override public void enableManagement(String cacheName, boolean enabled) { throw new UnsupportedOperationException(); } @Override public void enableStatistics(String cacheName, boolean enabled) { throw new UnsupportedOperationException(); } @Override public void close() { if (closed.compareAndSet(false, true)) { cacheMap.values().forEach(Cache::close); cacheMap.clear(); } } @Override public boolean isClosed() { return closed.get(); } @Override public <T> T unwrap(Class<T> clazz) { if (clazz.isAssignableFrom(this.getClass())) { return clazz.cast(this); } throw new IllegalArgumentException(); } private void exceptionIfClosed() { if (closed.get()) { throw new IllegalStateException("CacheManager is closed."); } } }
phax/ph-css
ph-css/src/test/java/com/helger/css/tools/MediaQueryToolsTest.java
/* * Copyright (C) 2014-2021 <NAME> (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.css.tools; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import org.junit.Test; import com.helger.css.ECSSVersion; import com.helger.css.decl.CSSMediaQuery; import com.helger.css.decl.CascadingStyleSheet; import com.helger.css.reader.CSSReader; import com.helger.css.writer.CSSWriter; /** * Test class for class {@link MediaQueryTools}. * * @author <NAME> */ public final class MediaQueryToolsTest { private static final ECSSVersion s_eVersion = ECSSVersion.CSS30; @Test public void testParseMediaQuery () { List <CSSMediaQuery> aMQs = MediaQueryTools.parseToMediaQuery ("screen", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("screen and (color)", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("not screen and (color)", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("only screen and (color)", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("screen and (color), projection and (color)", s_eVersion); assertNotNull (aMQs); assertEquals (2, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("aural and (device-aspect-ratio: 16/9)", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("speech and (min-device-width: 800px)", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("screen and (max-weight: 3kg) and (color), (color)", s_eVersion); assertNotNull (aMQs); assertEquals (2, aMQs.size ()); aMQs = MediaQueryTools.parseToMediaQuery ("print and (min-width: 25cm)", s_eVersion); assertNotNull (aMQs); assertEquals (1, aMQs.size ()); } @Test public void testGetWrapped () { // Read and arbitrary CSS final CascadingStyleSheet aBaseCSS = CSSReader.readFromString ("p { color:red;}", s_eVersion); assertNotNull (aBaseCSS); // Create structured media queries final List <CSSMediaQuery> aMQs = MediaQueryTools.parseToMediaQuery ("screen", s_eVersion); assertNotNull (aMQs); // Wrap the source CSS with the specified media queries final CascadingStyleSheet aWrappedCSS = MediaQueryTools.getWrappedInMediaQuery (aBaseCSS, aMQs, false); assertNotNull (aWrappedCSS); assertEquals ("@media screen{p{color:red}}", new CSSWriter (s_eVersion, true).getCSSAsString (aWrappedCSS)); } }
adzai/Network-Simulator
src/cz/praguecityuniversity/NetworkAdapter.java
package cz.praguecityuniversity; /** * Network Adapter that is a component of devices' internal hardware */ abstract class NetworkAdapter extends Entity { Device device; NetworkAdapter(Device device, TypeofEntity typeofEntity) { super(typeofEntity); this.device = device; } }
NunoEdgarGFlowHub/NemCommunityClient
nem-client-api/src/test/java/org/nem/ncc/controller/viewmodels/HarvestInfoViewModelTest.java
<gh_stars>10-100 package org.nem.ncc.controller.viewmodels; import net.minidev.json.JSONObject; import org.hamcrest.core.IsEqual; import org.junit.*; import org.nem.core.model.ncc.HarvestInfo; import org.nem.core.model.primitive.*; import org.nem.core.serialization.JsonSerializer; import org.nem.core.time.*; public class HarvestInfoViewModelTest { @Test public void viewModelCanBeCreated() { // Arrange: final HarvestInfo model = new HarvestInfo(123L, new BlockHeight(84), new TimeInstant(12), Amount.fromNem(7), 98765L); // Act: final HarvestInfoViewModel viewModel = new HarvestInfoViewModel(model); // Assert: Assert.assertThat(viewModel.getId(), IsEqual.equalTo(123L)); Assert.assertThat(viewModel.getBlockHeight(), IsEqual.equalTo(new BlockHeight(84))); Assert.assertThat(viewModel.getTimeStamp(), IsEqual.equalTo(new TimeInstant(12))); Assert.assertThat(viewModel.getTotalFee(), IsEqual.equalTo(Amount.fromNem(7))); Assert.assertThat(viewModel.getDifficulty(), IsEqual.equalTo(98765L)); } @Test public void viewModelCanBeSerialized() { // Arrange: final HarvestInfo model = new HarvestInfo(123L, new BlockHeight(84), new TimeInstant(12), Amount.fromNem(7), 98765L); final HarvestInfoViewModel viewModel = new HarvestInfoViewModel(model); // Act: final JSONObject jsonObject = JsonSerializer.serializeToJson(viewModel); // Assert: Assert.assertThat(jsonObject.size(), IsEqual.equalTo(6)); Assert.assertThat(jsonObject.get("id"), IsEqual.equalTo(123L)); Assert.assertThat(jsonObject.get("message"), IsEqual.equalTo("Block #84")); Assert.assertThat(jsonObject.get("timeStamp"), IsEqual.equalTo(SystemTimeProvider.getEpochTimeMillis() + 12000)); Assert.assertThat(jsonObject.get("fee"), IsEqual.equalTo(7000000L)); Assert.assertThat(jsonObject.get("height"), IsEqual.equalTo(84L)); Assert.assertThat(jsonObject.get("difficulty"), IsEqual.equalTo(98765L)); } }
ckclark/leetcode
py/predict-the-winner.py
<reponame>ckclark/leetcode class Solution(object): def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ dp = dict() def top_down(start, end): if start == end: dp[start, end] = 0 elif (start, end) not in dp: dp[start, end] = max(nums[start] - top_down(start + 1, end), nums[end - 1] - top_down(start, end - 1)) return dp[start, end] return top_down(0, len(nums)) >= 0
WAng91An/Blog
src/main/java/com/wrq/mapper/CategoryMapper.java
<reponame>WAng91An/Blog<gh_stars>1-10 package com.wrq.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.wrq.vo.CategoryVo; import com.wrq.pojo.Category; /** * todo:分类 * Category * 创建人:王瑞乾 * 时间:2019年02月03日 15:55:04 * @version 1.0.0 * */ public interface CategoryMapper { //添加 public int saveCategory(Category category); //修改 public int updateCategory(Category category); //删除 public int deleteCategoryById(@Param("id")Integer id); //查询单个 public Category getCategoryById(@Param("id")Integer id); //查询所有 public List<Category> queryCategoryAll(CategoryVo categoryVo); }
benoitkugler/webrender
svg/paint.go
package svg import ( "fmt" "strings" "github.com/benoitkugler/webrender/backend" "github.com/benoitkugler/webrender/css/parser" "github.com/benoitkugler/webrender/matrix" "github.com/benoitkugler/webrender/text" "github.com/benoitkugler/webrender/utils" ) // handle painter for fill and stroke values // painter is either a simple RGBA color, // or a reference to a more complex `paintServer` type painter struct { // value of the url attribute, refering // to a paintServer element refID string color parser.RGBA // if 'false', no painting occurs (not the same as black) valid bool } // parse a fill or stroke attribute func newPainter(attr string) (painter, error) { attr = strings.TrimSpace(attr) if attr == "" || attr == "none" { return painter{}, nil } var out painter if strings.HasPrefix(attr, "url(") { if i := strings.IndexByte(attr, ')'); i != -1 { out.refID = parseURLFragment(attr[:i]) attr = attr[i+1:] // skip the ) } else { return out, fmt.Errorf("invalid url in color '%s'", attr) } } color := parser.ParseColorString(attr) // currentColor has been resolved during tree building out.color = color.RGBA out.valid = true return out, nil } // ensure that v is positive and equal to offset modulo total func clampModulo(offset, total Fl) Fl { if offset < 0 { // shift to [0, dashesLength] offset = -offset quotient := utils.Floor(offset / total) remainder := offset - quotient*total return total - remainder } return offset } func (dims drawingDims) resolveDashes(dashArray []Value, dashOffset Value) ([]Fl, Fl) { dashes := make([]Fl, len(dashArray)) var dashesLength Fl for i, v := range dashArray { dashes[i] = dims.length(v) if dashes[i] < 0 { return nil, 0 } dashesLength += dashes[i] } if dashesLength == 0 { return nil, 0 } offset := dims.length(dashOffset) offset = clampModulo(offset, dashesLength) return dashes, offset } func (svg *SVGImage) setupPaint(dst backend.Canvas, node *svgNode, dims drawingDims) (doFill, doStroke bool) { strokeWidth := dims.length(node.strokeWidth) doFill = node.fill.valid doStroke = node.stroke.valid && strokeWidth > 0 // fill if doFill { svg.applyPainter(dst, node, node.fill, node.fillOpacity, dims, false) } // stroke if doStroke { svg.applyPainter(dst, node, node.stroke, node.strokeOpacity, dims, true) // stroke options dashes, offset := dims.resolveDashes(node.dashArray, node.dashOffset) dst.State().SetDash(dashes, offset) dst.State().SetLineWidth(strokeWidth) dst.State().SetStrokeOptions(node.strokeOptions) } return } func newPaintOp(fill, stroke, evenOdd bool) backend.PaintOp { var op backend.PaintOp if fill { if evenOdd { op |= backend.FillEvenOdd } else { op |= backend.FillNonZero } } if stroke { op |= backend.Stroke } return op } // apply the given painter to the given node, outputing the // the result in `dst` // opacity is an additional opacity factor func (svg *SVGImage) applyPainter(dst backend.Canvas, node *svgNode, pt painter, opacity Fl, dims drawingDims, stroke bool) { if !pt.valid { return } // check for a paintServer if ps := svg.definitions.paintServers[pt.refID]; ps != nil { wasPainted := ps.paint(dst, node, opacity, dims, svg.textContext, stroke) if wasPainted { return } // else default to a plain color } pt.color.A *= opacity // apply the opacity factor dst.State().SetColorRgba(pt.color, stroke) } // gradient or pattern type paintServer interface { // setup the "color" for the given `node` paint(dst backend.Canvas, node *svgNode, opacity Fl, dims drawingDims, textContext text.TextLayoutContext, stroke bool) bool } // either linear or radial type gradientKind interface { isGradient() } func (gradientLinear) isGradient() {} func (gradientRadial) isGradient() {} type gradientLinear struct { x1, y1, x2, y2 Value } func newGradientLinear(node *cascadedNode) (out gradientLinear, err error) { out.x1, err = parseValue(node.attrs["x1"]) if err != nil { return out, err } out.y1, err = parseValue(node.attrs["y1"]) if err != nil { return out, err } out.x2, err = parseValue(node.attrs["x2"]) if err != nil { return out, err } out.y2, err = parseValue(node.attrs["y2"]) if err != nil { return out, err } // default values if out.x2.U == 0 { out.x2 = Value{100, Perc} // 100% } return out, nil } type gradientRadial struct { // if fx or fy are empty, they should default to // the resolved values of cx and cy cx, cy, r, fx, fy, fr Value } func newGradientRadial(node *cascadedNode) (out gradientRadial, err error) { cx, cy, r := node.attrs["cx"], node.attrs["cy"], node.attrs["r"] if cx == "" { cx = "50%" } if cy == "" { cy = "50%" } if r == "" { r = "50%" } fx, fy, fr := node.attrs["fx"], node.attrs["fy"], node.attrs["fr"] out.cx, err = parseValue(cx) if err != nil { return out, err } out.cy, err = parseValue(cy) if err != nil { return out, err } out.r, err = parseValue(r) if err != nil { return out, err } out.fx, err = parseValue(fx) if err != nil { return out, err } out.fy, err = parseValue(fy) if err != nil { return out, err } out.fr, err = parseValue(fr) if err != nil { return out, err } return out, nil } // gradient specification, prior to resolving units type gradient struct { kind gradientKind spreadMethod GradientSpread // default to NoRepeat positions []Value colors []parser.RGBA transforms []transform isUnitsUserSpace bool } // parse a linearGradient or radialGradient node func newGradient(node *cascadedNode) (out gradient, err error) { out.positions = make([]Value, len(node.children)) out.colors = make([]parser.RGBA, len(node.children)) for i, child := range node.children { out.positions[i], err = parseValue(child.attrs["offset"]) if err != nil { return out, err } sc, has := child.attrs["stop-color"] if !has { sc = "black" } stopColor := parser.ParseColorString(sc).RGBA stopColor.A, err = parseOpacity(child.attrs["stop-opacity"]) if err != nil { return out, err } out.colors[i] = stopColor } out.isUnitsUserSpace = node.attrs["gradientUnits"] == "userSpaceOnUse" switch node.attrs["spreadMethod"] { case "repeat": out.spreadMethod = Repeat case "reflect": out.spreadMethod = Reflect // default NoRepeat } out.transforms, err = parseTransform(node.attrs["gradientTransform"]) if err != nil { return out, err } switch node.tag { case "linearGradient": out.kind, err = newGradientLinear(node) if err != nil { return out, fmt.Errorf("invalid linear gradient: %s", err) } case "radialGradient": out.kind, err = newGradientRadial(node) if err != nil { return out, fmt.Errorf("invalid radial gradient: %s", err) } default: panic("unexpected node tag " + node.tag) } return out, nil } func (gr gradient) paint(dst backend.Canvas, node *svgNode, opacity Fl, dims drawingDims, textContext text.TextLayoutContext, stroke bool) bool { if len(gr.colors) == 0 { return false } if len(gr.colors) == 1 { // actually solid dst.State().SetColorRgba(gr.colors[0], stroke) return true } bbox, ok := node.resolveBoundingBox(dims, stroke) if !ok { return false } x, y := bbox.X, bbox.Y width, height := bbox.Width, bbox.Height if gr.isUnitsUserSpace { width, height = dims.innerWidth, dims.innerHeight } // resolve positions values positions := make([]Fl, len(gr.positions)) var previousPos Fl for i, p := range gr.positions { pos := p.Resolve(dims.fontSize, 1) positions[i] = utils.MaxF(pos, previousPos) // ensure positions is increasing previousPos = pos } colors := append([]parser.RGBA(nil), gr.colors...) switch gr.spreadMethod { case Repeat, Reflect: if positions[0] > 0 { positions = append([]Fl{0}, positions...) colors = append([]parser.RGBA{colors[0]}, colors...) } if positions[len(positions)-1] < 1 { positions = append(positions, 1) colors = append(colors, colors[len(colors)-1]) } default: // Add explicit colors at boundaries if needed, because PDF doesn’t // extend color stops that are not displayed if positions[0] == positions[1] { if _, isRadial := gr.kind.(gradientRadial); isRadial { // avoid negative radius for radial gradients positions = append([]Fl{0}, positions...) } else { positions = append([]Fl{positions[0] - 1}, positions...) } colors = append([]parser.RGBA{colors[0]}, colors...) } if L := len(positions); positions[L-2] == positions[L-1] { positions = append(positions, positions[L-1]+1) colors = append(colors, colors[len(colors)-1]) } } var laidOutGradient backend.GradientLayout mt := matrix.Translation(x, y) switch kind := gr.kind.(type) { case gradientLinear: x1 := kind.x1.Resolve(dims.fontSize, 1) y1 := kind.y1.Resolve(dims.fontSize, 1) x2 := kind.x2.Resolve(dims.fontSize, 1) y2 := kind.y2.Resolve(dims.fontSize, 1) if gr.isUnitsUserSpace { x1 -= x y1 -= y x2 -= x y2 -= y } else { length := utils.MinF(width, height) x1 *= length y1 *= length x2 *= length y2 *= length // update the transformation matrix var a, d Fl = 1, 1 if height < width { a = width / height } else { d = height / width } mt.LeftMultBy(matrix.Scaling(a, d)) } dx, dy := x2-x1, y2-y1 vectorLength := utils.Hypot(dx, dy) laidOutGradient = gr.spreadMethod.LinearGradient(positions, colors, x1, y1, dx, dy, vectorLength) case gradientRadial: cx := kind.cx.Resolve(dims.fontSize, 1) cy := kind.cy.Resolve(dims.fontSize, 1) r := kind.r.Resolve(dims.fontSize, 1) fx, fy := cx, cy if kind.fx.U != 0 { fx = kind.fx.Resolve(dims.fontSize, width) } if kind.fy.U != 0 { fy = kind.fy.Resolve(dims.fontSize, height) } fr := kind.fr.Resolve(dims.fontSize, 1) if gr.isUnitsUserSpace { cx -= x cy -= y fx -= x fy -= y } else { length := utils.MinF(width, height) cx *= length cy *= length r *= length fx *= length fy *= length fr *= length // update the transformation matrix var a, d Fl = 1, 1 if height < width { a = width / height } else { d = height / width } mt.RightMultBy(matrix.Scaling(a, d)) } laidOutGradient = gr.spreadMethod.RadialGradient(positions, colors, fx, fy, fr, cx, cy, r, width, height) } laidOutGradient.Reapeating = gr.spreadMethod != NoRepeat if trs := gr.transforms; len(trs) != 0 { mat := aggregateTransforms(trs, dims.fontSize, dims.normalizedDiagonal) mt.LeftMultBy(mat) } if laidOutGradient.Kind == "solid" { dst.Rectangle(0, 0, width, height) dst.State().SetColorRgba(laidOutGradient.Colors[0], false) dst.Paint(backend.FillNonZero) return true } pattern := dst.NewGroup(0, 0, width, height) pattern.DrawGradient(laidOutGradient, dims.concreteWidth, dims.concreteHeight) dst.State().SetColorPattern(pattern, width, height, mt, stroke) return true } // pattern is a container for shapes to be used as // fill or stroke color type pattern struct { svgNode isUnitsUserSpace bool // patternUnits isContentUnitsBBox bool // patternContentUnits } func newPattern(node *cascadedNode, children []*svgNode) (out pattern, err error) { out.children = children out.isUnitsUserSpace = node.attrs["patternUnits"] == "userSpaceOnUse" out.isContentUnitsBBox = node.attrs["patternContentUnits"] == "objectBoundingBox" err = node.attrs.parseCommonAttributes(&out.attributes) if err != nil { return out, fmt.Errorf("parsing pattern element: %s", err) } return out, nil } func (pt pattern) paint(dst backend.Canvas, node *svgNode, opacity Fl, dims drawingDims, textContext text.TextLayoutContext, stroke bool) bool { bbox, ok := node.resolveBoundingBox(dims, stroke) if !ok { return false } mat := matrix.Translation(bbox.X, bbox.Y) var patternWidth, patternHeight Fl if pt.isUnitsUserSpace { patternWidth = pt.width.Resolve(dims.fontSize, 1) patternHeight = pt.height.Resolve(dims.fontSize, 1) } else { width, height := bbox.Width, bbox.Height if pt.width.V == 0 { pt.width = Value{U: Px, V: 1} } if pt.height.V == 0 { pt.height = Value{U: Px, V: 1} } patternWidth = pt.width.Resolve(dims.fontSize, 1) * width patternHeight = pt.height.Resolve(dims.fontSize, 1) * height if pt.viewbox == nil { pt.box.width = Value{U: Px, V: patternWidth} pt.box.height = Value{U: Px, V: patternHeight} if pt.isContentUnitsBBox { pt.transforms = []transform{{kind: scale, args: [6]Value{ {U: Px, V: width}, {U: Px, V: height}, }}} } } } // Fail if pattern has an invalid size if patternWidth == 0 || patternHeight == 0 { return false } tr := aggregateTransforms(pt.transforms, dims.fontSize, dims.innerDiagonal) mat.RightMultBy(tr) // draw the pattern content on the temporary target pat := dst.NewGroup(0, 0, patternWidth, patternHeight) pat.State().SetColorRgba(parser.RGBA{A: opacity}, false) patSVG := SVGImage{root: &pt.svgNode} patSVG.Draw(pat, patternWidth, patternHeight, textContext) // apply the pattern dst.State().SetColorPattern(pat, patternWidth, patternHeight, mat, stroke) return true }
Grosskopf/openoffice
main/svtools/source/control/urlcontrol.cxx
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/urlcontrol.hxx> #include "svl/filenotation.hxx" //......................................................................... namespace svt { //......................................................................... //===================================================================== //= OFileURLControl //===================================================================== //--------------------------------------------------------------------- OFileURLControl::OFileURLControl(Window* _pParent) :SvtURLBox(_pParent, INET_PROT_FILE) { DisableHistory(); } //--------------------------------------------------------------------- OFileURLControl::OFileURLControl(Window* _pParent, const ResId& _rId) :SvtURLBox(_pParent, _rId, INET_PROT_FILE) { DisableHistory(); } //--------------------------------------------------------------------- long OFileURLControl::PreNotify( NotifyEvent& _rNEvt ) { if (GetSubEdit() == _rNEvt.GetWindow()) if (EVENT_KEYINPUT == _rNEvt.GetType()) if (KEY_RETURN == _rNEvt.GetKeyEvent()->GetKeyCode().GetCode()) if (IsInDropDown()) m_sPreservedText = GetURL(); return SvtURLBox::PreNotify(_rNEvt); } //--------------------------------------------------------------------- long OFileURLControl::Notify( NotifyEvent& _rNEvt ) { if (GetSubEdit() == _rNEvt.GetWindow()) if (EVENT_KEYINPUT == _rNEvt.GetType()) if (KEY_RETURN == _rNEvt.GetKeyEvent()->GetKeyCode().GetCode()) if (IsInDropDown()) { long nReturn = SvtURLBox::Notify(_rNEvt); // build a system dependent (thus more user readable) file name OFileNotation aTransformer(m_sPreservedText, OFileNotation::N_URL); SetText(aTransformer.get(OFileNotation::N_SYSTEM)); Modify(); // Update the pick list UpdatePickList(); return nReturn; } return SvtURLBox::Notify(_rNEvt); } //......................................................................... } // namespace svt //.........................................................................
kjthegod/chromium
android_webview/javatests/src/org/chromium/android_webview/test/StandaloneAwQuotaManagerBridgeTest.java
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.android_webview.test; import org.chromium.android_webview.AwContents; import org.chromium.android_webview.AwQuotaManagerBridge; import org.chromium.android_webview.test.util.AwQuotaManagerBridgeTestUtil; /** * This class tests AwQuotaManagerBridge runs without AwContents etc. It simulates * use case that user calls WebStorage getInstance() without WebView. */ public class StandaloneAwQuotaManagerBridgeTest extends AwTestBase { public void testStartup() throws Exception { // AwQuotaManager should run without any issue. AwQuotaManagerBridge.Origins origins = AwQuotaManagerBridgeTestUtil.getOrigins(this); assertEquals(origins.mOrigins.length, 0); assertEquals(AwContents.getNativeInstanceCount(), 0); } }
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
platform/main/server-4q/com/cyc/cycjava/cycl/quirk/quirk_trampolines.java
<gh_stars>1-10 package com.cyc.cycjava.cycl.quirk; import static com.cyc.cycjava.cycl.access_macros.register_external_symbol; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeSymbol; import static com.cyc.tool.subl.util.SubLFiles.declareFunction; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObject; import com.cyc.tool.subl.jrtl.nativeCode.type.symbol.SubLSymbol; import com.cyc.tool.subl.util.SubLFile; import com.cyc.tool.subl.util.SubLTranslatedFile; public final class quirk_trampolines extends SubLTranslatedFile { public static final SubLFile me = new quirk_trampolines(); public static final String myName = "com.cyc.cycjava.cycl.quirk.quirk_trampolines"; public static final String myFingerPrint = "cea4b21512cb02c6b0e636ec47052283a9d6e8881ae5d18068dc1484c813cd83"; // Internal Constants public static final SubLSymbol GET_PASSAGES_FOR_ENTITY = makeSymbol("GET-PASSAGES-FOR-ENTITY"); public static final SubLSymbol RETURN_DOCUMENT_AS_STRING = makeSymbol("RETURN-DOCUMENT-AS-STRING"); public static final SubLSymbol TOPICS_RELATED_TO_ENTITY = makeSymbol("TOPICS-RELATED-TO-ENTITY"); public static final SubLSymbol ANSWER_GUI_QUESTION = makeSymbol("ANSWER-GUI-QUESTION"); public static final SubLSymbol IDENTIFY_ALL_GEQ_ENTITIES = makeSymbol("IDENTIFY-ALL-GEQ-ENTITIES"); public static final SubLSymbol GET_FOLLOWUPS_FOR_ENTITY = makeSymbol("GET-FOLLOWUPS-FOR-ENTITY"); public static SubLObject get_passages_for_entity(final SubLObject entity_name) { return quirk_java_gui.get_passages_for_entity_int(entity_name); } public static SubLObject return_document_as_string(final SubLObject passage_doc_id) { return quirk_java_gui.return_document_as_string_int(passage_doc_id); } public static SubLObject topics_related_to_entity(final SubLObject entity_name) { return quirk_java_gui.topics_related_to_entity_int(entity_name); } public static SubLObject answer_gui_question(final SubLObject question_string) { return quirk_java_gui.answer_gui_question_int(question_string); } public static SubLObject identify_all_geq_entities(final SubLObject geq_string) { return quirk_java_gui.identify_all_geq_entities_int(geq_string); } public static SubLObject get_followups_for_entity(final SubLObject entity_name) { return quirk_java_gui.get_followups_for_entity_int(entity_name); } public static SubLObject declare_quirk_trampolines_file() { declareFunction(me, "get_passages_for_entity", "GET-PASSAGES-FOR-ENTITY", 1, 0, false); declareFunction(me, "return_document_as_string", "RETURN-DOCUMENT-AS-STRING", 1, 0, false); declareFunction(me, "topics_related_to_entity", "TOPICS-RELATED-TO-ENTITY", 1, 0, false); declareFunction(me, "answer_gui_question", "ANSWER-GUI-QUESTION", 1, 0, false); declareFunction(me, "identify_all_geq_entities", "IDENTIFY-ALL-GEQ-ENTITIES", 1, 0, false); declareFunction(me, "get_followups_for_entity", "GET-FOLLOWUPS-FOR-ENTITY", 1, 0, false); return NIL; } public static SubLObject init_quirk_trampolines_file() { return NIL; } public static SubLObject setup_quirk_trampolines_file() { register_external_symbol(GET_PASSAGES_FOR_ENTITY); register_external_symbol(RETURN_DOCUMENT_AS_STRING); register_external_symbol(TOPICS_RELATED_TO_ENTITY); register_external_symbol(ANSWER_GUI_QUESTION); register_external_symbol(IDENTIFY_ALL_GEQ_ENTITIES); register_external_symbol(GET_FOLLOWUPS_FOR_ENTITY); return NIL; } @Override public void declareFunctions() { declare_quirk_trampolines_file(); } @Override public void initializeVariables() { init_quirk_trampolines_file(); } @Override public void runTopLevelForms() { setup_quirk_trampolines_file(); } } /** * Total time: 64 ms */
SanjanaAnaokar/Helping-Hands
Helpinghands/EcoSystem/src/Business/WorkQueue/AdopterWorkRequest.java
<filename>Helpinghands/EcoSystem/src/Business/WorkQueue/AdopterWorkRequest.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Business.WorkQueue; /** * * @author sanja */ public class AdopterWorkRequest extends WorkRequest { private String bgcStatus; private String financeStatus; public String getBgcStatus() { return bgcStatus; } public void setBgcStatus(String bgcStatus) { this.bgcStatus = bgcStatus; } public String getFinanceStatus() { return financeStatus; } public void setFinanceStatus(String financeStatus) { this.financeStatus = financeStatus; } }
bam241/FRENSIE
packages/utility/core/src/Utility_TypeNameTraits.hpp
<reponame>bam241/FRENSIE<filename>packages/utility/core/src/Utility_TypeNameTraits.hpp //---------------------------------------------------------------------------// //! //! \file Utility_TypeNameTraits.hpp //! \author <NAME> //! \brief Type name traits class specializations //! //---------------------------------------------------------------------------// #ifndef UTILITY_TYPE_NAME_TRAITS_HPP #define UTILITY_TYPE_NAME_TRAITS_HPP // Std Lib Includes #include <string> #include <complex> // Boost Includes #include <boost/units/quantity.hpp> // FRENSIE Includes #include "Utility_TypeNameTraitsDecl.hpp" #include "Utility_TypeTraits.hpp" #include "Utility_ToStringTraits.hpp" #include "Utility_UnitTraits.hpp" namespace boost{ namespace archive{ class xml_oarchive; class xml_iarchive; class text_oarchive; class text_iarchive; class binary_oarchive; class binary_iarchive; class polymorphic_oarchive; class polymorphic_iarchive; } // end archive namespace } // end boost namespace namespace Utility{ TYPE_NAME_TRAITS_QUICK_DECL( void ); TYPE_NAME_TRAITS_QUICK_DECL( void* ); TYPE_NAME_TRAITS_QUICK_DECL( float ); TYPE_NAME_TRAITS_QUICK_DECL( double ); TYPE_NAME_TRAITS_QUICK_DECL( long double ); TYPE_NAME_TRAITS_QUICK_DECL( bool ); TYPE_NAME_TRAITS_QUICK_DECL( char ); TYPE_NAME_TRAITS_QUICK_DECL( unsigned char ); TYPE_NAME_TRAITS_QUICK_DECL( signed char ); TYPE_NAME_TRAITS_QUICK_DECL( wchar_t ); TYPE_NAME_TRAITS_QUICK_DECL( short ); TYPE_NAME_TRAITS_QUICK_DECL( unsigned short ); TYPE_NAME_TRAITS_QUICK_DECL( int ); TYPE_NAME_TRAITS_QUICK_DECL( unsigned int ); TYPE_NAME_TRAITS_QUICK_DECL( long int ); TYPE_NAME_TRAITS_QUICK_DECL( unsigned long int ); TYPE_NAME_TRAITS_QUICK_DECL( long long int ); TYPE_NAME_TRAITS_QUICK_DECL( unsigned long long int ); TYPE_NAME_TRAITS_QUICK_DECL( std::complex<float> ); TYPE_NAME_TRAITS_QUICK_DECL( std::complex<double> ); TYPE_NAME_TRAITS_QUICK_DECL( std::string ); TYPE_NAME_TRAITS_QUICK_DECL( std::wstring ); /*! \brief Partial specialization of Utility::TypeNameTraits for * std::integral_constant types * \ingroup type_name_traits */ template<typename T, T v> struct TypeNameTraits<std::integral_constant<T,v> > { //! Check if the type has a specialization typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return Utility::toString( v ); } }; /*! \brief Partial specialization of Utility::TypeNameTraits for * boost::units::unit types * \ingroup type_name_traits */ template<typename Dim, typename Sys> struct TypeNameTraits<boost::units::unit<Dim,Sys> > { //! Check if the type has a specialization typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return Utility::UnitTraits<boost::units::unit<Dim,Sys> >::name(); } }; /*! \brief Partial specialization of Utility::TypeNameTraits for * boost::units::quantity types * \ingroup type_name_traits */ template<typename Unit, typename T> struct TypeNameTraits<boost::units::quantity<Unit,T> > { //! Check if the type has a specialization typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return std::string("boost::units::quantity<") + Utility::UnitTraits<Unit>::symbol() + "," + TypeNameTraits<T>::name() +">"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::xml_oarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::xml_oarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::xml_oarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::xml_iarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::xml_iarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::xml_iarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::text_oarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::text_oarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::text_oarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::text_iarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::text_iarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::text_iarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::binary_oarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::binary_oarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::binary_oarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::binary_iarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::binary_iarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::binary_iarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::polymorphic_oarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::polymorphic_oarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::polymorphic_oarchive"; } }; /*! \brief Specialization of Utility::TypeNameTraits for * boost::archive::polymorphic_iarchive * \ingroup type_name_traits */ template<> struct TypeNameTraits<boost::archive::polymorphic_iarchive> { typedef std::true_type IsSpecialized; //! Get the type name static inline std::string name() { return "boost::archive::polymorphic_iarchive"; } }; /*! Partial specialization of Utility::TypeNameTraits for const types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<std::is_const<T>::value && !std::is_volatile<T>::value && !std::is_pointer<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_const<T>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return std::string("const ") + TypeNameTraits<typename std::remove_const<T>::type>::name(); } }; /*! Partial specialization of Utility::TypeNameTraits for volatile types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<!std::is_const<T>::value && std::is_volatile<T>::value && !std::is_pointer<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_volatile<T>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return std::string("volatile ") + TypeNameTraits<typename std::remove_volatile<T>::type>::name(); } }; /*! Partial specialization of Utility::TypeNameTraits for const volatile types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T, typename std::enable_if<std::is_const<T>::value && std::is_volatile<T>::value && !std::is_pointer<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_cv<T>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return std::string("const volatile ") + TypeNameTraits<typename std::remove_cv<T>::type>::name(); } }; /*! Partial specialization of Utility::TypeNameTraits for pointer types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<!std::is_const<T>::value && !std::is_volatile<T>::value && std::is_pointer<T>::value && !IsPointerToConst<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_pointer<T>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return TypeNameTraits<typename std::remove_pointer<T>::type>::name() + "*"; } }; /*! Partial specialization of Utility::TypeNameTraits for const pointer types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<std::is_const<T>::value && !std::is_volatile<T>::value && std::is_pointer<T>::value && !IsPointerToConst<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_pointer<T>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return TypeNameTraits<typename std::remove_pointer<T>::type>::name() + "* const"; } }; /*! \brief Partial specialization of Utility::TypeNameTraits for * pointer-to-const types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<!std::is_const<T>::value && !std::is_volatile<T>::value && std::is_pointer<T>::value && IsPointerToConst<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_const<typename std::remove_pointer<T>::type>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return std::string("const ")+TypeNameTraits<typename std::remove_const<typename std::remove_pointer<T>::type>::type>::name()+"*"; } }; /*! \brief Partial specialization of Utility::TypeNameTraits for * const pointer-to-const types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<std::is_const<T>::value && !std::is_volatile<T>::value && std::is_pointer<T>::value && IsPointerToConst<T>::value && !std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_const<typename std::remove_pointer<T>::type>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return std::string("const ")+TypeNameTraits<typename std::remove_const<typename std::remove_pointer<T>::type>::type>::name()+"* const"; } }; /*! Partial specialization of Utility::TypeNameTraits for reference types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<!std::is_const<T>::value && !std::is_volatile<T>::value && !std::is_pointer<T>::value && std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_reference<T>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return TypeNameTraits<typename std::remove_reference<T>::type>::name() + "&"; } }; /*! Partial specialization of Utility::TypeNameTraits for const reference types * \ingroup type_name_traits */ template<typename T> struct TypeNameTraits<T,typename std::enable_if<std::is_const<T>::value && !std::is_volatile<T>::value && !std::is_pointer<T>::value && std::is_reference<T>::value>::type> { //! Check if the type has a specialization typedef typename TypeNameTraits<typename std::remove_const<typename std::remove_reference<T>::type>::type>::IsSpecialized IsSpecialized; //! Get the type name static inline std::string name() { return std::string("const ")+TypeNameTraits<typename std::remove_const<typename std::remove_reference<T>::type>::type>::name()+"&"; } }; namespace Details{ /*! The type name parameter pack helper class * \ingroup type_name_traits */ template<typename... Types> struct TypeNameParameterPackHelper; /*! \brief Partial specialization of the TypeNameParameterPackHelper class for * a single template parameter * \ingroup type_name_traits */ template<typename T> struct TypeNameParameterPackHelper<T> { //! Append the type name to the end of the string static void appendName( std::string& parameter_pack_name ) { parameter_pack_name += Utility::TypeNameTraits<T>::name(); } }; /*! \brief Partial specialization of the TypeNameParameterPackHelper class for * peeling off the first parameter * \ingroup type_name_traits */ template<typename T, typename... Types> struct TypeNameParameterPackHelper<T,Types...> { //! Append all type names to the end of the string static void appendName( std::string& parameter_pack_name ) { parameter_pack_name += Utility::TypeNameTraits<T>::name(); parameter_pack_name += ","; TypeNameParameterPackHelper<Types...>::appendName( parameter_pack_name ); } }; } // end Details namespace // Return the type name template<typename T> inline std::string typeName() { return Utility::TypeNameTraits<T>::name(); } // Return the type name template<typename... Types> inline typename std::enable_if<(sizeof...(Types)>1),std::string>::type typeName() { std::string parameter_pack_name; Details::TypeNameParameterPackHelper<Types...>::appendName( parameter_pack_name ); return parameter_pack_name; } } // end Utility namespace #endif // end UTILITY_TYPE_NAME_TRAITS_HPP //---------------------------------------------------------------------------// // end Utility_TypeNameTraits.hpp //---------------------------------------------------------------------------//
Alf-Melmac/slotbotServer
src/main/java/de/webalf/slotbot/assembler/api/EventApiAssembler.java
<reponame>Alf-Melmac/slotbotServer package de.webalf.slotbot.assembler.api; import de.webalf.slotbot.assembler.EventTypeAssembler; import de.webalf.slotbot.assembler.UserAssembler; import de.webalf.slotbot.controller.website.EventWebController; import de.webalf.slotbot.model.Event; import de.webalf.slotbot.model.User; import de.webalf.slotbot.model.dtos.api.EventApiDto; import de.webalf.slotbot.model.dtos.api.EventApiViewDto; import de.webalf.slotbot.model.dtos.api.EventRecipientApiDto; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; import java.time.LocalDateTime; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; /** * @author Alf * @since 04.11.2020 */ @Component @RequiredArgsConstructor(onConstructor_ = @Autowired) public final class EventApiAssembler { private final SquadApiAssembler squadApiAssembler; public static EventApiDto toDto(@NonNull Event event) { LocalDateTime dateTime = event.getDateTime(); return EventApiDto.builder() .url(getUrl(event.getId())) .id(event.getId()) .hidden(event.isHidden()) .shareable(event.isShareable()) .name(event.getName()) .date(dateTime.toLocalDate()) .startTime(dateTime.toLocalTime()) .creator(event.getCreator()) .eventType(EventTypeAssembler.toDto(event.getEventType())) .description(event.getDescription()) .missionType(event.getMissionType()) .missionLength(event.getMissionLength()) .pictureUrl(event.getPictureUrl()) .details(EventFieldApiAssembler.toDtoList(event.getDetails())) .squadList(SquadApiAssembler.toDtoList(event.getSquadList())) .reserveParticipating(event.getReserveParticipating()) .ownerGuild(Long.toString(event.getOwnerGuild())) .build(); } /** * To be used if a recipient must be defined */ public static EventRecipientApiDto toActionDto(Event event, User recipient) { EventRecipientApiDto eventRecipientApiDto = EventRecipientApiDto.builder().recipient(UserAssembler.toDto(recipient)).build(); ReflectionUtils.shallowCopyFieldState(toDto(event), eventRecipientApiDto); return eventRecipientApiDto; } public EventApiViewDto toViewDto(Event event) { return EventApiViewDto.builder() .id(event.getId()) .name(event.getName()) .dateTime(event.getDateTime()) .squadList(squadApiAssembler.toViewDtoList(event.getSquadList())) .url(getUrl(event.getId())) .build(); } private static String getUrl(long eventId) { return linkTo(methodOn(EventWebController.class).getEventDetailsHtml(eventId)).toUri().toString(); } }
lifansama/xposed_art_n
test/140-field-packing/src/GapOrderBase.java
/* * Copyright (C) 2014 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. */ // Regression test for 22460222, the base class. // The field gaps order was wrong. If there were two gaps of different sizes, // and the larger one was needed, it wouldn't be found. // This class has a size of 9 bytes: 8 for object plus 1 for the field 'b'. class GapOrderBase { public byte b; }
ridictking/promo
src/main/java/com/ng/emts/christmasOffer/model/request/besrequest/OrderData.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ng.emts.christmasOffer.model.request.besrequest; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.ArrayList; /** * * @author victor.akinola */ public class OrderData implements Serializable { @Expose @SerializedName("busiOwnership") @JsonInclude(JsonInclude.Include.NON_NULL) private BusinessOwnershipData busiOwnership; @Expose @SerializedName("orderBasicInfo") @JsonInclude(JsonInclude.Include.NON_NULL) private OrderBasicInfoData orderBasicInfo; @Expose private ArrayList<OrderItemData> orderItem; @Expose @SerializedName("contactPersonInfo") @JsonInclude(JsonInclude.Include.NON_NULL) private ContactPersonInfoData contactPersonInfo; @Expose @SerializedName("invoiceInfo") @JsonInclude(JsonInclude.Include.NON_NULL) private InvoiceInfoData invoiceInfo; @Expose @SerializedName("businessFee") @JsonInclude(JsonInclude.Include.NON_NULL) private ArrayList<BusinessFeeFeeItemData> businessFee; @Expose @SerializedName("paymentInfo") @JsonInclude(JsonInclude.Include.NON_NULL) private PaymentInfoData paymentInfo; public BusinessOwnershipData getBusiOwnership() { return busiOwnership; } public void setBusiOwnership(BusinessOwnershipData busiOwnership) { this.busiOwnership = busiOwnership; } public OrderBasicInfoData getOrderBasicInfo() { return orderBasicInfo; } public void setOrderBasicInfo(OrderBasicInfoData orderBasicInfo) { this.orderBasicInfo = orderBasicInfo; } public ArrayList<OrderItemData> getOrderItem() { return orderItem; } public void setOrderItem(ArrayList<OrderItemData> orderItem) { this.orderItem = orderItem; } public ContactPersonInfoData getContactPersonInfo() { return contactPersonInfo; } public void setContactPersonInfo(ContactPersonInfoData contactPersonInfo) { this.contactPersonInfo = contactPersonInfo; } public InvoiceInfoData getInvoiceInfo() { return invoiceInfo; } public void setInvoiceInfo(InvoiceInfoData invoiceInfo) { this.invoiceInfo = invoiceInfo; } public ArrayList<BusinessFeeFeeItemData> getBusinessFee() { return businessFee; } public void setBusinessFee(ArrayList<BusinessFeeFeeItemData> businessFee) { this.businessFee = businessFee; } public PaymentInfoData getPaymentInfo() { return paymentInfo; } public void setPaymentInfo(PaymentInfoData paymentInfo) { this.paymentInfo = paymentInfo; } @Override public String toString() { return "OrderData{" + "busiOwnership=" + busiOwnership + ", orderBasicInfo=" + orderBasicInfo + ", orderItem=" + orderItem + ", contactPersonInfo=" + contactPersonInfo + ", invoiceInfo=" + invoiceInfo + ", businessFee=" + businessFee + ", paymentInfo=" + paymentInfo + '}'; } }
oberasoftware/jasdb
jasdb_api/src/main/java/com/oberasoftware/jasdb/api/storage/RecordResult.java
<gh_stars>10-100 /* * The JASDB software and code is Copyright protected 2011 and owned by <NAME> * * All the code and design principals in the codebase are also Copyright 2011 * protected and owned Renze de Vries. Any unauthorized usage of the code or the * design and principals as in this code is prohibited. */ package com.oberasoftware.jasdb.api.storage; import com.oberasoftware.jasdb.api.exceptions.JasDBStorageException; /** * This contains a single record result from storage. */ public interface RecordResult { /** * Gets an inputstream allowing reading of the record entity * @return The record stream * @throws JasDBStorageException If unable to stream the record */ ClonableDataStream getStream() throws JasDBStorageException; /** * The size of the record * @return The size of the record */ long getRecordSize(); /** * Returns whether a record is found * @return True if a record is found, False if not */ boolean isRecordFound(); }
fangrx/my-blog
common/src/main/java/com/nonelonely/common/utils/CustomCallable.java
package com.nonelonely.common.utils; import com.nonelonely.common.data.RunInfo; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.Callable; /** * Create by andy on 2018-12-07 13:10 */ public class CustomCallable implements Callable<RunInfo> { private String sourceCode; public CustomCallable(String sourceCode) { this.sourceCode = sourceCode; } //方案1 //@Override //public RunInfo call() throws Exception { // System.out.println("开始执行call" + LocalTime.now()); // RunInfo runInfo = new RunInfo(); // CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(sourceCode); // if (compiler.compiler()) { // runInfo.setCompilerSuccess(true); // try { // compiler.runMainMethod(); // runInfo.setRunSuccess(true); // runInfo.setRunTakeTime(compiler.getRunTakeTime()); // runInfo.setRunMessage(compiler.getRunResult()); //获取运行的时候输出内容 // } catch (Exception e) { // e.printStackTrace(); // runInfo.setRunSuccess(false); // runInfo.setRunMessage(e.getMessage()); // } // } else { // //编译失败 // runInfo.setCompilerSuccess(false); // } // runInfo.setCompilerTakeTime(compiler.getCompilerTakeTime()); // runInfo.setCompilerMessage(compiler.getCompilerMessage()); // System.out.println("call over" + LocalTime.now()); // return runInfo; //} //方案2 @Override public RunInfo call() throws Exception { RunInfo runInfo = new RunInfo(); Thread t1 = new Thread(() -> realCall(runInfo)); t1.start(); try { t1.join(3000); //等待3秒 } catch (InterruptedException e) { e.printStackTrace(); } //不管有没有正常执行完成,强制停止t1 t1.stop(); return runInfo; } private void realCall(RunInfo runInfo) { CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(sourceCode); if (compiler.compiler()) { runInfo.setCompilerSuccess(true); try { compiler.runMainMethod(); runInfo.setRunSuccess(true); runInfo.setRunTakeTime(compiler.getRunTakeTime()); runInfo.setRunMessage(compiler.getRunResult()); //获取运行的时候输出内容 } catch (InvocationTargetException e) { //反射调用异常了,是因为超时的线程被强制stop了 if ("java.lang.ThreadDeath".equalsIgnoreCase(e.getCause().toString())) { return; } } catch (Exception e) { e.printStackTrace(); runInfo.setRunSuccess(false); runInfo.setRunMessage(e.getMessage()); } } else { //编译失败 runInfo.setCompilerSuccess(false); } runInfo.setCompilerTakeTime(compiler.getCompilerTakeTime()); runInfo.setCompilerMessage(compiler.getCompilerMessage()); runInfo.setTimeOut(false); //走到这一步代表没有超时 } }
veriktig/scandium
old-external/felix/utils/src/main/java/org/apache/felix/utils/properties/Properties.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.felix.utils.properties; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilterWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.osgi.framework.BundleContext; /** * <p> * Enhancement of the standard <code>Properties</code> * managing the maintain of comments, etc. * </p> * * @author gnodet, jbonofre */ public class Properties extends AbstractMap<String, String> { /** Constant for the supported comment characters.*/ private static final String COMMENT_CHARS = "#!"; /** The list of possible key/value separators */ private static final char[] SEPARATORS = new char[] {'=', ':'}; /** The white space characters used as key/value separators. */ private static final char[] WHITE_SPACE = new char[] {' ', '\t', '\f'}; /** * The default encoding (ISO-8859-1 as specified by * http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html) */ static final String DEFAULT_ENCODING = "ISO-8859-1"; /** Constant for the platform specific line separator.*/ private static final String LINE_SEPARATOR = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return System.getProperty("line.separator"); } }); /** Constant for the radix of hex numbers.*/ private static final int HEX_RADIX = 16; /** Constant for the length of a unicode literal.*/ private static final int UNICODE_LEN = 4; private final Map<String,String> storage = new LinkedHashMap<String,String>(); private final Map<String,Layout> layout = new LinkedHashMap<String,Layout>(); private List<String> header; private List<String> footer; private File location; private InterpolationHelper.SubstitutionCallback callback; boolean substitute = true; boolean typed; public Properties() { } public Properties(File location) throws IOException { this(location, (InterpolationHelper.SubstitutionCallback) null); } public Properties(File location, BundleContext context) throws IOException { this(location, new InterpolationHelper.BundleContextSubstitutionCallback(context)); } public Properties(File location, InterpolationHelper.SubstitutionCallback callback) throws IOException { this.location = location; this.callback = callback; if(location.exists()) load(location); } public Properties(boolean substitute) { this.substitute = substitute; } public Properties(File location, boolean substitute) { this.location = location; this.substitute = substitute; } public void load(File location) throws IOException { InputStream is = new FileInputStream(location); try { load(is); } finally { is.close(); } } public void load(URL location) throws IOException { InputStream is = location.openStream(); try { load(is); } finally { is.close(); } } public void load(InputStream is) throws IOException { load(new InputStreamReader(is, DEFAULT_ENCODING)); } public void load(Reader reader) throws IOException { loadLayout(reader, false); } public void save() throws IOException { save(this.location); } public void save(File location) throws IOException { OutputStream os = new FileOutputStream(location); try { save(os); } finally { os.close(); } } public void save(OutputStream os) throws IOException { save(new OutputStreamWriter(os, DEFAULT_ENCODING)); } public void save(Writer writer) throws IOException { saveLayout(writer, typed); } /** * Store a properties into a output stream, preserving comments, special character, etc. * This method is mainly to be compatible with the java.util.Properties class. * * @param os an output stream. * @param comment this parameter is ignored as this Properties * @throws IOException If storing fails */ public void store(OutputStream os, String comment) throws IOException { this.save(os); } /** * Searches for the property with the specified key in this property list. * * @param key the property key. * @return the value in this property list with the specified key value. */ public String getProperty(String key) { return this.get(key); } /** * Searches for the property with the specified key in this property list. If the key is not found in this property * list, the default property list, and its defaults, recursively, are then checked. The method returns the default * value argument if the property is not found. * * @param key the property key. * @param defaultValue a default value. * @return The property value of the default value */ public String getProperty(String key, String defaultValue) { if (this.get(key) != null) return this.get(key); return defaultValue; } @Override public Set<Entry<String, String>> entrySet() { return new AbstractSet<Entry<String, String>>() { @Override public Iterator<Entry<String, String>> iterator() { return new Iterator<Entry<String, String>>() { final Iterator<Entry<String, String>> keyIterator = storage.entrySet().iterator(); public boolean hasNext() { return keyIterator.hasNext(); } public Entry<String, String> next() { final Entry<String, String> entry = keyIterator.next(); return new Entry<String, String>() { public String getKey() { return entry.getKey(); } public String getValue() { return entry.getValue(); } public String setValue(String value) { String old = entry.setValue(value); if (old == null || !old.equals(value)) { Layout l = layout.get(entry.getKey()); if (l != null) { l.clearValue(); } } return old; } }; } public void remove() { keyIterator.remove(); } }; } @Override public int size() { return storage.size(); } }; } /** * Returns an enumeration of all the keys in this property list, including distinct keys in the default property * list if a key of the same name has not already been found from the main properties list. * * @return an enumeration of all the keys in this property list, including the keys in the default property list. */ public Enumeration<?> propertyNames() { return Collections.enumeration(storage.keySet()); } /** * Calls the map method put. Provided for parallelism with the getProperty method. * Enforces use of strings for property keys and values. The value returned is the result of the map call to put. * * @param key the key to be placed into this property list. * @param value the value corresponding to the key. * @return the previous value of the specified key in this property list, or null if it did not have one. */ public Object setProperty(String key, String value) { return this.put(key, value); } @Override public String put(String key, String value) { String old = storage.put(key, value); if (old == null || !old.equals(value)) { Layout l = layout.get(key); if (l != null) { l.clearValue(); } } return old; } void putAllSubstituted(Map<? extends String, ? extends String> m) { storage.putAll(m); } public String put(String key, List<String> commentLines, List<String> valueLines) { commentLines = new ArrayList<String>(commentLines); valueLines = new ArrayList<String>(valueLines); String escapedKey = escapeKey(key); StringBuilder sb = new StringBuilder(); int lastLine = valueLines.size() - 1; if (valueLines.isEmpty()) { valueLines.add(escapedKey + "="); sb.append(escapedKey).append("="); } else { String val0 = valueLines.get(0); String rv0 = typed ? val0 : escapeJava(val0); if (!val0.trim().startsWith(escapedKey)) { valueLines.set(0, escapedKey + " = " + rv0 /*+ (0 < lastLine? "\\": "")*/); sb.append(escapedKey).append(" = ").append(rv0); } else { valueLines.set(0, rv0 /*+ (0 < lastLine? "\\": "")*/); sb.append(rv0); } } for (int i = 1; i < valueLines.size(); i++) { String val = valueLines.get(i); valueLines.set(i, typed ? val : escapeJava(val) /*+ (i < lastLine? "\\": "")*/); while (val.length() > 0 && Character.isWhitespace(val.charAt(0))) { val = val.substring(1); } sb.append(val); } String[] property = PropertiesReader.parseProperty(sb.toString()); this.layout.put(key, new Layout(commentLines, valueLines)); return storage.put(key, property[1]); } public String put(String key, List<String> commentLines, String value) { commentLines = new ArrayList<String>(commentLines); this.layout.put(key, new Layout(commentLines, null)); return storage.put(key, value); } public String put(String key, String comment, String value) { return put(key, Collections.singletonList(comment), value); } public boolean update(Map<String, String> props) { Properties properties; if (props instanceof Properties) { properties = (Properties) props; } else { properties = new Properties(); for (Map.Entry<? extends String, ? extends String> e : props.entrySet()) { properties.put(e.getKey(), e.getValue()); } } return update(properties); } public boolean update(Properties properties) { boolean modified = false; // Remove "removed" properties from the cfg file for (String key : new ArrayList<String>(this.keySet())) { if (!properties.containsKey(key)) { this.remove(key); modified = true; } } // Update existing keys for (String key : properties.keySet()) { String v = this.get(key); List<String> comments = properties.getComments(key); List<String> value = properties.getRaw(key); if (v == null) { this.put(key, comments, value); modified = true; } else if (!v.equals(properties.get(key))) { if (comments.isEmpty()) { comments = this.getComments(key); } this.put(key, comments, value); modified = true; } } return modified; } public List<String> getRaw(String key) { if (layout.containsKey(key)) { if (layout.get(key).getValueLines() != null) { return new ArrayList<String>(layout.get(key).getValueLines()); } } List<String> result = new ArrayList<String>(); if (storage.containsKey(key)) { result.add(storage.get(key)); } return result; } public List<String> getComments(String key) { if (layout.containsKey(key)) { if (layout.get(key).getCommentLines() != null) { return new ArrayList<String>(layout.get(key).getCommentLines()); } } return new ArrayList<String>(); } @Override public String remove(Object key) { Layout l = layout.get(key); if (l != null) { l.clearValue(); } return storage.remove(key); } @Override public void clear() { for (Layout l : layout.values()) { l.clearValue(); } storage.clear(); } /** * Return the comment header. * * @return the comment header */ public List<String> getHeader() { return header; } /** * Set the comment header. * * @param header the header to use */ public void setHeader(List<String> header) { this.header = header; } /** * Return the comment footer. * * @return the comment footer */ public List<String> getFooter() { return footer; } /** * Set the comment footer. * * @param footer the footer to use */ public void setFooter(List<String> footer) { this.footer = footer; } /** * Reads a properties file and stores its internal structure. The found * properties will be added to the associated configuration object. * * @param in the reader to the properties file * @throws java.io.IOException if an error occurs */ protected void loadLayout(Reader in, boolean maybeTyped) throws IOException { PropertiesReader reader = new PropertiesReader(in, maybeTyped); boolean hasProperty = false; while (reader.nextProperty()) { hasProperty = true; storage.put(reader.getPropertyName(), reader.getPropertyValue()); int idx = checkHeaderComment(reader.getCommentLines()); layout.put(reader.getPropertyName(), new Layout(idx < reader.getCommentLines().size() ? new ArrayList<String>(reader.getCommentLines().subList(idx, reader.getCommentLines().size())) : null, new ArrayList<String>(reader.getValueLines()))); } typed = maybeTyped && reader.typed != null && reader.typed; if (!typed) { for (Map.Entry<String,String> e : storage.entrySet()) { e.setValue(unescapeJava(e.getValue())); } } if (hasProperty) { footer = new ArrayList<String>(reader.getCommentLines()); } else { header = new ArrayList<String>(reader.getCommentLines()); } if (substitute) { substitute(); } } public void substitute() { substitute(callback); } public void substitute(InterpolationHelper.SubstitutionCallback callback) { if (callback == null) { callback = new InterpolationHelper.BundleContextSubstitutionCallback(null); } InterpolationHelper.performSubstitution(storage, callback); } /** * Writes the properties file to the given writer, preserving as much of its * structure as possible. * * @param out the writer * @throws java.io.IOException if an error occurs */ protected void saveLayout(Writer out, boolean typed) throws IOException { PropertiesWriter writer = new PropertiesWriter(out, typed); if (header != null) { for (String s : header) { writer.writeln(s); } } for (String key : storage.keySet()) { Layout l = layout.get(key); if (l != null && l.getCommentLines() != null) { for (String s : l.getCommentLines()) { writer.writeln(s); } } if (l != null && l.getValueLines() != null) { for (int i = 0; i < l.getValueLines().size(); i++) { String s = l.getValueLines().get(i); if (i < l.getValueLines().size() - 1) { writer.writeln(s + "\\"); } else { writer.writeln(s); } } } else { writer.writeProperty(key, storage.get(key)); } } if (footer != null) { for (String s : footer) { writer.writeln(s); } } writer.flush(); } /** * Checks if parts of the passed in comment can be used as header comment. * This method checks whether a header comment can be defined (i.e. whether * this is the first comment in the loaded file). If this is the case, it is * searched for the lates blank line. This line will mark the end of the * header comment. The return value is the index of the first line in the * passed in list, which does not belong to the header comment. * * @param commentLines the comment lines * @return the index of the next line after the header comment */ private int checkHeaderComment(List<String> commentLines) { if (getHeader() == null && layout.isEmpty()) { // This is the first comment. Search for blank lines. int index = commentLines.size() - 1; while (index >= 0 && commentLines.get(index).length() > 0) { index--; } setHeader(new ArrayList<String>(commentLines.subList(0, index + 1))); return index + 1; } else { return 0; } } /** * Tests whether a line is a comment, i.e. whether it starts with a comment * character. * * @param line the line * @return a flag if this is a comment line */ static boolean isCommentLine(String line) { String s = line.trim(); // blank lines are also treated as comment lines return s.length() < 1 || COMMENT_CHARS.indexOf(s.charAt(0)) >= 0; } /** * <p>Unescapes any Java literals found in the <code>String</code> to a * <code>Writer</code>.</p> This is a slightly modified version of the * StringEscapeUtils.unescapeJava() function in commons-lang that doesn't * drop escaped separators (i.e '\,'). * * @param str the <code>String</code> to unescape, may be null * @return the processed string * @throws IllegalArgumentException if the Writer is <code>null</code> */ protected static String unescapeJava(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer out = new StringBuffer(sz); StringBuffer unicode = new StringBuffer(UNICODE_LEN); boolean hadSlash = false; boolean inUnicode = false; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); if (unicode.length() == UNICODE_LEN) { // unicode now contains the four hex digits // which represents our unicode character try { int value = Integer.parseInt(unicode.toString(), HEX_RADIX); out.append((char) value); unicode.setLength(0); inUnicode = false; hadSlash = false; } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe); } } continue; } if (hadSlash) { // handle an escaped value hadSlash = false; switch (ch) { case '\\' : out.append('\\'); break; case '\'' : out.append('\''); break; case '\"' : out.append('"'); break; case 'r' : out.append('\r'); break; case 'f' : out.append('\f'); break; case 't' : out.append('\t'); break; case 'n' : out.append('\n'); break; case 'b' : out.append('\b'); break; case 'u' : // uh-oh, we're in unicode country.... inUnicode = true; break; default : out.append(ch); break; } continue; } else if (ch == '\\') { hadSlash = true; continue; } out.append(ch); } if (hadSlash) { // then we're in the weird case of a \ at the end of the // string, let's output it anyway. out.append('\\'); } return out.toString(); } /** * <p>Escapes the characters in a <code>String</code> using Java String rules.</p> * * <p>Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p> * * <p>So a tab becomes the characters <code>'\\'</code> and * <code>'t'</code>.</p> * * <p>The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.</p> * * <p>Example:</p> * <pre> * input string: He didn't say, "Stop!" * output string: He didn't say, \"Stop!\" * </pre> * * * @param str String to escape values in, may be null * @return String with escaped values, <code>null</code> if null string input */ protected static String escapeJava(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer out = new StringBuffer(sz * 2); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.append("\\u").append(hex(ch)); } else if (ch > 0xff) { out.append("\\u0").append(hex(ch)); } else if (ch > 0x7f) { out.append("\\u00").append(hex(ch)); } else if (ch < 32) { switch (ch) { case '\b' : out.append('\\'); out.append('b'); break; case '\n' : out.append('\\'); out.append('n'); break; case '\t' : out.append('\\'); out.append('t'); break; case '\f' : out.append('\\'); out.append('f'); break; case '\r' : out.append('\\'); out.append('r'); break; default : if (ch > 0xf) { out.append("\\u00").append(hex(ch)); } else { out.append("\\u000").append(hex(ch)); } break; } } else { switch (ch) { case '"' : out.append('\\'); out.append('"'); break; case '\\' : out.append('\\'); out.append('\\'); break; default : out.append(ch); break; } } } return out.toString(); } /** * <p>Returns an upper case hexadecimal <code>String</code> for the given * character.</p> * * @param ch The character to convert. * @return An upper case hexadecimal <code>String</code> */ protected static String hex(char ch) { return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH); } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(char[] array, char valueToFind) { if (array == null) { return false; } for (int i = 0; i < array.length; i++) { if (valueToFind == array[i]) { return true; } } return false; } /** * Escape the separators in the key. * * @param key the key * @return the escaped key */ private static String escapeKey(String key) { StringBuffer newkey = new StringBuffer(); for (int i = 0; i < key.length(); i++) { char c = key.charAt(i); if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c)) { // escape the separator newkey.append('\\'); newkey.append(c); } else { newkey.append(c); } } return newkey.toString(); } /** * This class is used to read properties lines. These lines do * not terminate with new-line chars but rather when there is no * backslash sign a the end of the line. This is used to * concatenate multiple lines for readability. */ public static class PropertiesReader extends LineNumberReader { /** Stores the comment lines for the currently processed property.*/ private final List<String> commentLines; /** Stores the value lines for the currently processed property.*/ private final List<String> valueLines; /** Stores the name of the last read property.*/ private String propertyName; /** Stores the value of the last read property.*/ private String propertyValue; private boolean maybeTyped; /** Stores if the properties are typed or not */ Boolean typed; /** * Creates a new instance of <code>PropertiesReader</code> and sets * the underlaying reader and the list delimiter. * * @param reader the reader */ public PropertiesReader(Reader reader, boolean maybeTyped) { super(reader); commentLines = new ArrayList<String>(); valueLines = new ArrayList<String>(); this.maybeTyped = maybeTyped; } /** * Reads a property line. Returns null if Stream is * at EOF. Concatenates lines ending with "\". * Skips lines beginning with "#" or "!" and empty lines. * The return value is a property definition (<code>&lt;name&gt;</code> * = <code>&lt;value&gt;</code>) * * @return A string containing a property value or null * * @throws java.io.IOException in case of an I/O error */ public String readProperty() throws IOException { commentLines.clear(); valueLines.clear(); StringBuffer buffer = new StringBuffer(); while (true) { String line = readLine(); if (line == null) { // EOF return null; } if (isCommentLine(line)) { commentLines.add(line); continue; } boolean combine = checkCombineLines(line); if (combine) { line = line.substring(0, line.length() - 1); } valueLines.add(line); while (line.length() > 0 && contains(WHITE_SPACE, line.charAt(0))) { line = line.substring(1, line.length()); } buffer.append(line); if (!combine) { break; } } return buffer.toString(); } /** * Parses the next property from the input stream and stores the found * name and value in internal fields. These fields can be obtained using * the provided getter methods. The return value indicates whether EOF * was reached (<b>false</b>) or whether further properties are * available (<b>true</b>). * * @return a flag if further properties are available * @throws java.io.IOException if an error occurs */ public boolean nextProperty() throws IOException { String line = readProperty(); if (line == null) { return false; // EOF } // parse the line String[] property = parseProperty(line); boolean typed = false; if (maybeTyped && property[1].length() >= 2) { typed = property[1].matches("\\s*[TILFDXSCBilfdxscb]?(\\[[\\S\\s]*\\]|\\{[\\S\\s]*\\}|\"[\\S\\s]*\")\\s*"); } if (this.typed == null) { this.typed = typed; } else { this.typed = this.typed & typed; } propertyName = unescapeJava(property[0]); propertyValue = property[1]; return true; } /** * Returns the comment lines that have been read for the last property. * * @return the comment lines for the last property returned by * <code>readProperty()</code> */ public List<String> getCommentLines() { return commentLines; } /** * Returns the value lines that have been read for the last property. * * @return the raw value lines for the last property returned by * <code>readProperty()</code> */ public List<String> getValueLines() { return valueLines; } /** * Returns the name of the last read property. This method can be called * after <code>{@link #nextProperty()}</code> was invoked and its * return value was <b>true</b>. * * @return the name of the last read property */ public String getPropertyName() { return propertyName; } /** * Returns the value of the last read property. This method can be * called after <code>{@link #nextProperty()}</code> was invoked and * its return value was <b>true</b>. * * @return the value of the last read property */ public String getPropertyValue() { return propertyValue; } /** * Checks if the passed in line should be combined with the following. * This is true, if the line ends with an odd number of backslashes. * * @param line the line * @return a flag if the lines should be combined */ private static boolean checkCombineLines(String line) { int bsCount = 0; for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--) { bsCount++; } return bsCount % 2 != 0; } /** * Parse a property line and return the key and the value in an array. * * @param line the line to parse * @return an array with the property's key and value */ private static String[] parseProperty(String line) { // sorry for this spaghetti code, please replace it as soon as // possible with a regexp when the Java 1.3 requirement is dropped String[] result = new String[2]; StringBuffer key = new StringBuffer(); StringBuffer value = new StringBuffer(); // state of the automaton: // 0: key parsing // 1: antislash found while parsing the key // 2: separator crossing // 3: white spaces // 4: value parsing int state = 0; for (int pos = 0; pos < line.length(); pos++) { char c = line.charAt(pos); switch (state) { case 0: if (c == '\\') { state = 1; } else if (contains(WHITE_SPACE, c)) { // switch to the separator crossing state state = 2; } else if (contains(SEPARATORS, c)) { // switch to the value parsing state state = 3; } else { key.append(c); } break; case 1: if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c)) { // this is an escaped separator or white space key.append(c); } else { // another escaped character, the '\' is preserved key.append('\\'); key.append(c); } // return to the key parsing state state = 0; break; case 2: if (contains(WHITE_SPACE, c)) { // do nothing, eat all white spaces state = 2; } else if (contains(SEPARATORS, c)) { // switch to the value parsing state state = 3; } else { // any other character indicates we encoutered the beginning of the value value.append(c); // switch to the value parsing state state = 4; } break; case 3: if (contains(WHITE_SPACE, c)) { // do nothing, eat all white spaces state = 3; } else { // any other character indicates we encoutered the beginning of the value value.append(c); // switch to the value parsing state state = 4; } break; case 4: value.append(c); break; } } result[0] = key.toString(); result[1] = value.toString(); return result; } } // class PropertiesReader /** * This class is used to write properties lines. */ public static class PropertiesWriter extends FilterWriter { private boolean typed; /** * Constructor. * * @param writer a Writer object providing the underlying stream */ public PropertiesWriter(Writer writer, boolean typed) { super(writer); this.typed = typed; } /** * Writes the given property and its value. * * @param key the property key * @param value the property value * @throws java.io.IOException if an error occurs */ public void writeProperty(String key, String value) throws IOException { write(escapeKey(key)); write(" = "); write(typed ? value : escapeJava(value)); writeln(null); } /** * Helper method for writing a line with the platform specific line * ending. * * @param s the content of the line (may be <b>null</b>) * @throws java.io.IOException if an error occurs */ public void writeln(String s) throws IOException { if (s != null) { write(s); } write(LINE_SEPARATOR); } } // class PropertiesWriter /** * TODO */ protected static class Layout { private List<String> commentLines; private List<String> valueLines; public Layout() { } public Layout(List<String> commentLines, List<String> valueLines) { this.commentLines = commentLines; this.valueLines = valueLines; } public List<String> getCommentLines() { return commentLines; } public void setCommentLines(List<String> commentLines) { this.commentLines = commentLines; } public List<String> getValueLines() { return valueLines; } public void setValueLines(List<String> valueLines) { this.valueLines = valueLines; } public void clearValue() { this.valueLines = null; } } // class Layout }
kcat/XLEngine
procedural/ProceduralFunc.cpp
<gh_stars>1-10 #include "ProceduralFunc.h" #include "Noise.h" #include "../math/Math.h" #include <math.h> namespace ProceduralFunc { float fBm(Vector3 p, int nOctaves, float H/*=0.5f*/, float r/*=2.0f*/) { float z = p.z; float fRes = Noise::Noise3D(p.x, p.y, z); float fAmp=H; for (int i=1; i<nOctaves; i++) { p = p * r; fRes += fAmp*Noise::Noise3D(p.x, p.y, z); fAmp *= H; } return fRes; } float Turbulance(Vector3 p, int nOctaves, float H/*=0.5f*/, float r/*=2.0f*/) { float z = p.z; float fRes = fabsf( Noise::Noise3D(p.x, p.y, z) ); float fAmp=H; for (int i=1; i<nOctaves; i++) { p = p * r; fRes += fAmp*fabsf(Noise::Noise3D(p.x, p.y, z)); fAmp *= H; } return fRes; } float Ridged(Vector3 p, int nOctaves, float H/*=0.5f*/, float r/*=2.0f*/) { float z = p.z; float fRes = 1.0f - fabsf( Noise::Noise3D(p.x, p.y, z) ); float fAmp=H; for (int i=1; i<nOctaves; i++) { p = p * r; fRes += fAmp*(1.0f - fabsf(Noise::Noise3D(p.x, p.y, z))); fAmp *= H; } return Math::Min(fRes,1.0f); } float RidgedMulti(Vector3 p, int nOctaves, float power/*=2.0f*/, float H/*=0.5f*/, float r/*=2.0f*/) { const float gain = 2.0f; float z = p.z; float weight = 1.0f; float signal = powf( 1.0f - fabsf( Noise::Noise3D(p.x, p.y, z) ), power ); float fRes = signal; float fAmp=H; for (int i=1; i<nOctaves; i++) { weight = Math::clamp( signal * gain, 0.0f, 1.0f ); p = p * r; signal = weight*powf( 1.0f - fabsf( Noise::Noise3D(p.x, p.y, z) ), power ); fRes += signal * fAmp; fAmp *= H; } return Math::Min(fRes,1.0f); } };
grishkam/QuickFigures
QuickFigures/User_Interface/imageDisplayApp/ImageWindowAndDisplaySet.java
/******************************************************************************* * Copyright (c) 2021 <NAME> * * 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. *******************************************************************************/ /** * Author: <NAME> * Date Modified: Feb 24, 2021 * Version: 2021.1 */ package imageDisplayApp; import undo.UndoManagerPlus; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.awt.Window; import java.awt.geom.Point2D; import applicationAdapters.CanvasMouseEvent; import applicationAdapters.DisplayedImage; import applicationAdapters.ImageWorkSheet; import graphicalObjects.BasicCoordinateConverter; import handles.SmartHandle; import handles.SmartHandleList; import layersGUI.GraphicTreeUI; import locatedObject.Selectable; /** Stores everything related to a particular worksheet including the display window, the layer set inside, the undo manager and what selections are made */ public class ImageWindowAndDisplaySet implements DisplayedImage { public static GraphicTreeUI exampletree; private GraphicSetDisplayWindow theWindow=null; private GraphicDisplayCanvas theCanvas=null; private StandardWorksheet theFigure=null; private MiniToolBarPanel sidePanel;//optional side panel /**The time frames for animations*/ private int currentFrame=0; private int endFrame=200; private transient Selectable selectedItem=null; /**This undo manager stores the undos for this image*/ transient UndoManagerPlus undoManager=null; /**Generates a Display of the given graphic set*/ public ImageWindowAndDisplaySet(StandardWorksheet graphicSet) { this.setTheSet( graphicSet); GraphicDisplayCanvas canvas = new GraphicDisplayCanvas(); this.setTheCanvas(canvas); //updateCanvasDims();// this.setTheWindow(new GraphicSetDisplayWindow(this,canvas)); this.getTheWindow().reSetCanvasAndWindowSizes() ; centreWindow(this.getWindow()); ensureAllLinked(); } /**called to let the window know which set of objects it is displaying*/ void ensureAllLinked() { this.getTheWindow().setDisplaySet(this); } /**returns the component that all the edited object are drawn onto*/ public GraphicDisplayCanvas getTheCanvas() { return theCanvas; } /**sets the component that all the edited object are drawn onto*/ public void setTheCanvas(GraphicDisplayCanvas theCanvas) { this.theCanvas = theCanvas; } /**getter methow for the window*/ public GraphicSetDisplayWindow getTheWindow() { return theWindow; } public void setTheWindow(GraphicSetDisplayWindow theWindow) { this.theWindow = theWindow; if (theWindow!=null) { theWindow.setDisplaySet(this); } } /**getter method for the 'image' containing all the objects and layers*/ public StandardWorksheet getTheSet() { return theFigure; } public void setTheSet(StandardWorksheet theSet) { this.theFigure = theSet; theSet.undoManager=this.getUndoManager(); if (theSet!=null) theSet.setDisplayGroup(this); } int count =0;//keeps a count of all the updates to the display windows public void updateDisplay() { if (this.getTheCanvas()==null) return; theCanvas.repaint(); if (this.sidePanel!=null) sidePanel.repaint(); count++; } public BasicCoordinateConverter getConverter() { if (theWindow==null) { //IssueLog.log("Problem: Cordinate conversion factor requested despite no window being set"); return new BasicCoordinateConverter();} return theWindow.getZoomer().getConverter(); } @Override public ImageWorkSheet getImageAsWorksheet() { return theFigure; } @Override public GraphicSetDisplayWindow getWindow() { return this.theWindow; } /**Creates a new blank image*/ public static ImageWindowAndDisplaySet createAndShowNew(String title, int width, int height) { StandardWorksheet gs = new StandardWorksheet(); gs.setTitle(title); gs.getBasics().setWidth(width); gs.getBasics().setHeight(height); return show(gs); } /**creates the window an user interface elements needed to display the image*/ public static ImageWindowAndDisplaySet show(StandardWorksheet gs) { ImageWindowAndDisplaySet set = new ImageWindowAndDisplaySet(gs); Window win = set.getWindow(); win.pack(); return set; } /**returns the undo manager*/ public UndoManagerPlus getUndoManager() { if ( undoManager==null) { undoManager=new UndoManagerPlus(); if (theFigure!=null)theFigure.undoManager=undoManager; } return undoManager; } /**sets the cursor being used*/ @Override public void setCursor(Cursor c) { if (c==null)return; if (theCanvas.getCursor().equals(c)) return; theCanvas.setCursor(c); } /**resets the window size*/ @Override public void updateWindowSize() { this.getTheWindow().reSetCanvasAndWindowSizes(); } /**places the window at the center of the screen*/ public static void centreWindow(Window window1) { Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - window1.getWidth()) / 2); int y = (int) ((dimension.getHeight() - window1.getHeight()) / 2); window1.setLocation(x, y); } /**chooses a zoom level automatically*/ public void autoZoom() { this.getTheWindow().comfortZoomIn(); } /**zooms out until the entire image is of a size that is comfortable visible*/ @Override public void zoomOutToDisplayEntireCanvas() { getTheWindow().shrinktoFit(); } @Override public void zoom(String actionCommand) { getTheWindow().zoom(actionCommand); } /**changes the zoom lebel and updates the window size*/ @Override public void setZoomLevel(double st) { getTheWindow().getZoomer().setZoom(st); updateWindowSize(); updateDisplay(); } public int getCurrentFrame() { return currentFrame; } public void setCurrentFrame(int currentFrame) { this.currentFrame = currentFrame; } public int getEndFrame() { return endFrame; } public void setEndFrame(int endFrame) { this.endFrame = endFrame; } @Override public void scrollPane(double dx, double dy) { theWindow.scrollPane(dx, dy); } @Override public void setScrollCenter(double dx, double dy) { theWindow.centerZoom(new Point2D.Double(dx, dy)); } @Override public void closeWindowButKeepObjects() { this.getTheWindow().closeGroupWithoutObjectDeath(); } public String toString() { return this.getTheSet().getTitle(); } public Selectable getSelectedItem() { if (selectedItem!=null&&!selectedItem.isSelected()) return null; return selectedItem; } public void setSelectedItem(Selectable selectedItem) { this.selectedItem = selectedItem; } /**returns the zoom level (100% is no zoom)*/ @Override public double getZoomLevel() { return 100*getTheWindow().getZoomer().getZoomMagnification(); } public void setSidePanel(MiniToolBarPanel miniToolBarPanel) { sidePanel=miniToolBarPanel; } /**a handle used for resizing the canvas*/ class CanvasResizeHandle extends SmartHandle { public CanvasResizeHandle(ImageWindowAndDisplaySet s) { this.setHandleNumber(999910044); this.setHandleColor(Color.DARK_GRAY.darker()); } /**the location at the bottom right corner of the canvas*/ public Point2D getCordinateLocation() { Dimension d = theFigure.getCanvasDims(); return new Point2D.Double(d.getWidth(), d.getHeight()); } /**performs the change in canvas size*/ public void handleDrag(CanvasMouseEvent lastDragOrRelMouseEvent) { Point p = lastDragOrRelMouseEvent.getCoordinatePoint(); theFigure.getBasics().setWidth(p.x); theFigure.getBasics().setHeight(p.y); //updateDisplay(); theWindow.resetCanvasDisplayObjectSize(); } public void handleRelease(CanvasMouseEvent lastDragOrRelMouseEvent) { if (theWindow.usesBuiltInSidePanel()) theWindow.reSetCanvasAndWindowSizes(); } /** * */ private static final long serialVersionUID = 1L; } /**The handle list for the canvas size changing handle*/ transient SmartHandleList canvasHandleList; @Override public SmartHandleList getCanvasHandles() { if (canvasHandleList==null) canvasHandleList = SmartHandleList.createList(new CanvasResizeHandle(this)); return canvasHandleList; } }
Aleoami/kaspad
cmd/kaspawallet/send.go
package main import ( "context" "fmt" "github.com/kaspanet/kaspad/cmd/kaspawallet/daemon/client" "github.com/kaspanet/kaspad/cmd/kaspawallet/daemon/pb" "github.com/kaspanet/kaspad/cmd/kaspawallet/keys" "github.com/kaspanet/kaspad/cmd/kaspawallet/libkaspawallet" "github.com/kaspanet/kaspad/domain/consensus/utils/constants" "github.com/pkg/errors" ) func send(conf *sendConfig) error { keysFile, err := keys.ReadKeysFile(conf.NetParams(), conf.KeysFile) if err != nil { return err } if len(keysFile.ExtendedPublicKeys) > len(keysFile.EncryptedMnemonics) { return errors.Errorf("Cannot use 'send' command for multisig wallet without all of the keys") } daemonClient, tearDown, err := client.Connect(conf.DaemonAddress) if err != nil { return err } defer tearDown() ctx, cancel := context.WithTimeout(context.Background(), daemonTimeout) defer cancel() sendAmountSompi := uint64(conf.SendAmount * constants.SompiPerKaspa) createUnsignedTransactionsResponse, err := daemonClient.CreateUnsignedTransactions(ctx, &pb.CreateUnsignedTransactionsRequest{ From: conf.FromAddresses, Address: conf.ToAddress, Amount: sendAmountSompi, }) if err != nil { return err } if len(conf.Password) == 0 { conf.Password = keys.GetPassword("Password:") } mnemonics, err := keysFile.DecryptMnemonics(conf.Password) if err != nil { return err } signedTransactions := make([][]byte, len(createUnsignedTransactionsResponse.UnsignedTransactions)) for i, unsignedTransaction := range createUnsignedTransactionsResponse.UnsignedTransactions { signedTransaction, err := libkaspawallet.Sign(conf.NetParams(), mnemonics, unsignedTransaction, keysFile.ECDSA) if err != nil { return err } signedTransactions[i] = signedTransaction } if len(signedTransactions) > 1 { fmt.Printf("Broadcasting %d transactions\n", len(signedTransactions)) } response, err := daemonClient.Broadcast(ctx, &pb.BroadcastRequest{Transactions: signedTransactions}) if err != nil { return err } fmt.Println("Transactions were sent successfully") fmt.Println("Transaction ID(s): ") for _, txID := range response.TxIDs { fmt.Printf("\t%s\n", txID) } return nil }
paragraff/Star-Citizen-WebGL-Map
src/scmap/map/geometry/system-glow.js
<filename>src/scmap/map/geometry/system-glow.js /** * @author <NAME> / https://github.com/Leeft */ import MapGeometry from '../map-geometry'; import settings from '../../settings'; import config from '../../config'; import THREE from 'three'; const GLOW_SCALE = 3.75; const BLACK = new THREE.Color( 'black' ); const UNSET = new THREE.Color( 0x80A0CC ); const GLOW_MATERIAL_PROMISE = new Promise( function ( resolve, reject ) { const loader = new THREE.TextureLoader(); loader.load( config.glowImage, function ( texture ) { resolve( new THREE.SpriteMaterial({ map: texture, blending: THREE.AdditiveBlending, opacity: 0.65, })); }, function ( /* progress */ ) {}, function ( failure ) { reject( new Error( `Could not load texture ${ config.glowImage }: ${ failure }` ) ); } ); }); class SystemGlow extends MapGeometry { constructor ({ material: material }) { super(...arguments); this.material = material; } get mesh () { if ( this._mesh ) { return this._mesh; } const group = new THREE.Group(); this._mesh = group; try { this.allSystems.forEach( system => { const color = system.color; if ( color.equals( BLACK ) ) { color.copy( UNSET ); } const material = this.material.clone(); material.color = color; const glow = new THREE.Sprite( material ); glow.position.set( system.position.x, system.position.y, system.position.z ); glow.userData.isGlow = true; glow.userData.system = system; glow.userData.y = system.position.y; glow.sortParticles = true; group.add( glow ); }); } catch( e ) { console.error( `Problem creating glow sprites:`, e ); throw e; } group.userData.y = 0; group.dynamic = false; group.userData.scaleY = SystemGlow.scaleY; group.updateMatrix(); group.name = 'Star System Glow'; this.refreshVisibility(); this.refreshScale(); SystemGlow.scaleY( group, this.initialScale ); return group; } refreshVisibility () { this._mesh.traverse( function( obj ) { if ( obj.userData.isGlow && obj.userData.system ) { obj.visible = settings.glow; } }); } refreshScale () { this._mesh.traverse( function( obj ) { if ( obj.userData.isGlow && obj.userData.system ) { const scale = obj.userData.system.scale * settings.systemScale * GLOW_SCALE; obj.scale.set( scale, scale, 1.0 ); } }); } static scaleY ( mesh, scaleY ) { mesh.traverse( function( obj ) { if ( obj.userData.isGlow && obj.userData.system ) { obj.position.setY( obj.userData.y * scaleY ); } }); } } export default SystemGlow; export { GLOW_MATERIAL_PROMISE };
zhangkn/iOS14Header
System/Library/PrivateFrameworks/NeutrinoCore.framework/NUDataSet.h
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:45:07 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/NeutrinoCore.framework/NeutrinoCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <NeutrinoCore/NeutrinoCore-Structs.h> #import <libobjc.A.dylib/NSCopying.h> #import <libobjc.A.dylib/NSMutableCopying.h> @interface NUDataSet : NSObject <NSCopying, NSMutableCopying> { SCD_Struct_NU32 _stats; struct { unsigned sum : 1; unsigned min : 1; unsigned max : 1; unsigned mean : 1; unsigned geomean : 1; unsigned median : 1; unsigned variance : 1; unsigned stddev : 1; unsigned stderr : 1; unsigned ci95 : 1; unsigned cv : 1; unsigned mad : 1; } _flags; DataSet* _data; } @property (nonatomic,readonly) long long count; @property (nonatomic,readonly) double sum; @property (nonatomic,readonly) double min; @property (nonatomic,readonly) double max; @property (nonatomic,readonly) double mean; @property (nonatomic,readonly) double geometricMean; @property (nonatomic,readonly) double median; @property (nonatomic,readonly) double variance; @property (nonatomic,readonly) double standardDeviation; @property (nonatomic,readonly) double standardError; @property (nonatomic,readonly) double confidenceInterval95; @property (nonatomic,readonly) double coefficientOfVariation; @property (nonatomic,readonly) double medianAbsoluteDeviation; @property (nonatomic,readonly) double estimatedStandardDeviation; @property (nonatomic,readonly) double estimatedStandardError; @property (nonatomic,readonly) double estimatedConfidenceInterval95; @property (nonatomic,readonly) double estimatedCoefficientOfVariation; -(double)sum; -(id)map:(/*^block*/id)arg1 ; -(double)mean; -(double)valueAtIndex:(long long)arg1 ; -(id)mutableCopyWithZone:(NSZone*)arg1 ; -(id)copyWithZone:(NSZone*)arg1 ; -(id)initWithValue:(double)arg1 ; -(double)min; -(double)median; -(id)filter:(/*^block*/id)arg1 ; -(double)standardError; -(id)initWithValues:(const double*)arg1 count:(long long)arg2 ; -(double)variance; -(id)init; -(BOOL)isEqual:(id)arg1 ; -(long long)count; -(double)max; -(double)standardDeviation; -(id)description; -(const DataSet*)_const_data; -(id)initWithDataSet:(id)arg1 ; -(void)enumerateValues:(/*^block*/id)arg1 ; -(BOOL)isEqualToDataSet:(id)arg1 ; -(void)_resetStats; -(double)geometricMean; -(double)confidenceInterval95; -(double)coefficientOfVariation; -(double)medianAbsoluteDeviation; -(double)estimatedStandardDeviation; -(double)estimatedStandardError; -(double)estimatedConfidenceInterval95; -(double)estimatedCoefficientOfVariation; -(double)percentile:(double)arg1 ; @end
loop-perception/AutowareArchitectureProposal.iv
perception/object_recognition/detection/lidar_apollo_instance_segmentation/lib/include/Utils.hpp
<gh_stars>10-100 /* * MIT License * * Copyright (c) 2018 lewes6369 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __TRT_UTILS_H_ #define __TRT_UTILS_H_ #include <NvInferPlugin.h> #include <cudnn.h> #include <algorithm> #include <iostream> #include <string> #include <utility> #include <vector> #ifndef CUDA_CHECK #define CUDA_CHECK(callstr) \ { \ cudaError_t error_code = callstr; \ if (error_code != cudaSuccess) { \ std::cerr << "CUDA error " << error_code << " at " << __FILE__ << ":" << __LINE__; \ assert(0); \ } \ } #endif namespace Tn { class Profiler : public nvinfer1::IProfiler { public: void printLayerTimes(int iterationsTimes) { float totalTime = 0; for (size_t i = 0; i < mProfile.size(); i++) { printf("%-40.40s %4.3fms\n", mProfile[i].first.c_str(), mProfile[i].second / iterationsTimes); totalTime += mProfile[i].second; } printf("Time over all layers: %4.3f\n", totalTime / iterationsTimes); } private: typedef std::pair<std::string, float> Record; std::vector<Record> mProfile; void reportLayerTime(const char * layerName, float ms) noexcept override { auto record = std::find_if( mProfile.begin(), mProfile.end(), [&](const Record & r) { return r.first == layerName; }); if (record == mProfile.end()) { mProfile.push_back(std::make_pair(layerName, ms)); } else { record->second += ms; } } }; // Logger for TensorRT info/warning/errors class Logger : public nvinfer1::ILogger { public: Logger() : Logger(Severity::kWARNING) {} explicit Logger(Severity severity) : reportableSeverity(severity) {} void log(Severity severity, const char * msg) noexcept override { // suppress messages with severity enum value greater than the reportable if (severity > reportableSeverity) { return; } switch (severity) { case Severity::kINTERNAL_ERROR: std::cerr << "INTERNAL_ERROR: "; break; case Severity::kERROR: std::cerr << "ERROR: "; break; case Severity::kWARNING: std::cerr << "WARNING: "; break; case Severity::kINFO: std::cerr << "INFO: "; break; default: std::cerr << "UNKNOWN: "; break; } std::cerr << msg << std::endl; } Severity reportableSeverity{Severity::kWARNING}; }; template <typename T> void write(char *& buffer, const T & val) { *reinterpret_cast<T *>(buffer) = val; buffer += sizeof(T); } template <typename T> void read(const char *& buffer, T & val) { val = *reinterpret_cast<const T *>(buffer); buffer += sizeof(T); } } // namespace Tn #endif
roti/lut
library/src/main/scala/roti/lut/Record.scala
package roti.lut import roti.lut.annotation.fields import scala.language.experimental.macros import scala.reflect.ClassTag /** Base trait for a Record. * */ trait Record extends Equals { val data: Map[String, Any] override def canEqual(that: Any): Boolean = that.isInstanceOf[Record] || that.isInstanceOf[Map[_,_]] override def equals(that: Any): Boolean = that match { case r: Record => data.equals(r.data) case m: Map[_, _] => data.equals(m) case _ => false } } object Record { import scala.reflect.runtime.{universe => ru} /** * Recursively converts a map to the record. * TODO Currently implemented via reflection. Search for better alternatives. */ def to[T <: Record](data: Map[String, Any])(implicit tt: ru.TypeTag[T], ct: ClassTag[T]): T = { to(data, tt.tpe).asInstanceOf[T] } private def to(data: Map[String, Any], tpe: ru.Type): Any = { //TODO use T's classloader, not ours val m = ru.runtimeMirror(getClass.getClassLoader) val cm = m.reflectModule(tpe.typeSymbol.companion.asModule) val ctorSymbol = cm.symbol.typeSignature.member(ru.TermName("apply")).alternatives.find(m => m.asMethod.paramLists.map(_.map(_.typeSignature)) match { case (typeSig :: Nil) :: Nil if typeSig =:= ru.typeOf[Map[String, Any]] => true case _ => false } ).get.asMethod val ctor = m.reflect(cm.instance).reflectMethod(ctorSymbol) val recordTpe = ru.typeOf[Record] val optionTpe = ru.typeOf[Option[_]] val fields = getFieldInfo(tpe) //val fields = tpe.decls.filter(m => m.isMethod && m.annotations.find(a => a.tree.tpe =:= fieldAnnTpe).isDefined).map(_.asMethod) val subRecordFields = fields.filter(m => m._2 <:< recordTpe) val optSubRecordFields = fields.filter(m => m._2 <:< optionTpe && m._2.typeArgs.head <:< recordTpe) val convertedData = subRecordFields.foldLeft(data) { (result, m) => val fieldName = m._1 val data = result.getOrElse(fieldName, throw new RecordException(s"missing data for $fieldName")).asInstanceOf[Map[String, Any]] result + (fieldName -> to(data, m._2)) } val convertedData2 = optSubRecordFields.foldLeft(convertedData) { (result, m) => val fieldName = m._1 val tpe = m._2.typeArgs.head result.get(fieldName).map(ddata => result + (fieldName -> to(ddata.asInstanceOf[Map[String, Any]], tpe)) ).getOrElse(result) } ctor(convertedData2) } /** * Returns record information from the fields annotation. * Basically the Same as RecordMacroImpl.getFieldInfo */ private def getFieldInfo(tpe: ru.Type): Map[String, ru.Type] = { val fieldsTpe = ru.typeOf[fields] val fieldsAnnot = tpe.typeSymbol.annotations.find(_.tree.tpe =:= fieldsTpe) val fieldNames = fieldsAnnot match { case None => Set.empty case Some(annot) => annot.tree.children.foldLeft(Set.empty[String])((result, a) => a match { case ru.Literal(name) => result + name.value.asInstanceOf[String] case _ => result } ) } fieldNames.map { name => //since there are at least two methods with the same name, we need to find the one without params val method = tpe.member(ru.TermName(name)).alternatives.find(m => m.asMethod.paramLists.isEmpty) (name, method.head.asMethod.returnType) }.toMap } }
MrDDaye/cna_cp1855
assignments/04_branching_programs/4-3_who_is_the_oldest/who_is_the_oldest.py
"""Determine the oldest age from three provided ages.""" def main() -> None: """Take three input ages and provide the oldest age.""" age_one: int = int(input('Enter 1st age: ')) age_two: int = int(input('Enter 2nd age: ')) age_three: int = int(input('Enter 3rd age: ')) ages: list[int] = [age_one, age_two, age_three] ages.sort() oldest: int = ages[-1] print(f'Oldest is {oldest}') if __name__ == "__main__": main()
takelifetime/competitive-programming
contests_atcoder/abc189/abc189_e_after.py
n = int(input()) points = [tuple(map(int, input().split())) for _ in range(n)] m = int(input()) ox = [(1, 0, 0)] oy = [(0, 1, 0)] for _ in range(m): o = tuple(map(int, input().split())) ax, bx, cx = ox[-1] ay, by, cy = oy[-1] if o[0] == 1: ox.append((ay, by, cy)) oy.append((-ax, -bx, -cx)) elif o[0] == 2: ox.append((-ay, -by, -cy)) oy.append((ax, bx, cx)) elif o[0] == 3: ox.append((-ax, -bx, -cx + 2*o[1])) oy.append((ay, by, cy)) elif o[0] == 4: ox.append((ax, bx, cx)) oy.append((-ay, -by, -cy + 2*o[1])) Q = int(input()) for _ in range(Q): t, p = map(int, input().split()) x, y = points[p-1] ax, bx, cx = ox[t] ay, by, cy = oy[t] print(ax * x + bx * y + cx, ay * x + by * y + cy)
acorg/acmacs-chart-2
cc/lispmds-token.hh
#pragma once #include <variant> #include <string> #include <vector> #include <stdexcept> #include <typeinfo> #include "acmacs-base/string.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/named-type.hh" // ---------------------------------------------------------------------- namespace acmacs::lispmds { class error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class type_mismatch : public error { public: using error::error; }; class keyword_no_found : public error { public: using error::error; }; class keyword_has_no_value : public error { public: using error::error; }; class nil { public: nil() = default; }; // class nil class boolean { public: boolean(bool aValue = false) : mValue{aValue} {} operator bool() const { return mValue; } private: bool mValue; }; // class boolean class number { public: number() = default; number(std::string aValue) : mValue(aValue) { for (auto& c: mValue) { switch (c) { case 'd': case 'D': c = 'e'; break; default: break; } } } number(std::string_view aValue) : number(std::string{aValue}) {} operator double() const { return std::stod(mValue); } operator float() const { return std::stof(mValue); } operator unsigned long() const { return std::stoul(mValue); } operator long() const { return std::stol(mValue); } private: std::string mValue; }; // class number class string : public acmacs::named_string_t<struct lispmds_string_tag_t> { public: using acmacs::named_string_t<struct lispmds_string_tag_t>::named_string_t; }; class symbol : public acmacs::named_string_t<struct lispmds_symbol_tag_t> { public: using acmacs::named_string_t<struct lispmds_symbol_tag_t>::named_string_t; }; class keyword : public acmacs::named_string_t<struct lispmds_keyword_tag_t> { public: using acmacs::named_string_t<struct lispmds_keyword_tag_t>::named_string_t; }; class list; using value = std::variant<nil, boolean, number, string, symbol, keyword, list>; // nil must be the first alternative, it is the default value; class list { public: list() = default; using iterator = decltype(std::declval<const std::vector<value>>().begin()); using reverse_iterator = decltype(std::declval<const std::vector<value>>().rbegin()); iterator begin() const { return mContent.begin(); } iterator end() const { return mContent.end(); } iterator begin() { return mContent.begin(); } iterator end() { return mContent.end(); } reverse_iterator rbegin() const { return mContent.rbegin(); } value& append(value&& to_add) { mContent.push_back(std::move(to_add)); return mContent.back(); } const value& operator[](size_t aIndex) const { return mContent.at(aIndex); } const value& operator[](std::string_view aKeyword) const; size_t size() const { return mContent.size(); } bool empty() const { return mContent.empty(); } private: std::vector<value> mContent; }; // class list // ---------------------------------------------------------------------- inline value& append(value& target, value&& to_add) { return std::visit([&](auto&& arg) -> value& { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, list>) return arg.append(std::move(to_add)); else throw type_mismatch{"not a lispmds::list, cannot append value"}; }, target); } inline const value& get_(const value& val, size_t aIndex) { using namespace std::string_literals; return std::visit([aIndex](const auto& arg) -> const value& { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, list>) return arg[aIndex]; else throw type_mismatch{"not a lispmds::list, cannot use [index]: "s + typeid(arg).name()}; }, val); } inline const value& get_(const value& val, int aIndex) { return get_(val, static_cast<size_t>(aIndex)); } inline const value& get_(const value& val, std::string aKeyword) { return std::visit([aKeyword](auto&& arg) -> const value& { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, list>) return arg[aKeyword]; else throw type_mismatch{"not a lispmds::list, cannot use [keyword]"}; }, val); } template <typename Arg, typename... Args> inline const value& get(const value& val, Arg&& arg, Args&&... args) { if constexpr (sizeof...(args) == 0) { return get_(val, std::forward<Arg>(arg)); } else { return get(get_(val, std::forward<Arg>(arg)), args...); } } inline size_t size(const value& val) { return std::visit([](auto&& arg) -> size_t { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, list>) return arg.size(); else if constexpr (std::is_same_v<T, nil>) return 0; else throw type_mismatch{"not a lispmds::list, cannot use size()"}; }, val); } template <typename... Args> inline size_t size(const value& val, Args&&... args) { return size(get(val, args...)); } inline bool empty(const value& val) { return std::visit([](auto&& arg) -> bool { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, list>) return arg.empty(); else if constexpr (std::is_same_v<T, nil>) return true; else throw type_mismatch{"not a lispmds::list, cannot use empty()"}; }, val); } template <typename... Args> inline bool empty(const value& val, Args&&... args) { return empty(get(val, args...)); } // ---------------------------------------------------------------------- inline const value& list::operator[](std::string_view aKeyword) const { auto p = mContent.begin(); while (p != mContent.end() && (!std::get_if<keyword>(&*p) || std::get<keyword>(*p) != aKeyword)) ++p; if (p == mContent.end()) throw keyword_no_found{std::string{aKeyword}}; ++p; if (p == mContent.end()) throw keyword_has_no_value{std::string{aKeyword}}; return *p; } // ---------------------------------------------------------------------- value parse_string(std::string_view aData); } // namespace acmacs::lispmds // ---------------------------------------------------------------------- namespace acmacs { inline std::string to_string(const lispmds::nil&) { return "nil"; } inline std::string to_string(const lispmds::boolean& val) { return val ? "t" : "f"; } inline std::string to_string(const lispmds::number& val) { return acmacs::to_string(static_cast<double>(val)); } inline std::string to_string(const lispmds::string& val) { return '"' + static_cast<std::string>(val) + '"'; } inline std::string to_string(const lispmds::symbol& val) { return '\'' + static_cast<std::string>(val); } inline std::string to_string(const lispmds::keyword& val) { return static_cast<std::string>(val); } std::string to_string(const lispmds::value& val); inline std::string to_string(const lispmds::list& list) { std::string result{"(\n"}; for (const lispmds::value& val: list) { result.append(to_string(val)); result.append(1, '\n'); } result.append(")\n"); return result; } inline std::string to_string(const lispmds::value& val) { return std::visit([](auto&& arg) -> std::string { return to_string(arg); }, val); } } // namespace acmacs // ---------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& s, const acmacs::lispmds::value& val) { return s << acmacs::to_string(val); } template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_same_v<decltype(acmacs::to_string(std::declval<T>())), std::string>, std::string>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const T& val, FormatCtx& ctx) { return fmt::formatter<std::string>::format(acmacs::to_string(val), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
GrinCash/Grinc-core
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/themes/qabstractfileiconengine.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qabstractfileiconengine_p.h" #include <qpixmapcache.h> QT_BEGIN_NAMESPACE /*! \class QAbstractFileIconEngine \brief Helper base class for retrieving icons for files for usage by QFileIconProvider and related. Reimplement availableSizes() and new virtual filePixmap() and return icons created with this engine from QPlatformTheme::fileIcon(). Note: The class internally caches pixmaps for files by suffix (with the exception of some files on Windows), but not for directories (since directory icons may have overlay icons on Windows). You might want to cache pixmaps for directories in your implementation. \since 5.8 \internal \sa QFileIconProvider::DontUseCustomDirectoryIcons, QPlatformTheme \ingroup qpa */ QPixmap QAbstractFileIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) { Q_UNUSED(mode); Q_UNUSED(state); if (!size.isValid()) return QPixmap(); QString key = cacheKey(); if (key.isEmpty()) return filePixmap(size, mode, state); key += QLatin1Char('_') + QString::number(size.width()); QPixmap result; if (!QPixmapCache::find(key, result)) { result = filePixmap(size, mode, state); if (!result.isNull()) QPixmapCache::insert(key, result); } return result; } QSize QAbstractFileIconEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state) { const QList<QSize> &sizes = availableSizes(mode, state); const int numberSizes = sizes.length(); if (numberSizes == 0) return QSize(); // Find the smallest available size whose area is still larger than the input // size. Otherwise, use the largest area available size. (We don't assume the // platform theme sizes are sorted, hence the extra logic.) const int sizeArea = size.width() * size.height(); QSize actualSize = sizes.first(); int actualArea = actualSize.width() * actualSize.height(); for (int i = 1; i < numberSizes; ++i) { const QSize &s = sizes.at(i); const int a = s.width() * s.height(); if ((sizeArea <= a && a < actualArea) || (actualArea < sizeArea && actualArea < a)) { actualSize = s; actualArea = a; } } if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height())) actualSize.scale(size, Qt::KeepAspectRatio); return actualSize; } /* Reimplement to return a cache key for the entry. An empty result indicates * the icon should not be cached (for example, directory icons having custom icons). */ QString QAbstractFileIconEngine::cacheKey() const { if (!m_fileInfo.isFile() || m_fileInfo.isSymLink() || m_fileInfo.isExecutable()) return QString(); const QString &suffix = m_fileInfo.suffix(); return QLatin1String("qt_.") + (suffix.isEmpty() ? m_fileInfo.fileName() : suffix); // handle "Makefile" ;) } QT_END_NAMESPACE
ssichynskyi/ui_plus_api_web_testing
framework/base.py
<reponame>ssichynskyi/ui_plus_api_web_testing import logging class LoggingObject: def __init__(self, name=None): """Base class for all objects with logging Args: name: logger name. By convention: the name of the logger is the name of the object. Get it via __name__ and provide as an argument to super class constructor """ if not name: name = __name__ self.logger = logging.getLogger(name)
uk-gov-mirror/companieshouse.dissolution-api
src/main/java/uk/gov/companieshouse/exception/UnauthorisedException.java
<filename>src/main/java/uk/gov/companieshouse/exception/UnauthorisedException.java package uk.gov.companieshouse.exception; public class UnauthorisedException extends RuntimeException { public UnauthorisedException(String message) { super(message); } }
kevinzhwl/ObjectARXMod
2006/samples/database/ARXDBG/Reactors/ArxDbgUiTdcPersistentReactors.cpp
<gh_stars>1-10 // // (C) Copyright 1998-1999 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // #include "stdafx.h" #include "ArxDbgUiTdcPersistentReactors.h" #include "ArxDbgUiDlgObjState.h" #include "ArxDbgUtils.h" #include "ArxDbgApp.h" #include "ArxDbgUiTdmREactors.h" #include "ArxDbgDocLockWrite.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // static state variables for showing state of notifying object BOOL ArxDbgUiTdcPersistentReactors::m_doStateModified = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateCancelled = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateErased = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateCopied = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateGoodbye = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateOpenMod = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateSubObjMod = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateModUndone = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateModXdata = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateModGraphics = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateUnappended = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateReappended = FALSE; BOOL ArxDbgUiTdcPersistentReactors::m_doStateClosed = FALSE; // These statics are all MDI aware ArxDbgPersistentObjReactor* ArxDbgUiTdcPersistentReactors::m_objReactor = NULL; ArxDbgPersistentEntReactor* ArxDbgUiTdcPersistentReactors::m_entReactor = NULL; // names of our dictionaries for reactor storage LPCTSTR ArxDbgUiTdcPersistentReactors::m_dictName = _T("ARXDBG_PERSISTENT_REACTORS"); /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::ArxDbgUiTdcPersistentReactors ** ** **jma ** *************************************/ ArxDbgUiTdcPersistentReactors::ArxDbgUiTdcPersistentReactors() : ArxDbgUiTdcObjReactorsBase() { //{{AFX_DATA_INIT(ArxDbgUiTdcPersistentReactors) //}}AFX_DATA_INIT } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::DoDataExchange ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::DoDataExchange(CDataExchange* pDX) { ArxDbgUiTdcObjReactorsBase::DoDataExchange(pDX); //{{AFX_DATA_MAP(ArxDbgUiTdcPersistentReactors) DDX_Check(pDX, ARXDBG_CB_STATE_MODIFIED, m_doStateModified); DDX_Check(pDX, ARXDBG_CB_STATE_CANCELLED, m_doStateCancelled); DDX_Check(pDX, ARXDBG_CB_STATE_ERASED, m_doStateErased); DDX_Check(pDX, ARXDBG_CB_STATE_COPIED, m_doStateCopied); DDX_Check(pDX, ARXDBG_CB_STATE_GOODBYE, m_doStateGoodbye); DDX_Check(pDX, ARXDBG_CB_STATE_OPENMOD, m_doStateOpenMod); DDX_Check(pDX, ARXDBG_CB_STATE_SUBOBJMOD, m_doStateSubObjMod); DDX_Check(pDX, ARXDBG_CB_STATE_MODUNDONE, m_doStateModUndone); DDX_Check(pDX, ARXDBG_CB_STATE_MODXDATA, m_doStateModXdata); DDX_Check(pDX, ARXDBG_CB_STATE_MODGRAPHICS, m_doStateModGraphics); DDX_Check(pDX, ARXDBG_CB_STATE_UNAPPENDED, m_doStateUnappended); DDX_Check(pDX, ARXDBG_CB_STATE_REAPPENDED, m_doStateReappended); DDX_Check(pDX, ARXDBG_CB_STATE_CLOSED, m_doStateClosed); //}}AFX_DATA_MAP } ///////////////////////////////////////////////////////////////////////////// // ArxDbgUiTdcPersistentReactors message handlers BEGIN_MESSAGE_MAP(ArxDbgUiTdcPersistentReactors, ArxDbgUiTdcObjReactorsBase) //{{AFX_MSG_MAP(ArxDbgUiTdcPersistentReactors) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // ArxDbgUiTdcPersistentReactors message handlers /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::OnInitDialog ** ** **jma ** *************************************/ BOOL ArxDbgUiTdcPersistentReactors::OnInitDialog() { ArxDbgUiTdcObjReactorsBase::OnInitDialog(); return TRUE; } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::getPersistentObjReactor ** ** **jma ** *************************************/ AcDbObjectId ArxDbgUiTdcPersistentReactors::getPersistentObjReactor(AcDbDatabase* db, bool createIfNotFound) { static LPCTSTR dictEntryName = _T("ARXDBG_PERSISTENT_OBJ_REACTOR"); AcDbObjectId prId; AcDbDictionary* prDict; // first see if its already there without "disturbing" anyone by opening them // for write. prDict = ArxDbgUtils::openDictionaryForRead(m_dictName, db); if (prDict != NULL) { if (prDict->getAt(dictEntryName, prId) == Acad::eOk) { prDict->close(); return prId; } prDict->close(); } // couldn't find it, bail if we aren't supposed to create it. if (createIfNotFound == false) return AcDbObjectId::kNull; // not here yet, so make an entry prDict = ArxDbgUtils::openDictionaryForWrite(m_dictName, true, db); if (prDict == NULL) return AcDbObjectId::kNull; Acad::ErrorStatus es; ArxDbgPersistentObjReactor* pr = new ArxDbgPersistentObjReactor; es = prDict->setAt(dictEntryName, pr, prId); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); ArxDbgUtils::alertBox(_T("ERROR: Could not add entry to dictionary.")); delete pr; prDict->close(); return AcDbObjectId::kNull; } else { pr->close(); prDict->close(); return prId; } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::getPersistentEntReactor ** ** **jma ** *************************************/ AcDbObjectId ArxDbgUiTdcPersistentReactors::getPersistentEntReactor(AcDbDatabase* db, bool createIfNotFound) { static LPCTSTR dictEntryName = _T("ARXDBG_PERSISTENT_ENT_REACTOR"); AcDbObjectId prId; AcDbDictionary* prDict; // first see if its already there without "disturbing" anyone by opening them // for write. prDict = ArxDbgUtils::openDictionaryForRead(m_dictName, db); if (prDict != NULL) { if (prDict->getAt(dictEntryName, prId) == Acad::eOk) { prDict->close(); return prId; } prDict->close(); } // couldn't find it, bail if we aren't supposed to create it. if (createIfNotFound == false) return AcDbObjectId::kNull; // not here yet, so make an entry prDict = ArxDbgUtils::openDictionaryForWrite(m_dictName, true, db); if (prDict == NULL) return AcDbObjectId::kNull; Acad::ErrorStatus es; ArxDbgPersistentEntReactor* pr = new ArxDbgPersistentEntReactor; es = prDict->setAt(dictEntryName, pr, prId); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); ArxDbgUtils::alertBox(_T("ERROR: Could not add entry to dictionary.")); delete pr; prDict->close(); return AcDbObjectId::kNull; } else { pr->close(); prDict->close(); return prId; } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::getAttachedObjects ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::getAttachedObjects(AcDbObjectIdArray& objIds) { AcDbVoidPtrArray dbPtrs; ArxDbgUtils::getAllDatabases(dbPtrs); AcDbObjectId prId; ArxDbgPersistentObjReactor* peReactor; Acad::ErrorStatus es; AcDbObjectIdArray tmpIds; int len = dbPtrs.length(); for (int i=0; i<len; i++) { prId = getPersistentObjReactor(static_cast<AcDbDatabase*>(dbPtrs[i]), false); es = acdbOpenObject(peReactor, prId, AcDb::kForRead); if (es == Acad::eOk) { tmpIds.setLogicalLength(0); // reusing array for each database peReactor->getAttachedToObjs(tmpIds); peReactor->close(); objIds.append(tmpIds); } } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::getAttachedEntities ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::getAttachedEntities(AcDbObjectIdArray& objIds) { AcDbVoidPtrArray dbPtrs; ArxDbgUtils::getAllDatabases(dbPtrs); AcDbObjectId prId; ArxDbgPersistentEntReactor* peReactor; Acad::ErrorStatus es; AcDbObjectIdArray tmpIds; int len = dbPtrs.length(); for (int i=0; i<len; i++) { prId = getPersistentEntReactor(static_cast<AcDbDatabase*>(dbPtrs[i]), false); es = acdbOpenObject(peReactor, prId, AcDb::kForRead); if (es == Acad::eOk) { tmpIds.setLogicalLength(0); // reusing array for each database peReactor->getAttachedToObjs(tmpIds); peReactor->close(); objIds.append(tmpIds); } } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::detachSelectedEnts ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::detachSelectedEnts(const AcDbObjectIdArray& objIds) { Acad::ErrorStatus es; AcDbEntity* ent; ArxDbgPersistentEntReactor* peReactor; AcDbObjectId prId; ArxDbgDocLockWrite docLock; // these potentially came from other documents int len = objIds.length(); for (int i=0; i<len; i++) { es = docLock.lock(objIds[i].database()); // lock the document associated with this database if (es == Acad::eOk) { es = acdbOpenAcDbEntity(ent, objIds[i], AcDb::kForWrite, true); if (es == Acad::eOk) { prId = getPersistentEntReactor(objIds[i].database(), true); ent->removePersistentReactor(prId); es = acdbOpenObject(peReactor, prId, AcDb::kForWrite); if (es == Acad::eOk) { peReactor->detachFrom(ent->objectId()); peReactor->close(); } else { CString str; str.Format(_T("ERROR: Could not update backward reference in reactor: (%s)"), ArxDbgUtils::rxErrorStr(es)); ArxDbgUtils::stopAlertBox(str); } ent->close(); } else { ArxDbgUtils::rxErrorAlert(es); } } else { ArxDbgUtils::rxErrorAlert(es); } } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::detachSelectedObjs ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::detachSelectedObjs(const AcDbObjectIdArray& objIds) { Acad::ErrorStatus es; AcDbEntity* ent; ArxDbgPersistentObjReactor* peReactor; AcDbObjectId prId; ArxDbgDocLockWrite docLock; // these potentially came from other documents int len = objIds.length(); for (int i=0; i<len; i++) { es = docLock.lock(objIds[i].database()); // lock the document associated with this database if (es == Acad::eOk) { es = acdbOpenAcDbEntity(ent, objIds[i], AcDb::kForWrite, true); if (es == Acad::eOk) { prId = getPersistentObjReactor(objIds[i].database(), true); ent->removePersistentReactor(prId); es = acdbOpenObject(peReactor, prId, AcDb::kForWrite); if (es == Acad::eOk) { peReactor->detachFrom(ent->objectId()); peReactor->close(); } else { CString str; str.Format(_T("ERROR: Could not update backward reference in reactor: (%s)"), ArxDbgUtils::rxErrorStr(es)); ArxDbgUtils::stopAlertBox(str); } ent->close(); } else { ArxDbgUtils::rxErrorAlert(es); } } else { ArxDbgUtils::rxErrorAlert(es); } } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::attachObjReactors ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::attachObjReactors(const AcDbObjectIdArray& objIds) { Acad::ErrorStatus es; AcDbObject* obj; ArxDbgPersistentObjReactor* peReactor; AcDbObjectId prId; ArxDbgDocLockWrite docLock; // these potentially came from other documents int len = objIds.length(); for (int i=0; i<len; i++) { es = docLock.lock(objIds[i].database()); // lock the document associated with this database if (es == Acad::eOk) { es = acdbOpenAcDbObject(obj, objIds[i], AcDb::kForWrite, true); if (es == Acad::eOk) { prId = getPersistentObjReactor(objIds[i].database(), true); if (ArxDbgUiTdmReactors::hasPersistentReactor(obj, prId)) { ArxDbgUtils::alertBox(_T("That object already has the reactor attached.")); } else { obj->addPersistentReactor(prId); es = acdbOpenObject(peReactor, prId, AcDb::kForWrite); if (es == Acad::eOk) { peReactor->attachTo(obj->objectId()); peReactor->close(); } else { CString str; str.Format(_T("ERROR: Could not update backward reference in reactor: (%s)"), ArxDbgUtils::rxErrorStr(es)); ArxDbgUtils::stopAlertBox(str); } } obj->close(); } else { ArxDbgUtils::rxErrorMsg(es); } } else { ArxDbgUtils::rxErrorAlert(es); } } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::attachEntReactors ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::attachEntReactors() { // unfortunately, this structure for making this page know about the main // dialog means that we could never use this page within another main dialog // container. Oh well... ArxDbgUiTdmReactors* tdmReactors = static_cast<ArxDbgUiTdmReactors*>(GetMainDialog()); tdmReactors->attachEntPersistentReactor(); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::detachEntReactors ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::detachEntReactors() { // unfortunately, this structure for making this page know about the main // dialog means that we could never use this page within another main dialog // container. Oh well... ArxDbgUiTdmReactors* tdmReactors = static_cast<ArxDbgUiTdmReactors*>(GetMainDialog()); tdmReactors->detachEntPersistentReactor(); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxCacelled ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxCacelled(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateCancelled) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Cancelled")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxCopied ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxCopied(const AcDbObject* obj, const AcDbObject* newObject) { if (ArxDbgUiTdcPersistentReactors::m_doStateCopied) { ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Copied (source object)")); ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Copied (new object)")); } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxErased ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxErased(const AcDbObject* obj, Adesk::Boolean isErasing) { if (ArxDbgUiTdcPersistentReactors::m_doStateErased) { if (isErasing) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Erase")); else ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Un-erase")); } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxGoodbye ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxGoodbye(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateGoodbye) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Goodbye")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxOpenedModify ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxOpenedModify(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateOpenMod) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Open For Modify")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxModified ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxModified(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateModified) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Modified")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxSubObjModified ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxSubObjModified(const AcDbObject* obj, const AcDbObject* subObj) { if (ArxDbgUiTdcPersistentReactors::m_doStateSubObjMod) { ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("SubObject Modified (main object)")); ArxDbgUiTdcPersistentReactors::doStateDbox(subObj, _T("SubObject Modified (sub-object)")); } } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxModifyUndone ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxModifyUndone(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateModUndone) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Modify Undone")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxModifiedXdata ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxModifiedXdata(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateModXdata) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Modified Xdata")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxModifiedGraphics ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxModifiedGraphics(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateModGraphics) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Modified Graphics")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxUnappended ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxUnappended(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateUnappended) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Un-appended")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxReappended ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxReappended(const AcDbObject* obj) { if (ArxDbgUiTdcPersistentReactors::m_doStateReappended) ArxDbgUiTdcPersistentReactors::doStateDbox(obj, _T("Re-appended")); } /**************************************************************************** ** ** ArxDbgUiTdcPersistentReactors::doStateDboxClosed ** ** **jma ** *************************************/ void ArxDbgUiTdcPersistentReactors::doStateDboxClosed(const AcDbObjectId& objId) { if (ArxDbgUiTdcPersistentReactors::m_doStateClosed) ArxDbgUiTdcPersistentReactors::doStateDbox(objId, _T("Object Closed")); }
kusumandaru/EBWiki
app/controllers/conversations_controller.rb
<gh_stars>10-100 # frozen_string_literal: true # Controller for conversations of EBWiki messages class ConversationsController < ApplicationController before_action :authenticate_user! def new @other_users = User.where.not(id: current_user.id).pluck(:name, :id) end def create recipients = User.where(id: conversation_params[:recipients]) conversation = current_user .send_message(recipients, conversation_params[:body], conversation_params[:subject]) .conversation flash[:success] = 'Your message was successfully sent!' redirect_to conversation_path(conversation) end def show @receipts = conversation.receipts_for(current_user) # mark conversation as read conversation.mark_as_read(current_user) end def reply current_user.reply_to_conversation(conversation, message_params[:body]) flash[:notice] = 'Your reply message was successfully sent!' redirect_to conversation_path(conversation) end def trash conversation.move_to_trash(current_user) redirect_to mailbox_inbox_path end def untrash conversation.untrash(current_user) redirect_to mailbox_inbox_path end def after_sign_up_path_for(resource) stored_location_for(resource) || super end def after_sign_in_path_for(resource) stored_location_for(resource) || super end private def mailbox @mailbox ||= current_user.mailbox end def conversation @conversation ||= mailbox.conversations.find(params[:id]) end def conversation_params params.require(:conversation).permit(:subject, :body, recipients: []) end def message_params params.require(:message).permit(:body, :subject) end end
ricardyn/ironpython-stubs
stubs.min/System/Windows/__init___parts/TemplatePartAttribute.py
<gh_stars>1-10 class TemplatePartAttribute(Attribute,_Attribute): """ Represents an attribute that is applied to the class definition to identify the types of the named parts that are used for templating. TemplatePartAttribute() """ def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass Name=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the pre-defined name of the part. Get: Name(self: TemplatePartAttribute) -> str Set: Name(self: TemplatePartAttribute)=value """ Type=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the type of the named part this attribute is identifying. Get: Type(self: TemplatePartAttribute) -> Type Set: Type(self: TemplatePartAttribute)=value """
KevinScholtes/ANTsX
Temporary/itkFEMDiscConformalMap.cxx
<filename>Temporary/itkFEMDiscConformalMap.cxx /*========================================================================= Program: Insight Segmentation & Registration Toolkit Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for detailm_Solver. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _FEMDiscConformalMap_hxx #define _FEMDiscConformalMap_hxx #include <vcl_compiler.h> #include <iostream> #include <cmath> #include <iostream> #include <vnl/vnl_real_polynomial.h> #include <vnl/vnl_vector.h> #include <vnl/vnl_vector_fixed.h> #include <itkMath.h> #include "vtkDelaunay2D.h" #include "vtkSelectPolyData.h" #include "vtkFloatArray.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkFEMDiscConformalMap.h" #include "itkFEMLoadNode.h" #include "itkSurfaceMeshCurvature.h" #include "vtkClipPolyData.h" #include "vtkContourFilter.h" #include "vtkSmartPointer.h" namespace itk { template <typename TSurface, typename TImage, unsigned int TDimension> FEMDiscConformalMap<TSurface, TImage, TDimension> ::FEMDiscConformalMap() { m_Sigma = 2.0e-4; m_ParameterFileName = ""; m_NorthPole = 0; m_SourceNodeNumber = 1; this->m_DistanceCostWeight = 1; this->m_LabelCostWeight = 0; m_Pi = 3.14159265358979323846; m_ReadFromFile = false; m_Debug = false; m_FindingRealSolution = true; this->m_SurfaceMesh = nullptr; for( int i = 0; i < 7; i++ ) { m_PoleElementsGN[i] = 0; } this->m_MapToCircle = true; this->m_MapToSquare = false; this->m_ParamWhileSearching = true; m_Smooth = 2.0; this->m_Label_to_Flatten = 0; this->m_FlatImage = nullptr; manifoldIntegrator = ManifoldIntegratorType::New(); } template <typename TSurface, typename TImage, unsigned int TDimension> bool FEMDiscConformalMap<TSurface, TImage, TDimension> ::InBorder(typename FEMDiscConformalMap<TSurface, TImage, TDimension>::GraphSearchNodePointer g) { if( this->m_HelpFindLoop[g->GetIdentity()] > 0 ) { return true; } else { return false; } float dist = g->GetTotalCost(); if( dist > m_MaxCost && dist < m_MaxCost + 1.0 ) { return true; } return false; } template <typename TSurface, typename TImage, unsigned int TDimension> bool FEMDiscConformalMap<TSurface, TImage, TDimension> ::InDisc(typename FEMDiscConformalMap<TSurface, TImage, TDimension>::GraphSearchNodePointer g) { // if ( this->m_HelpFindLoop[ g->GetIdentity() ] != 0 ) return true; // else return false; // if ( g->WasVisited() ) return true; float d = g->GetTotalCost(); for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { if( d <= this->m_DiscBoundaryList[i]->GetTotalCost() ) { return true; } } return false; if( g->GetPredecessor() ) { return true; } else { return false; } } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::FindSource(IndexType index) { vtkPoints* vtkpoints = this->m_SurfaceMesh->GetPoints(); int numPoints = vtkpoints->GetNumberOfPoints(); float mindist = 1.e9; for( int i = 0; i < numPoints; i++ ) { double* pt = vtkpoints->GetPoint(i); float dist = 0.0; for( int j = 0; j < ImageDimension; j++ ) { dist += (pt[j] - (float)index[j]) * (pt[j] - (float)index[j]); } dist = sqrt(dist); if( dist < mindist ) { mindist = dist; m_SourceNodeNumber = i; } } } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::FindMeanSourceInLabel(unsigned int label ) { vtkPoints* vtkpoints = this->m_SurfaceMesh->GetPoints(); int numPoints = vtkpoints->GetNumberOfPoints(); float mindist = 1.e9; float meanx = 0., meany = 0, meanz = 0; unsigned long ct = 0; vtkDataArray* labels = this->m_SurfaceMesh->GetPointData()->GetArray("Label"); vtkDataArray* features = nullptr; if( this->m_SurfaceFeatureMesh ) { if( this->m_SurfaceFeatureMesh->GetPointData()->GetArray("Feature") ) { features = this->m_SurfaceFeatureMesh->GetPointData()->GetArray("Feature"); } else { features = labels; } } if( !labels ) { std::cout << " cant get Labels --- need an array named Label in the mesh ... " << std::endl; std::exception(); } else { std::cout << " got Labels " << std::endl; } for( int i = 0; i < numPoints; i++ ) { double* pt = vtkpoints->GetPoint(i); manifoldIntegrator->GetGraphNode(i)->SetValue(labels->GetTuple1(i), 3); // std::cout << " label " << labels->GetTuple1(i) << " & " << label <<std::endl; if( fabs( labels->GetTuple1(i) - label ) < 0.5 ) { // std::cout << " choose " << labels->GetTuple1(i) << " & " << label << std::endl; meanx += pt[0]; meany += pt[1]; meanz += pt[2]; ct++; // i=numPoints+1; } else { // ct+=0; manifoldIntegrator->GetGraphNode(i)->SetUnVisitable(); } } meanx /= (float)ct; meany /= (float)ct; meanz /= (float)ct; for( int i = 0; i < numPoints; i++ ) { double* pt = vtkpoints->GetPoint(i); float dist = 0.0; dist += (pt[0] - meanx) * (pt[0] - meanx); dist += (pt[1] - meany) * (pt[1] - meany); dist += (pt[2] - meanz) * (pt[2] - meanz); dist = sqrt(dist); if( dist < mindist && fabs( label - labels->GetTuple1(i) ) < 0.5 ) { mindist = dist; m_SourceNodeNumber = i; // std::cout << " label " << label << " chose " << labels->GetTuple1(i) << std::endl; } } if( this->FindLoopAroundNode( this->m_SourceNodeNumber ) == 2 ) { std::cout << " found loop " << std::endl; } if( ct > 0 ) { std::cout << meanx << " " << meany << " " << meanz << std::endl; } else { std::cout << " no label " << label << " exiting " << std::endl; std::exception(); } } template <typename TSurface, typename TImage, unsigned int TDimension> float FEMDiscConformalMap<TSurface, TImage, TDimension> ::AssessNodeDistanceCost( unsigned int nodeid ) { return manifoldIntegrator->GetGraphNode(nodeid)->GetTotalCost(); /* diff=G1->GetLocation()-G3->GetLocation(); tangentlength=0; for (unsigned int d=0; d<diff.Size(); d++) tangentlength+=diff[d]*diff[d]; elementlength+=sqrt(tangentlength); diff=G2->GetLocation()-G3->GetLocation(); tangentlength=0; for (unsigned int d=0; d<diff.Size(); d++) tangentlength+=diff[d]*diff[d]; elementlength+=sqrt(tangentlength); */ } template <typename TSurface, typename TImage, unsigned int TDimension> float FEMDiscConformalMap<TSurface, TImage, TDimension> ::GetBoundaryParameterForSquare( unsigned int nodeid, unsigned int whichParam ) { // compute loop length and check validity float tangentlength = 0, totallength = 0, nodeparam = 0, x = 0, y = 0; typename GraphSearchNodeType::NodeLocationType diff; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { unsigned int nxt = ( ( i + 1 ) % this->m_DiscBoundaryList.size() ); diff = this->m_DiscBoundaryList[i]->GetLocation() - this->m_DiscBoundaryList[nxt]->GetLocation(); if( this->m_DiscBoundaryList[i]->GetIdentity() == nodeid ) { nodeparam = totallength; } tangentlength = 0; for( unsigned int d = 0; d < diff.Size(); d++ ) { tangentlength += diff[d] * diff[d]; } totallength += tangentlength; } float arclength = nodeparam / totallength; if( arclength <= 0.25 ) { x = 0; y = arclength / 0.25; /* 0 => 1 */ } else if( arclength <= 0.5 ) { x = (0.5 - arclength) / 0.25; /* 0 => 1 */ y = 1; } else if( arclength <= 0.75 ) { x = 1; y = (0.75 - arclength) / 0.25; /* 1 => 0 */ } else if( arclength <= 1 ) { x = (1 - arclength) / 0.25; /* 1 => 0 */ y = 0; } // std::cout <<" x " << x << " y " << y << " al " << arclength << std::endl; if( whichParam == 0 ) { return x; } else if( whichParam == 1 ) { return y; } else { return arclength; } } template <typename TSurface, typename TImage, unsigned int TDimension> float FEMDiscConformalMap<TSurface, TImage, TDimension> ::GetBoundaryParameterForCircle( unsigned int nodeid, unsigned int whichParam ) { // compute loop length and check validity float tangentlength = 0, totallength = 0, nodeparam = 0; typename GraphSearchNodeType::NodeLocationType diff; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { unsigned int nxt = ( ( i + 1 ) % this->m_DiscBoundaryList.size() ); diff = this->m_DiscBoundaryList[i]->GetLocation() - this->m_DiscBoundaryList[nxt]->GetLocation(); if( this->m_DiscBoundaryList[i]->GetIdentity() == nodeid ) { nodeparam = totallength; } tangentlength = 0; for( unsigned int d = 0; d < diff.Size(); d++ ) { tangentlength += diff[d] * diff[d]; } totallength += tangentlength; } float arclength = nodeparam / totallength * M_PI * 2; if( whichParam == 0 ) { return cos(arclength); } else if( whichParam == 1 ) { return sin(arclength); } else { return arclength; } } template <typename TSurface, typename TImage, unsigned int TDimension> unsigned int FEMDiscConformalMap<TSurface, TImage, TDimension> ::AddVertexToLoop() { // compute loop length and check validity float tangentlength = 0, totallength = 0; bool isvalid = true; typename GraphSearchNodeType::NodeLocationType diff; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { unsigned int nxt = ( ( i + 1 ) % this->m_DiscBoundaryList.size() ); // std::cout << " this->m_DiscBoundaryList[i]->GetLocation() " << // this->m_DiscBoundaryList[i]->GetLocation() << // std::endl; diff = this->m_DiscBoundaryList[i]->GetLocation() - this->m_DiscBoundaryList[nxt]->GetLocation(); tangentlength = 0; for( unsigned int d = 0; d < diff.Size(); d++ ) { tangentlength += diff[d] * diff[d]; } totallength += tangentlength; // check if the next node is in the current node's neighborlist isvalid = false; for( unsigned int n = 0; n < this->m_DiscBoundaryList[i]->m_NumberOfNeighbors; n++ ) { if( this->m_DiscBoundaryList[i]->m_Neighbors[n] == this->m_DiscBoundaryList[nxt] ) { isvalid = true; } } } std::cout << " length " << totallength << " valid? " << isvalid << " entries " << this->m_DiscBoundaryList.size() << " gsz " << this->m_HelpFindLoop.size() << std::endl; /** now find a node with HelpFindLoop value == 0 that minimally changes the length ... and that has a root neighbor and next neighbor consistent with the original edge */ unsigned int newnodeid = 0; unsigned int nodeparam = 0; // the position in the curve parameter float newedgelength = 1.e9; // minimize this GraphSearchNodePointer G1, G2, G3, BestG = nullptr; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { unsigned int nxt = ( ( i + 1 ) % this->m_DiscBoundaryList.size() ); G1 = this->m_DiscBoundaryList[i]; G2 = this->m_DiscBoundaryList[nxt]; G3 = nullptr; /** 3 conditions : (1) HelpFindLoop == 0 (2) am neighbor of curnode (3) am neighbor of next node (4) minlength */ for( unsigned int n = 0; n < G1->m_NumberOfNeighbors; n++ ) { for( unsigned int m = 0; m < G2->m_NumberOfNeighbors; m++ ) { long hfl = abs(this->m_HelpFindLoop[G1->m_Neighbors[n]->GetIdentity()]); hfl += abs(this->m_HelpFindLoop[G2->m_Neighbors[m]->GetIdentity()]); if( G1->m_Neighbors[n] == G2->m_Neighbors[m] && hfl == 0 ) { G3 = G1->m_Neighbors[n]; n = G1->m_NumberOfNeighbors; m = G2->m_NumberOfNeighbors; float elementlength = this->AssessNodeDistanceCost( G3->GetIdentity() ); if( elementlength < newedgelength ) { newedgelength = elementlength; BestG = G3; newnodeid = G3->GetIdentity(); nodeparam = i; } } } } } if( !BestG ) { std::cout << " does not exist " << std::endl; return false; } if( this->m_HelpFindLoop[BestG->GetIdentity()] != 0 ) { std::cout << " already done " << std::endl; return false; } std::vector<GraphSearchNodePointer> neighborlist; long paramct = 0; totallength = 0; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { paramct++; neighborlist.push_back( this->m_DiscBoundaryList[i] ); this->m_HelpFindLoop[this->m_DiscBoundaryList[i]->GetIdentity()] = paramct; if( i == nodeparam ) { paramct++; neighborlist.push_back( BestG ); this->m_HelpFindLoop[BestG->GetIdentity()] = paramct; } } // std::cout << " len1 " << this->m_DiscBoundaryList.size() << " len2 " << neighborlist.size() << // std::endl; this->SetDiscBoundaryList( neighborlist ); // this->m_DiscBoundaryList.assign(neighborlist.begin(),neighborlist.end()); /* for (unsigned int i=0; i<this->m_DiscBoundaryList.size(); i++) { unsigned int nxt=( ( i+1 ) % this->m_DiscBoundaryList.size() ); diff=this->m_DiscBoundaryList[i]->GetLocation()-this->m_DiscBoundaryList[nxt]->GetLocation(); tangentlength=0; for (unsigned int d=0; d<diff.Size(); d++) tangentlength+=diff[d]*diff[d]; totallength+=tangentlength; } */ /** find out if there is a "short-cut" that lets you traverse the loop without hitting all the nodes ... */ /** at the same time, you want to maximize the enclosed area */ neighborlist.clear(); paramct = 0; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { paramct++; neighborlist.push_back( this->m_DiscBoundaryList[i] ); this->m_HelpFindLoop[this->m_DiscBoundaryList[i]->GetIdentity()] = paramct; if( this->m_DiscBoundaryList[i]->GetIdentity() == newnodeid ) { // find the parameter of any of this fellows neighors ... // if it's greater than i+1 then skip ahead long bestparam = this->m_HelpFindLoop[this->m_DiscBoundaryList[i]->GetIdentity()] + 1; for( unsigned int n = 0; n < this->m_DiscBoundaryList[i]->m_NumberOfNeighbors; n++ ) { if( this->m_HelpFindLoop[this->m_DiscBoundaryList[i]->m_Neighbors[n]->GetIdentity()] > bestparam ) { bestparam = this->m_HelpFindLoop[this->m_DiscBoundaryList[i]->m_Neighbors[n]->GetIdentity()]; BestG = this->m_DiscBoundaryList[i]->m_Neighbors[n]; } } // neighborlist.push_back( BestG ); for( unsigned int j = i + 1; j < (unsigned int) bestparam - 1; j++ ) { this->m_HelpFindLoop[this->m_DiscBoundaryList[j]->GetIdentity()] = -1; } i = (unsigned int) (bestparam - 2); } } this->SetDiscBoundaryList( neighborlist ); // this->m_DiscBoundaryList.assign(neighborlist.begin(),neighborlist.end()); float newtotallength = 0; for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { unsigned int nxt = ( ( i + 1 ) % this->m_DiscBoundaryList.size() ); diff = this->m_DiscBoundaryList[i]->GetLocation() - this->m_DiscBoundaryList[nxt]->GetLocation(); tangentlength = 0; for( unsigned int d = 0; d < diff.Size(); d++ ) { tangentlength += diff[d] * diff[d]; } newtotallength += tangentlength; } std::cout << " total1 " << totallength << " total2 " << newtotallength << std::endl; // check for self-intersection for( unsigned int i = 0; i < this->m_DiscBoundaryList.size(); i++ ) { for( unsigned int j = 0; j < this->m_DiscBoundaryList.size(); j++ ) { if( i != j && this->m_DiscBoundaryList[i]->GetIdentity() == this->m_DiscBoundaryList[j]->GetIdentity() ) { isvalid = false; } } } for( unsigned long g = 0; g < this->m_HelpFindLoop.size(); g++ ) { if( this->m_HelpFindLoop[g] != 0 ) { this->m_HelpFindLoop[g] = -1; } } for( unsigned int j = 0; j < this->m_DiscBoundaryList.size(); j++ ) { m_HelpFindLoop[this->m_DiscBoundaryList[j]->GetIdentity()] = j + 1; } unsigned long MAXLIST = 200; if( this->m_DiscBoundaryList.size() > MAXLIST ) { std::cout << this->m_RootNode->GetLocation() << std::endl; std::cout << "long list " << MAXLIST << std::endl; return 2; } return isvalid; } template <typename TSurface, typename TImage, unsigned int TDimension> unsigned int FEMDiscConformalMap<TSurface, TImage, TDimension> ::FindLoopAroundNode( unsigned int j_in ) { vtkDataArray* labels = this->m_SurfaceMesh->GetPointData()->GetArray("Label"); vtkDataArray* features = nullptr; if( this->m_SurfaceFeatureMesh ) { if( this->m_SurfaceFeatureMesh->GetPointData()->GetArray("Feature") ) { features = this->m_SurfaceFeatureMesh->GetPointData()->GetArray("Feature"); } else { features = labels; } } this->m_DiscBoundaryList.clear(); unsigned int gsz = manifoldIntegrator->GetGraphSize(); // get distance from this node to all others // now measure the length distortion of the given solution this->m_RootNode = manifoldIntegrator->GetGraphNode(j_in); for( int i = 0; i < manifoldIntegrator->GetGraphSize(); i++ ) { manifoldIntegrator->GetGraphNode(i)->SetTotalCost(vnl_huge_val(manifoldIntegrator->GetMaxCost() ) ); manifoldIntegrator->GetGraphNode(i)->SetUnVisited(); manifoldIntegrator->GetGraphNode(i)->SetValue(0.0, 1); manifoldIntegrator->GetGraphNode(i)->SetValue(0.0, 2); float labval = labels->GetTuple1(i); manifoldIntegrator->GetGraphNode(i)->SetValue(labval, 3); manifoldIntegrator->GetGraphNode(i)->SetPredecessor(nullptr); } manifoldIntegrator->EmptyQ(); manifoldIntegrator->SetSearchFinished( false ); manifoldIntegrator->SetSource(this->m_RootNode); manifoldIntegrator->InitializeQueue(); manifoldIntegrator->SetParamWhileSearching( this->m_ParamWhileSearching ); manifoldIntegrator->SetWeights(this->m_MaxCost, this->m_DistanceCostWeight, this->m_LabelCostWeight); manifoldIntegrator->PrintWeights(); manifoldIntegrator->FindPath(); /** at this point, we should have extracted the disc now we want to find a boundary point and an instant parameterization via FEM */ this->SetDiscBoundaryList( manifoldIntegrator->m_BoundaryList ); // this->m_DiscBoundaryList.assign(manifoldIntegrator->m_BoundaryList.begin(), // manifoldIntegrator->m_BoundaryList.end()); this->m_HelpFindLoop.clear(); this->m_HelpFindLoop.resize(gsz, 0); this->m_HelpFindLoop[j_in] = -1; unsigned int furthestnode = 0; float maxdist = 0; GraphSearchNodePointer farnode1 = nullptr; for( unsigned int j = 0; j < this->m_DiscBoundaryList.size(); j++ ) { if( this->m_DiscBoundaryList[j]->GetTotalCost() > maxdist ) { maxdist = this->m_DiscBoundaryList[j]->GetTotalCost(); furthestnode = this->m_DiscBoundaryList[j]->GetIdentity(); farnode1 = this->m_DiscBoundaryList[j]; } m_HelpFindLoop[this->m_DiscBoundaryList[j]->GetIdentity()] = j + 1; } if( this->m_ParamWhileSearching ) { return 2; } // butt ManifoldIntegratorTypePointer discParameterizer = ManifoldIntegratorType::New(); discParameterizer->SetSurfaceMesh(this->m_SurfaceMesh); discParameterizer->InitializeGraph3(); discParameterizer->SetMaxCost(1.e9); std::cout << " dcz " << discParameterizer->GetGraphSize() << std::endl; for( int i = 0; i < discParameterizer->GetGraphSize(); i++ ) { discParameterizer->GetGraphNode(i)->SetTotalCost(vnl_huge_val(discParameterizer->GetMaxCost() ) ); discParameterizer->GetGraphNode(i)->SetUnVisitable(); if( this->m_HelpFindLoop[i] > 0 ) { discParameterizer->GetGraphNode(i)->SetUnVisited(); } discParameterizer->GetGraphNode(i)->SetValue(0.0, 1); discParameterizer->GetGraphNode(i)->SetValue(0.0, 2); discParameterizer->GetGraphNode(i)->SetPredecessor(nullptr); } discParameterizer->EmptyQ(); discParameterizer->SetSearchFinished( false ); discParameterizer->SetSource(discParameterizer->GetGraphNode(furthestnode) ); discParameterizer->InitializeQueue(); discParameterizer->SetWeights(1.e9, 1, 0); discParameterizer->FindPath(); float temp = 0; GraphSearchNodePointer farnode2 = nullptr; unsigned int vct = 0; for( int i = 0; i < discParameterizer->GetGraphSize(); i++ ) { if( discParameterizer->GetGraphNode(i)->WasVisited() ) { float t = discParameterizer->GetGraphNode(i)->GetTotalCost(); if( t > temp ) { temp = t; farnode2 = discParameterizer->GetGraphNode(i); } vct++; // std::cout << " dist " << t << " vct " << vct << std::endl; } } discParameterizer->BackTrack(farnode2); // butt2 ManifoldIntegratorTypePointer lastlooper = ManifoldIntegratorType::New(); lastlooper->SetSurfaceMesh(this->m_SurfaceMesh); lastlooper->InitializeGraph3(); lastlooper->SetMaxCost(1.e9); // std::cout << " dcz "<< lastlooper->GetGraphSize() << std::endl; for( int i = 0; i < lastlooper->GetGraphSize(); i++ ) { lastlooper->GetGraphNode(i)->SetTotalCost(vnl_huge_val(lastlooper->GetMaxCost() ) ); lastlooper->GetGraphNode(i)->SetUnVisitable(); if( this->m_HelpFindLoop[i] > 0 ) { lastlooper->GetGraphNode(i)->SetUnVisited(); } lastlooper->GetGraphNode(i)->SetValue(0.0, 1); lastlooper->GetGraphNode(i)->SetValue(0.0, 2); lastlooper->GetGraphNode(i)->SetPredecessor(nullptr); } lastlooper->EmptyQ(); lastlooper->SetSearchFinished( false ); for( unsigned int pp = 0; pp < discParameterizer->GetPathSize(); pp++ ) { unsigned int id = discParameterizer->GetPathAtIndex(pp)->GetIdentity(); lastlooper->SetSource( lastlooper->GetGraphNode(id) ); } lastlooper->InitializeQueue(); lastlooper->SetWeights(1.e9, 1, 0); lastlooper->FindPath(); GraphSearchNodePointer farnode3 = nullptr; vct = 0; temp = 0; for( int i = 0; i < lastlooper->GetGraphSize(); i++ ) { if( lastlooper->GetGraphNode(i)->WasVisited() ) { float t = lastlooper->GetGraphNode(i)->GetTotalCost(); if( t > temp ) { temp = t; farnode3 = lastlooper->GetGraphNode(i); } vct++; // std::cout << " dist " << t << " vct " << vct << std::endl; } } // std::exception(); // finally reuse lastlooper with farnode3 as root ... for( int i = 0; i < lastlooper->GetGraphSize(); i++ ) { lastlooper->GetGraphNode(i)->SetTotalCost(vnl_huge_val(lastlooper->GetMaxCost() ) ); lastlooper->GetGraphNode(i)->SetUnVisitable(); if( this->m_HelpFindLoop[i] > 0 ) { lastlooper->GetGraphNode(i)->SetUnVisited(); } lastlooper->GetGraphNode(i)->SetValue(0.0, 1); lastlooper->GetGraphNode(i)->SetValue(0.0, 2); lastlooper->GetGraphNode(i)->SetPredecessor(nullptr); } lastlooper->EmptyQ(); lastlooper->SetSearchFinished( false ); lastlooper->SetSource( lastlooper->GetGraphNode(farnode3->GetIdentity() ) ); lastlooper->InitializeQueue(); lastlooper->SetWeights(1.e9, 1, 0); lastlooper->FindPath(); // now assemble the parameterization... // this->m_DiscBoundaryList.clear(); // add both the above to the list // std::cout << " part 1 " << std::endl; for( unsigned int i = 0; i < discParameterizer->GetPathSize(); i++ ) { unsigned int id = discParameterizer->GetPathAtIndex(i)->GetIdentity(); // std::cout << manifoldIntegrator->GetGraphNode(id)->GetLocation() << std::endl; this->m_DiscBoundaryList.push_back( manifoldIntegrator->GetGraphNode(id) ); } // std::cout << " part 2 " << std::endl; lastlooper->BackTrack( lastlooper->GetGraphNode( farnode1->GetIdentity() ) ); for( unsigned int i = 0; i < lastlooper->GetPathSize(); i++ ) { unsigned int id = lastlooper->GetPathAtIndex(i)->GetIdentity(); // std::cout << manifoldIntegrator->GetGraphNode(id)->GetLocation() << std::endl; this->m_DiscBoundaryList.push_back( manifoldIntegrator->GetGraphNode(id) ); } // std::cout << farnode1->GetLocation() << std::endl; // std::cout << farnode2->GetLocation() << std::endl; // std::cout << farnode3->GetLocation() << std::endl; // std::cout << " another idea --- get two points far apart then solve a minimization problem across the // graph // that gives the average value in 0 => 1 ... " << std::endl; // std::cout << " path 1 sz " << discParameterizer->GetPathSize() << std::endl; // finally do but add in reverse order // std::cout << " part 3 " <<farnode2->GetIdentity() << " and " << farnode1->GetIdentity() << std::endl; lastlooper->EmptyPath(); lastlooper->BackTrack( lastlooper->GetGraphNode( farnode2->GetIdentity() ) ); for( unsigned int i = lastlooper->GetPathSize() - 1; i > 0; i-- ) { unsigned int id = lastlooper->GetPathAtIndex(i)->GetIdentity(); // std::cout << manifoldIntegrator->GetGraphNode(id)->GetLocation() << std::endl; this->m_DiscBoundaryList.push_back( manifoldIntegrator->GetGraphNode(id) ); } std::cout << " Almost ... " << std::endl; this->m_HelpFindLoop.clear(); this->m_HelpFindLoop.resize(gsz, 0); for( unsigned int j = 0; j < this->m_DiscBoundaryList.size(); j++ ) { m_HelpFindLoop[this->m_DiscBoundaryList[j]->GetIdentity()] = j + 1; } std::cout << " Achievement!! " << std::endl; return 2; } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::LocateAndParameterizeDiscBoundary( unsigned int label, bool CheckCost ) { float effectivemaxcost = 0; this->m_DiscBoundaryList.clear(); unsigned int gsz = manifoldIntegrator->GetGraphSize(); std::vector<bool> alreadyfound(gsz, false); this->m_DiscBoundarySorter.clear(); this->m_DiscBoundarySorter.resize(gsz, 0); for( unsigned int j = 0; j < gsz; j++ ) { if( manifoldIntegrator->GetGraphNode(j) ) { float cost = manifoldIntegrator->GetGraphNode(j)->GetTotalCost(); if( !CheckCost ) { cost = 0; } if( fabs( manifoldIntegrator->GetGraphNode(j)->GetValue(3) - label ) < 0.5 && cost <= this->m_MaxCost ) { float inb = 0; for( unsigned int i = 0; i < manifoldIntegrator->GetGraphNode(j)->m_NumberOfNeighbors; i++ ) { if( fabs( manifoldIntegrator->GetGraphNode(j)->m_Neighbors[i]->GetValue(3) - label ) > 0.5 ) { // CurrentNode is in the boundary inb = 1; } } // neighborhood if( inb > 0 ) // std::cout << " Node is in boundary " << std::endl; { inb = 0; for( unsigned int i = 0; i < manifoldIntegrator->GetGraphNode(j)->m_NumberOfNeighbors; i++ ) { if( fabs( manifoldIntegrator->GetGraphNode(j)->m_Neighbors[i]->GetValue(3) - label ) < 0.5 && cost <= this->m_MaxCost ) { // CurrentNode is in the boundary inb += 1; } } // neighborhood if( inb >= 2 && alreadyfound[j] == false ) // need at least two neighbors with same label { alreadyfound[j] = true; this->m_DiscBoundaryList.push_back(manifoldIntegrator->GetGraphNode(j) ); if( cost > effectivemaxcost ) { effectivemaxcost = cost; } } } } // less than max cost } // if node exists } // gsz std::cout << " Boundary has " << this->m_DiscBoundaryList.size() << " elements with eff. max cost " << effectivemaxcost << std::endl; if( CheckCost ) { // very inefficient way to parameterize boundary .... unsigned int bsz = this->m_DiscBoundaryList.size(); std::vector<bool> alreadyfound(bsz, false); this->m_DiscBoundarySorter.resize(bsz, 0); unsigned int boundcount = 0; unsigned int rootind = 0, lastroot = 0; this->m_DiscBoundarySorter[rootind] = boundcount; alreadyfound[rootind] = true; bool paramdone = false; while( !paramdone ) { std::cout << " start param " << bsz << std::endl; if( bsz == 0 ) { std::exception(); } for( unsigned int myi = 0; myi < bsz; myi++ ) { if( this->m_DiscBoundaryList[myi] != this->m_DiscBoundaryList[rootind] ) { std::cout << " myi " << myi << " root " << rootind << " bc " << boundcount << std::endl; for( unsigned int n = 0; n < this->m_DiscBoundaryList[rootind]->m_NumberOfNeighbors; n++ ) { if( this->m_DiscBoundaryList[myi] == this->m_DiscBoundaryList[rootind]->m_Neighbors[n] && !alreadyfound[myi] ) // // its // in // the // bndry { // check that it's not an isolated bastard bool oknode = true; if( oknode ) { boundcount++; alreadyfound[myi] = true; this->m_DiscBoundarySorter[myi] = boundcount; n = this->m_DiscBoundaryList[rootind]->m_NumberOfNeighbors + 1; std::cout << " cur " << this->m_DiscBoundaryList[rootind]->GetLocation() << " next " << this->m_DiscBoundaryList[myi]->GetLocation() << " boundcount " << boundcount << " of " << bsz << " curroot " << rootind << std::endl; lastroot = rootind; rootind = myi; myi = bsz; } } // is in boundary } // neighborhood loop } // not currootnode if( boundcount >= bsz - 1 ) { paramdone = true; } else if( myi == (bsz - 1) ) { boundcount--; rootind = lastroot; this->m_DiscBoundarySorter[rootind] = -1; std::cout << " failure " << std::endl; std::exception(); } } // all boundary nodes } // while // std::exception(); } // param boundary if } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::ExtractSurfaceDisc(unsigned int label) { std::cout << " set surface mesh " << std::endl; manifoldIntegrator->SetSurfaceMesh(this->m_SurfaceMesh); std::cout << " begin initializing graph " << std::endl; manifoldIntegrator->InitializeGraph3(); this->m_SurfaceMesh = manifoldIntegrator->GetSurfaceMesh(); // float frac=0; // IndexType index; if( this->m_Label_to_Flatten == 0 ) { std::cout << " enter LabelToExtract "; std::cin >> m_Label_to_Flatten; float mc = 0; std::cout << " Enter max cost "; std::cin >> mc; m_MaxCost = mc; } manifoldIntegrator->SetMaxCost(this->m_MaxCost); this->FindMeanSourceInLabel( this->m_Label_to_Flatten ); // this->LocateAndParameterizeDiscBoundary( m_Label_to_Flatten , false ); // this->LocateAndParameterizeDiscBoundary( m_Label_to_Flatten , true ); // std::cout << " findpath in extractsurfacedisk done "; // assign scalars to the original surface mesh // typedef itk::SurfaceMeshCurvature<GraphSearchNodeType,GraphSearchNodeType> surfktype; // typename surfktype::Pointer surfk=surfktype::New(); vtkPoints* vtkpoints = this->m_SurfaceMesh->GetPoints(); int numPoints = vtkpoints->GetNumberOfPoints(); vtkFloatArray* param = vtkFloatArray::New(); param->SetName("angle"); for( int i = 0; i < numPoints; i++ ) { float temp = fabs(manifoldIntegrator->GetGraphNode(i)->GetTotalCost() ); if( temp > m_MaxCost ) { temp = m_MaxCost; } param->InsertNextValue(temp * 255. / m_MaxCost); } std::cout << " extractsurfacedisk done "; // m_SurfaceMesh->GetPointData()->SetScalars(param); } template <typename TSurface, typename TImage, unsigned int TDimension> bool FEMDiscConformalMap<TSurface, TImage, TDimension> ::GenerateSystemFromSurfaceMesh() { if( !this->m_SurfaceMesh ) { std::cout << " NO MESH"; return false; } std::cout << " Generate system from surface mesh " << std::endl; m_Smooth = m_Sigma; // create a material // Choose the material properties typename MaterialType::Pointer m; m = MaterialType::New(); m->GN = 0; // Global number of the material /// m->E = 4.0; // Young modulus -- used in the membrane /// m->A = 0.0; // Crossection area /// m->h = 0.0; // Crossection area /// m->I = 0.0; // Moment of inertia /// m->nu = 0.; // .0; // poissons -- DONT CHOOSE 1.0!!/// m->RhoC = 0.0; // Create the element type ElementType::Pointer e1 = ElementType::New(); e1->m_mat = dynamic_cast<MaterialType *>( m ); vtkPoints* vtkpoints = this->m_SurfaceMesh->GetPoints(); int numPoints = vtkpoints->GetNumberOfPoints(); int foundnum = 0; int boundsz = 0; for( int i = 0; i < numPoints; i++ ) { double* pt = vtkpoints->GetPoint(i); typename NodeType::Pointer n; n = new NodeType(pt[0], pt[1], pt[2]); if( this->InDisc(manifoldIntegrator->GetGraphNode(i) ) ) { n->GN = i; m_Solver.node.push_back(itk::fem::FEMP<NodeType>(n) ); foundnum++; } if( this->InBorder(manifoldIntegrator->GetGraphNode(i) ) ) { boundsz++; } } typename NodeType::Pointer * narr = new NodeType::Pointer[numPoints]; for( int i = 0; i < numPoints; i++ ) { if( this->InDisc(manifoldIntegrator->GetGraphNode(i) ) || this->InBorder(manifoldIntegrator->GetGraphNode(i) ) ) { narr[i] = m_Solver.node.Find( i ); } } std::cout << " Found " << foundnum << " nodes " << std::endl; std::cout << " bound " << boundsz << std::endl; vtkCellArray* vtkcells = this->m_SurfaceMesh->GetPolys(); vtkIdType npts; vtkIdType* pts; unsigned long i = 0; // unsigned long toti = vtkcells->GetNumberOfCells(); // unsigned long rate = toti/50; // std::cout << " progress "; for( vtkcells->InitTraversal(); vtkcells->GetNextCell(npts, pts); ) { // if ( i % rate == 0 && i > rate ) std::cout << " " << (float) i / (float) toti << " "; // turn the cell into an element // std::cout << " points ids a " << pts[0] << " b " << pts[1] << " c " << pts[2] << std::endl; bool eltok = true; ElementType::Pointer e; e = dynamic_cast<ElementType *>(e1->Clone() ); if( this->InDisc(manifoldIntegrator->GetGraphNode(pts[0]) ) ) { e->SetNode(2, narr[pts[0]]); } // e->SetNode(2,m_Solver.node.Find( pts[0] )); else { eltok = false; } if( this->InDisc(manifoldIntegrator->GetGraphNode(pts[1]) ) ) { e->SetNode(1, narr[pts[1]]); } // e->SetNode(1,m_Solver.node.Find( pts[1] )); else { eltok = false; } if( this->InDisc(manifoldIntegrator->GetGraphNode(pts[2]) ) ) { e->SetNode(0, narr[pts[2]]); } // e->SetNode(0,m_Solver.node.Find( pts[2] )); else { eltok = false; } if( eltok ) { e->GN = i; m_Solver.el.push_back(itk::fem::FEMP<itk::fem::Element>(e) ); i++; } // else std::cout <<" cannot find elt " << std::endl; } std::cout << " DONE: NUMBER OF CELLS " << i << std::endl; return true; } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::FixBoundaryPoints(unsigned int option) { itk::fem::Element::ArrayType::iterator elt = m_Solver.el.begin(); unsigned int dofs = (*elt)->GetNumberOfDegreesOfFreedomPerNode(); int fixct = 0; int eltct = 0; while( elt != m_Solver.el.end() ) { for( unsigned int i = 0; i < dofs; i++ ) { int nodeid = (*elt)->GetNode(i)->GN; // if( manifoldIntegrator->GetGraphNode(nodeid)->GetTotalCost() > 222 ) if( this->InBorder(manifoldIntegrator->GetGraphNode(nodeid) ) ) { itk::fem::LoadBC::Pointer l1; l1 = itk::fem::LoadBC::New(); l1->m_element = (*elt); l1->m_dof = i; l1->m_value = vnl_vector<double>(1, 0.0); // for exp float fixvalue = 0.0; if( this->m_MapToCircle ) { fixvalue = this->GetBoundaryParameterForCircle(nodeid, option); } else { fixvalue = this->GetBoundaryParameterForSquare(nodeid, option); } l1->m_value = vnl_vector<double>(1, fixvalue); // for direct rad m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*l1) ); /* itk::fem::LoadNode::Pointer ln1=itk::fem::LoadNode::New(); ln1->m_pt=0; ln1->F.set_size(1); ln1->F.fill(fixvalue); ln1->m_element=(*elt); m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*ln1) ); itk::fem::LoadNode::Pointer ln2=itk::fem::LoadNode::New(); ln2->m_pt=1; ln2->F.set_size(1); ln2->F.fill(fixvalue); ln2->m_element=(*elt); m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*ln2) ); itk::fem::LoadNode::Pointer ln3=itk::fem::LoadNode::New(); ln3->m_pt=2; ln3->F.set_size(1); ln3->F.fill(fixvalue); ln3->m_element=(*elt); m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*ln3) ); */ if( i == 0 ) { fixct++; } } } ++el; eltct++; } std::cout << " Fixed elt number " << fixct << " of " << eltct << std::endl; } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::ApplyRealForces() { /* itk::fem::Element::Pointer e = m_Solver.el[m_PoleElementsGN[0]]; // load node 0 { itk::fem::LoadNode::Pointer ln1=itk::fem::LoadNode::New(); ln1->m_pt=0; ln1->F.set_size(1); ln1->F.fill(-4.0*m_Pi); ln1->m_element=(e); m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*ln1) ); itk::fem::LoadNode::Pointer ln2=itk::fem::LoadNode::New(); ln2->m_pt=1; ln2->F.set_size(1); ln2->F.fill(-4.0*m_Pi); ln2->m_element=(e); m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*ln2) ); itk::fem::LoadNode::Pointer ln3=itk::fem::LoadNode::New(); ln3->m_pt=2; ln3->F.set_size(1); ln3->F.fill(-4.0*m_Pi); ln3->m_element=(e); m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*ln3) ); } */ } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::ApplyImaginaryForces() { itk::fem::Element::Pointer e = m_Solver.el[m_PoleElementsGN[0]]; itk::fem::LoadBC::Pointer l1; l1 = itk::fem::LoadBC::New(); l1->m_element = (e); l1->m_dof = 0; l1->m_value = vnl_vector<double>(1, -1. / 3.); // for exp m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*l1) ); itk::fem::LoadBC::Pointer l2; l2 = itk::fem::LoadBC::New(); l2->m_element = (e); l2->m_dof = 1; l2->m_value = vnl_vector<double>(1, -1. / 3.); // for exp m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*l2) ); itk::fem::LoadBC::Pointer l3; l3 = itk::fem::LoadBC::New(); l3->m_element = (e); l3->m_dof = 2; l3->m_value = vnl_vector<double>(1, 2. / 3.); // for exp m_Solver.load.push_back( itk::fem::FEMP<itk::fem::Load>(&*l3) ); } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension>::MakeFlatImage() { // first declare the flat image typename FlatImageType::RegionType region; typename FlatImageType::SizeType size; int sz = 256; size[0] = sz; size[1] = sz; region.SetSize( size ); m_FlatImage = FlatImageType::New(); m_FlatImage->SetRegions( region ); m_FlatImage->Allocate(); typename FlatImageType::IndexType index; std::cout << " Making flat image " << std::endl; int maxits = 100; for( int its = 0; its <= maxits; its++ ) { for( ::itk::fem::Solver::NodeArray::iterator n = m_Solver.node.begin(); n != m_Solver.node.end(); ++n ) { float temp = 255.0 - manifoldIntegrator->GetGraphNode( (*n)->GN)->GetValue(3); // curvature // float temp=255.0*manifoldIntegrator->GetGraphNode((*n)->GN)->GetValue(2); // extrinsic dist index[0] = (long int)(0.5 + ( 1.0 + manifoldIntegrator->GetGraphNode( (*n)->GN)->GetValue(0) ) * (float)(sz - 1) / 2.); index[1] = (long int)(0.5 + ( 1.0 + manifoldIntegrator->GetGraphNode( (*n)->GN)->GetValue(1) ) * (float)(sz - 1) / 2.); // std::cout << " ind " << index << std::endl; m_FlatImage->SetPixel(index, temp); } typedef itk::DiscreteGaussianImageFilter<FlatImageType, FlatImageType> dgf; typename dgf::Pointer filter = dgf::New(); filter->SetVariance(1.0); filter->SetUseImageSpacingOff(); filter->SetMaximumError(.01f); filter->SetInput(m_FlatImage); filter->Update(); m_FlatImage = filter->GetOutput(); if( its < maxits ) { int center = (int)sz / 2; itk::ImageRegionIteratorWithIndex<FlatImageType> it( m_FlatImage, region ); it.GoToBegin(); typename FlatImageType::IndexType index; while( !it.IsAtEnd() ) { index = it.GetIndex(); float x = (float)index[0] - (float)sz / 2.0; float y = (float)index[1] - (float)sz / 2.0; float dist = sqrt(x * x + y * y); // std::cout << "center " << center << " index " << index << "dist " << dist ; if( dist > center ) { it.Set( 0.0 ); } ++it; } } } } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension>::BuildOutputMeshes(float tval) { std::cout << " build output mesh " << std::endl; typedef GraphSearchNodeType::NodeLocationType loctype; // Get the number of points in the mesh int numPoints = m_Solver.node.size(); vtkDataArray* labels = this->m_SurfaceMesh->GetPointData()->GetArray("Label"); vtkDataArray* features = nullptr; if( this->m_SurfaceFeatureMesh ) { if( this->m_SurfaceFeatureMesh->GetPointData()->GetArray("Feature") ) { features = this->m_SurfaceFeatureMesh->GetPointData()->GetArray("Feature"); } else { features = labels; } } else { features = labels; } // Create vtk polydata vtkPolyData* polydata1 = vtkPolyData::New(); vtkPolyData* polydata2 = vtkPolyData::New(); // Create the vtkPoints object and set the number of points vtkPoints* vpoints1 = vtkPoints::New(); vtkPoints* vpoints2 = vtkPoints::New(); vpoints1->SetNumberOfPoints(numPoints); vpoints2->SetNumberOfPoints(numPoints); std::cout << " start pts "; int idx = 0; vtkFloatArray* param = vtkFloatArray::New(); param->SetName("feature"); vtkFloatArray* paramAngle = vtkFloatArray::New(); paramAngle->SetName("angle"); vtkFloatArray* paramDistance = vtkFloatArray::New(); paramDistance->SetName("distance"); vtkIdTypeArray* paramPoints = vtkIdTypeArray::New(); paramPoints->SetName("points"); for( ::itk::fem::Solver::NodeArray::iterator n = m_Solver.node.begin(); n != m_Solver.node.end(); ++n ) { loctype loc = manifoldIntegrator->GetGraphNode( (*n)->GN)->GetLocation(); float pt1[3]; pt1[0] = loc[0]; pt1[1] = loc[1]; pt1[2] = loc[2]; float pt2[3]; pt2[0] = manifoldIntegrator->GetGraphNode( (*n)->GN)->GetValue(0) * 100. * (1.0 - tval) + tval * loc[0]; pt2[1] = manifoldIntegrator->GetGraphNode( (*n)->GN)->GetValue(1) * 100. * (1.0 - tval) + tval * loc[1]; pt2[2] = 1. * (1.0 - tval) + tval * loc[2]; vpoints1->SetPoint(idx, pt1); vpoints2->SetPoint(idx, pt2); float temp = features->GetTuple1( (*n)->GN); float temp2 = manifoldIntegrator->GetGraphNode( (*n)->GN)->GetValue(0) * 255; // for length param->InsertNextValue(temp); paramDistance->InsertNextValue(temp2); paramPoints->InsertNextValue( (*n)->GN); paramAngle->InsertNextValue(temp); // curvature // param->InsertNextValue(temp*255./m_MaxCost); (*n)->GN = idx; idx++; } std::cout << " done with pts " << std::endl; vtkCellArray* tris1 = vtkCellArray::New(); vtkCellArray* tris2 = vtkCellArray::New(); std::cout << " start with tris " << std::endl; for( ::itk::fem::Solver::ElementArray::iterator n = m_Solver.el.begin(); n != m_Solver.el.end(); ++n ) { tris1->InsertNextCell(3); tris2->InsertNextCell(3); for( unsigned int i = 0; i < (*n)->GetNumberOfNodes(); i++ ) { tris1->InsertCellPoint( (*n)->GetNode(i)->GN); tris2->InsertCellPoint( (*n)->GetNode(i)->GN); } } std::cout << " done with tris " << std::endl; // Assign points and cells polydata1->SetPoints(vpoints1); polydata2->SetPoints(vpoints2); polydata1->SetPolys(tris1); polydata2->SetPolys(tris2); polydata1->GetPointData()->SetScalars(param); polydata2->GetPointData()->SetScalars(param); polydata1->GetPointData()->AddArray(paramAngle); polydata2->GetPointData()->AddArray(paramAngle); polydata1->GetPointData()->AddArray(paramDistance); polydata2->GetPointData()->AddArray(paramDistance); polydata1->GetPointData()->AddArray(paramPoints); polydata2->GetPointData()->AddArray(paramPoints); m_ExtractedSurfaceMesh = polydata1; // vtkDelaunay2D* delny2 = vtkDelaunay2D::New(); delny2->SetInput(polydata2); m_DiskSurfaceMesh = delny2->GetOutput(); // m_DiskSurfaceMesh=polydata2; return; } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::ConformalMap() { m_Solver.load.clear(); m_Solver.node.clear(); m_Solver.el.clear(); /** * Open the file and assign it to stream object f */ if( m_ReadFromFile ) { const char* filename = m_ParameterFileName.c_str(); std::cout << "Reading FEM problem from file: " << std::string(filename) << "\n"; std::ifstream f; f.open(filename); if( !f ) { std::cout << "File " << filename << " not found!\n"; return; } try { m_Solver.Read(f); } catch( ::itk::fem::FEMException & e ) { std::cout << "Error reading FEM problem: " << filename << "!\n"; e.Print(std::cout); return; } f.close(); } else if( this->GenerateSystemFromSurfaceMesh() ) { ; } else { return; } /** * Assign a unique id (global freedom number - GFN) * to every degree of freedom (DOF) in a system. */ m_Solver.GenerateGFN(); m_ImagSolution.set_size(m_Solver.GetNumberOfDegreesOfFreedom() ); m_RealSolution.set_size(m_Solver.GetNumberOfDegreesOfFreedom() ); m_Radius.set_size(m_Solver.GetNumberOfDegreesOfFreedom() ); m_RealSolution.fill(0); m_ImagSolution.fill(0); m_Radius.fill(0); m_Debug = false; if( m_Debug ) { for( ::itk::fem::Solver::NodeArray::iterator n = m_Solver.node.begin(); n != m_Solver.node.end(); ++n ) { std::cout << "Node#: " << (*n)->GN << ": "; std::cout << " coord " << (*n)->GetCoordinates() << " coord2 " << manifoldIntegrator->GetGraphNode( (*n)->GN)->GetLocation() << std::endl; } for( ::itk::fem::Solver::ElementArray::iterator n = m_Solver.el.begin(); n != m_Solver.el.end(); ++n ) { std::cout << "Elt#: " << (*n)->GN << ": has " << (*n)->GetNumberOfNodes() << " nodes "; for( unsigned int i = 0; i < (*n)->GetNumberOfNodes(); i++ ) { std::cout << " coord " << (*n)->GetNode(i)->GetCoordinates() << std::endl; } } } unsigned int maxits = m_Solver.GetNumberOfDegreesOfFreedom(); // should be > twice ndofs // if (m_Debug) std::cout << " ndof " << maxits << std::endl; itpackWrapper.SetMaximumNumberIterations(maxits * 5); itpackWrapper.SetTolerance(1.e-4); itpackWrapper.SuccessiveOverrelaxation(); // itpackWrapper.JacobianConjugateGradient(); itpackWrapper.SetMaximumNonZeroValuesInMatrix(maxits * 50); m_Solver.SetLinearSystemWrapper(&itpackWrapper); this->FixBoundaryPoints(0); m_Solver.AssembleK(); m_Solver.DecomposeK(); // this->ApplyRealForces(); std::cout << " appl force "; m_Solver.AssembleF(); // for (int i=0; i<maxits; i++) if (m_Solver.GetVectorValue(i) != 0) m_Solver.SetVectorValue(i,1.0); std::cout << " b solve "; m_Solver.Solve(); std::cout << " e solve "; m_Solver.UpdateDisplacements(); // copies solution to nodes unsigned long ct = 0; for( ::itk::fem::Solver::NodeArray::iterator n = m_Solver.node.begin(); n != m_Solver.node.end(); ++n ) { for( unsigned int d = 0, dof; (dof = (*n)->GetDegreeOfFreedom(d) ) != ::itk::fem::Element::InvalidDegreeOfFreedomID; d++ ) { m_RealSolution[dof] = m_Solver.GetSolution(dof); // if ( ct % 10 == 0) std::cout << " mrdof " << m_RealSolution[dof] << " dof " << dof << // std::endl; } ct++; } this->ConformalMap2(); // this->ConformalMap3(); this->ConjugateHarmonic(); } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::ConformalMap2() { m_Solver.load.clear(); this->FixBoundaryPoints(1); m_Solver.AssembleK(); // need to reassemble b/c LoadBC's affect K m_Solver.AssembleF(); m_Solver.Solve(); m_Solver.UpdateDisplacements(); // copies solution to nodes unsigned long ct = 0; for( ::itk::fem::Solver::NodeArray::iterator n = m_Solver.node.begin(); n != m_Solver.node.end(); ++n ) { for( unsigned int d = 0, dof; (dof = (*n)->GetDegreeOfFreedom(d) ) != ::itk::fem::Element::InvalidDegreeOfFreedomID; d++ ) { m_ImagSolution[dof] = m_Solver.GetSolution(dof); // if (ct % 10 == 0) std::cout << " midof " << m_ImagSolution[dof] << " dof " << dof << // std::endl; } ct++; } } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::MeasureLengthDistortion() { // now measure the length distortion of the given solution manifoldIntegrator->EmptyQ(); manifoldIntegrator->SetSearchFinished( false ); for( int i = 0; i < manifoldIntegrator->GetGraphSize(); i++ ) { manifoldIntegrator->GetGraphNode(i)->SetTotalCost(vnl_huge_val(manifoldIntegrator->GetMaxCost() ) ); manifoldIntegrator->GetGraphNode(i)->SetUnVisited(); manifoldIntegrator->GetGraphNode(i)->SetValue(0.0, 1); manifoldIntegrator->GetGraphNode(i)->SetValue(0.0, 2); manifoldIntegrator->GetGraphNode(i)->SetPredecessor(nullptr); } manifoldIntegrator->SetSource(manifoldIntegrator->GetGraphNode(this->m_SourceNodeNumber) ); manifoldIntegrator->InitializeQueue(); float mchere = 1.2; manifoldIntegrator->SetMaxCost(mchere); manifoldIntegrator->SetWeights(this->m_MaxCost, this->m_DistanceCostWeight, this->m_LabelCostWeight); manifoldIntegrator->FindPath(); // backtrack everywhere to set up forweard tracking float maxmanifolddist = 0; float distDistortion = 0; unsigned int ct = 0; for( int i = 0; i < manifoldIntegrator->GetGraphSize(); i++ ) { if( manifoldIntegrator->GetGraphNode(i) ) { if( manifoldIntegrator->GetGraphNode(i)->GetTotalCost() <= manifoldIntegrator->GetMaxCost() ) { float ttt = manifoldIntegrator->GetGraphNode(i)->GetValue(2); if( ttt > maxmanifolddist ) { maxmanifolddist = ttt; } ct++; } } } ct = 0; for( int i = 0; i < manifoldIntegrator->GetGraphSize(); i++ ) { if( manifoldIntegrator->GetGraphNode(i) ) { if( manifoldIntegrator->GetGraphNode(i)->GetTotalCost() < manifoldIntegrator->GetMaxCost() ) { const float rad = manifoldIntegrator->GetGraphNode(i)->GetValue(0); const float manifolddist = manifoldIntegrator->GetGraphNode(i)->GetValue(2) / maxmanifolddist; manifoldIntegrator->GetGraphNode(i)->SetValue(manifolddist, 2); distDistortion += fabs(rad - manifolddist); ct++; } } } std::cout << " distDistortion/ct " << distDistortion / (float)ct << " maxmfd " << maxmanifolddist << std::endl; return; /* m_ExtractedSurfaceMesh=polydata1;// // m_DiskSurfaceMesh=delny2->GetOutput(); float total=0.0; for (int i=0; i<this->m_SurfaceMesh->GetPoints()->GetNumberOfPoints(); i++) { float length1=0; float length2=0; float pt1[3]; for (int ne=0; ne<manifoldIntegrator->GetGraphNode(i)->GetNumberOfNeighbors(); ne++) { } } */ } template <typename TSurface, typename TImage, unsigned int TDimension> void FEMDiscConformalMap<TSurface, TImage, TDimension> ::ConjugateHarmonic() { std::cout << " Conformal coordinates " << std::endl; unsigned long ct = 0; for( ::itk::fem::Solver::NodeArray::iterator n = m_Solver.node.begin(); n != m_Solver.node.end(); ++n ) { ct++; unsigned long dof = (*n)->GetDegreeOfFreedom(0); if( dof < m_RealSolution.size() ) { const float U = m_RealSolution[dof]; const float V = m_ImagSolution[dof]; manifoldIntegrator->GetGraphNode( (*n)->GN )->SetValue(U, 0); manifoldIntegrator->GetGraphNode( (*n)->GN )->SetValue(V, 1); } } // this->MakeFlatImage(); this->BuildOutputMeshes(); return; } } // namespace itk /* vtkSelectPolyData *loop = vtkSelectPolyData::New(); loop->SetInput(this->m_SurfaceMesh); // put points inside ... vtkPoints* points = vtkPoints::New(); points->SetNumberOfPoints( this->m_DiscBoundaryList.size()); unsigned int idx=0; for ( unsigned int j = 0 ; j < this->m_DiscBoundaryList.size(); j ++ ) { float pt1[3]; typename GraphSearchNodeType::NodeLocationType loc=this->m_DiscBoundaryList[j]->GetLocation(); pt1[0]=loc[0]; pt1[1]=loc[1]; pt1[2]=loc[2]; // unsigned int idx=this->m_DiscBoundaryList[j]->GetIdentity(); points->SetPoint(idx,pt); idx++; } loop->GenerateSelectionScalarsOff(); loop->SetSelectionModeToClosestPointRegion(); //negative scalars inside loop->SetSelectionModeToSmallestRegion(); //negative scalars inside loop->SetLoop(points); loop->Modified(); vtkClipPolyData *clip = vtkClipPolyData::New(); //clips out positive region clip->SetInput(loop->GetOutput()); vtkPolyDataMapper *clipMapper = vtkPolyDataMapper::New(); clipMapper->SetInput(clip->GetOutput()); vtkActor *clipActor = vtkActor::New(); clipActor->SetMapper(clipMapper); clipActor->AddPosition(1, 0, 0); // clipActor->GetProperty()->SetColor(0, 0, 1); //Set colour blue vtkRenderer *ren1 = vtkRenderer::New(); vtkRenderWindow* renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren1); vtkRenderWindowInteractor* inter = vtkRenderWindowInteractor::New(); inter->SetRenderWindow(renWin); ren1->SetViewport(0.0, 0.0, 1.0, 1.0); ren1->AddActor(clipActor); renWin->Render(); inter->Start(); ren1->Delete(); renWin->Delete(); points-> Delete(); loop->Delete(); clip->Delete(); clipMapper->Delete(); clipActor->Delete(); */ #endif
t-sagara/geonlp-software
libgeonlp/unit_test/test_rpcclient.cpp
<gh_stars>1-10 #include <iostream> #include "JsonRpcClient.h" int main(int argc, char* argv[]) { try { if (argc != 3 && argc != 4) { std::cout << "Usage: async_client <server> <path>\n"; std::cout << "Example:\n"; std::cout << " test_rpcclient localhost /index.html\n"; return 1; } char* message = (char*)""; if (argc == 4) { message = argv[3]; } else { message = (char*)"{\"method\":\"getWeight\",\"params\":[[[37.393276,138.595812]]],\"id\":1}"; } boost::asio::io_service io_service; geonlp::JsonRpcClient c(io_service, argv[1], argv[2], message, "80"); io_service.run(); std::cout << "Content: \n" << c.content_ << std::endl; picojson::ext e = c.getJsonResponse(); std::cout << "JSON: '" << e.toJson() << "'" << std::endl; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
inblock-io/inblock
src/components/partners.js
import React from 'react' import Container from '../components/container' import styles from './partners.module.css' export default ({ partners }) => ( <div className={styles.partners}> <Container> <img className={styles.titleImg} src="/3d-cube.svg" alt=""/> <div className="d-block"> <h2 className={styles.title}>Key partners <br className="d-none d-lg-block" /></h2> <div className="d-flex flex-wrap justify-content-center"> {partners.map(({ node }) => { return ( <a key={node.title} href={node.link} target="_blank"> <img className={styles.partnerLogo} src={node.logo.sizes.src} alt={node.title}/> </a> ) })} </div> </div> </Container> </div> )
CEpBrowser/CEpBrowser--from-UCSC-CGI-BIN
hg/hgTracks/rnaPLFoldTrack.c
#include "common.h" #include "jksql.h" #include "hgTracks.h" #include "rnaPLFoldTrack.h" /* ------ BEGIN RNAplfold ------ */ /*******************************************************************/ #define RNAPLFOLD_DATA_SHADES 10 /* Declare our color gradients and the the number of colors in them */ Color plShadesPos[RNAPLFOLD_DATA_SHADES * 3]; Color plOutlineColor; Color plHighDprimeLowLod; /* blue */ int colorLookup[256]; double basePairSpan=0; int maxBasePairSpan=5000; boolean rnaPLFoldInv=FALSE; // default is inverted = sequence on buttom double scaleHeight=0; void plShadesInit(struct track *tg, struct hvGfx *hvg, boolean isDprime) /* Allocate the LD for positive and negative values, and error cases */ { static struct rgbColor white = {255, 255, 255}; static struct rgbColor red = {255, 0, 0}; static struct rgbColor green = {0 , 255, 0}; static struct rgbColor blue = { 0, 0, 255}; plOutlineColor = hvGfxFindColorIx(hvg, 0, 0, 0); /* black */ plHighDprimeLowLod = hvGfxFindColorIx(hvg, 192, 192, 240); /* blue */ hvGfxMakeColorGradient(hvg, &white, &blue, RNAPLFOLD_DATA_SHADES, plShadesPos); hvGfxMakeColorGradient(hvg, &white, &red, RNAPLFOLD_DATA_SHADES, plShadesPos + RNAPLFOLD_DATA_SHADES); hvGfxMakeColorGradient(hvg, &white, &green, RNAPLFOLD_DATA_SHADES, plShadesPos + 2 * RNAPLFOLD_DATA_SHADES); char *cartString = cartCgiUsualString(cart, RNAPLFOLD_INVERT, RNAPLFOLD_INVERT_DEF); rnaPLFoldInv = sameString(cartString,RNAPLFOLD_INVERT_BUTTOM) ? FALSE : TRUE; } void plInitColorLookup(struct track *tg, struct hvGfx *hvg, boolean isDprime) { plShadesInit(tg, hvg, isDprime); colorLookup[(int)'a'] = plShadesPos[0]; colorLookup[(int)'b'] = plShadesPos[1]; colorLookup[(int)'c'] = plShadesPos[2]; colorLookup[(int)'d'] = plShadesPos[3]; colorLookup[(int)'e'] = plShadesPos[4]; colorLookup[(int)'f'] = plShadesPos[5]; colorLookup[(int)'g'] = plShadesPos[6]; colorLookup[(int)'h'] = plShadesPos[7]; colorLookup[(int)'i'] = plShadesPos[8]; colorLookup[(int)'j'] = plShadesPos[9]; colorLookup[(int)'A'] = plShadesPos[10]; colorLookup[(int)'B'] = plShadesPos[11]; colorLookup[(int)'C'] = plShadesPos[12]; colorLookup[(int)'D'] = plShadesPos[13]; colorLookup[(int)'E'] = plShadesPos[14]; colorLookup[(int)'F'] = plShadesPos[15]; colorLookup[(int)'G'] = plShadesPos[16]; colorLookup[(int)'H'] = plShadesPos[17]; colorLookup[(int)'I'] = plShadesPos[18]; colorLookup[(int)'J'] = plShadesPos[19]; colorLookup[(int)'K'] = plShadesPos[20]; colorLookup[(int)'L'] = plShadesPos[21]; colorLookup[(int)'M'] = plShadesPos[22]; colorLookup[(int)'N'] = plShadesPos[23]; colorLookup[(int)'O'] = plShadesPos[24]; colorLookup[(int)'P'] = plShadesPos[25]; colorLookup[(int)'Q'] = plShadesPos[26]; colorLookup[(int)'R'] = plShadesPos[27]; colorLookup[(int)'S'] = plShadesPos[28]; colorLookup[(int)'T'] = plShadesPos[29]; //colorLookup[(int)'y'] = plHighLodLowDprime; /* LOD error case */ //colorLookup[(int)'z'] = plHighDprimeLowLod; /* LOD error case */ } void bedLoadRnaLpFoldItemByQuery(struct track *tg, char *table, char *query, ItemLoader loader) /* RNALPFOLD specific tg->item loader, as we need to load items beyond the current window to load the chromEnd positions for RNALPFOLD values. */ { struct sqlConnection *conn = hAllocConn(database); int rowOffset = 0; //int chromEndOffset = min(winEnd-winStart, 250000); /* extended chromEnd range */ struct sqlResult *sr = NULL; char **row = NULL; struct slList *itemList = NULL, *item = NULL; char altTable[64]; if(winEnd-winStart < maxBasePairSpan) { // test if another base-pair span as default is set char *tableSuffix = cartCgiUsualString(cart, RNAPLFOLD_MAXBPDISTANCE, RNAPLFOLD_MAXBPDISTANCE_DEF); basePairSpan=atoi(tableSuffix); //if(strcmp(tableSuffix,RNAPLFOLD_MAXBPDISTANCE_DEF) != 0) // { strcpy(altTable,table); strcat(altTable,tableSuffix); table=altTable; // } if(query == NULL) sr = hRangeQuery(conn, table, chromName, winStart, winEnd/*+chromEndOffset*/, NULL, &rowOffset); else sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { item = loader(row + rowOffset); slAddHead(&itemList, item); } } //slSort(&itemList, bedCmp); sqlFreeResult(&sr); tg->items = itemList; hFreeConn(&conn); } void bedLoadRnaLpFoldItem(struct track *tg, char *table, ItemLoader loader) /* RNALPFOLD specific tg->item loader. */ { bedLoadRnaLpFoldItemByQuery(tg, table, NULL, loader); } void rnaPLFoldLoadItems(struct track *tg) /* loadItems loads up items for the chromosome range indicated. */ { int count = 0; bedLoadRnaLpFoldItem(tg, tg->table, (ItemLoader)rnaPLFoldLoad); count = slCount((struct sList *)(tg->items)); tg->canPack = FALSE; } int rnaPLFoldTotalHeight(struct track *tg, enum trackVisibility vis) /* Return total height. Called before and after drawItems. * Must set height, lineHeight, heightPer */ { tg->lineHeight = tl.fontHeight + 1; tg->heightPer = tg->lineHeight - 1; if ( vis==tvDense || ( tg->limitedVisSet && tg->limitedVis==tvDense ) ) tg->height = tg->lineHeight; else { tg->height = max((int)(insideWidth*(basePairSpan/2.0)/(winEnd-winStart)),tg->lineHeight); if(tg->height > 200) { scaleHeight = 200.0 / (double)tg->height; tg->height = 200; // test !! } else scaleHeight = 1; } return tg->height; } void lpDrawDiamond(struct hvGfx *hvg, int xl, int yl, int xt, int yt, int xr, int yr, int xb, int yb, Color fillColor, Color outlineColor) /* Draw diamond shape. */ { struct gfxPoly *poly = gfxPolyNew(); gfxPolyAddPoint(poly, xl, yl); gfxPolyAddPoint(poly, xt, yt); gfxPolyAddPoint(poly, xr, yr); gfxPolyAddPoint(poly, xb, yb); hvGfxDrawPoly(hvg, poly, fillColor, TRUE); gfxPolyFree(&poly); } void rnaPLFoldDrawDiamond(struct hvGfx *hvg, struct track *tg, int width, int xOff, int yOff, int a, int b, int c, int d, Color shade, Color outlineColor, double scale, boolean drawMap, char *name, enum trackVisibility vis, boolean trim) /* Draw and map a single pairwise RNALPFOLD box */ { int yMax = rnaPLFoldTotalHeight(tg, vis)+yOff; /* convert from genomic coordinates to hvg coordinates */ /* multiple coordinates by 10 to avoid integer division rounding errors */ a*=10; b*=10; c*=10; d*=10; int xl = round((double)(scale*((c+a)/2-winStart*10)))/10 + xOff; int xt = round((double)(scale*((d+a)/2-winStart*10)))/10 + xOff; int xr = round((double)(scale*((d+b)/2-winStart*10)))/10 + xOff; int xb = round((double)(scale*((c+b)/2-winStart*10)))/10 + xOff; int yl = round((double)(scaleHeight * scale*(c-a)/2))/10 + yOff; int yt = round((double)(scaleHeight * scale*(d-a)/2))/10 + yOff; int yr = round((double)(scaleHeight * scale*(d-b)/2))/10 + yOff; int yb = round((double)(scaleHeight * scale*(c-b)/2))/10 + yOff; if (!rnaPLFoldInv) { yl = yMax - yl + yOff; yt = yMax - yt + yOff; yr = yMax - yr + yOff; yb = yMax - yb + yOff; } /* correct bottom coordinate if necessary */ if (yb<=0) yb=1; if (yt>yMax && trim) yt=yMax; lpDrawDiamond(hvg, xl, yl, xt, yt, xr, yr, xb, yb, shade, outlineColor); return; /* mapDiamondUI is working well, but there is a bug with AREA=POLY on the Mac browsers, so this will be postponed for now by not using this code */ /* also, since it only goes to hgTrackUi, it is redundant with mapTrackBackground. * so keep this disabled until there is something more specific like an hgc * handler for diamonds. */ if (drawMap && xt-xl>5 && xb-xl>5) mapDiamondUi(hvg, xl, yl, xt, yt, xr, yr, xb, yb, name, tg->track, tg->tdb->track); } void rnaPLFoldAddToDenseValueHash(struct hash *rnaPLFoldHash, unsigned a, char rnaPLFoldVal) /* Add new values to rnaFoldLp hash or update existing values. Values are averaged along the diagonals. */ { ldAddToDenseValueHash(rnaPLFoldHash, a, rnaPLFoldVal); } void rnaPLFoldDrawDenseValueHash(struct hvGfx *hvg, struct track *tg, int xOff, int yOff, double scale, Color outlineColor, struct hash *ldHash) { ldDrawDenseValueHash(hvg, tg, xOff, yOff, scale, outlineColor, ldHash); } /* rnaPLFoldDrawItems -- lots of disk and cpu optimizations here. * Based on rnaPLFoldDrawItems */ void rnaPLFoldDrawItems(struct track *tg, int seqStart, int seqEnd, struct hvGfx *hvg, int xOff, int yOff, int width, MgFont *font, Color color, enum trackVisibility vis) /* Draw item list, one per track. */ { struct rnaPLFold *dPtr = NULL; // *sPtr = NULL; /* pointers to 5' and 3' ends */ double scale = scaleForPixels(insideWidth); //int itemCount = slCount((struct slList *)tg->items); Color shade = 0, outlineColor = plOutlineColor; //getOutlineColor(tg, itemCount); int a=0, b, c, d=0, i; /* chromosome coordinates and counter */ boolean drawMap = FALSE; /* ( itemCount<1000 ? TRUE : FALSE ); */ //struct hash *rnaPLFoldHash = newHash(20); Color yellow = hvGfxFindRgb(hvg, &undefinedYellowColor); char *rnaPLFoldVal = NULL; boolean rnaPLFoldTrm = FALSE; int basePairOffset; if ( vis==tvDense || ( tg->limitedVisSet && tg->limitedVis==tvDense ) ) hvGfxBox(hvg, insideX, yOff, insideWidth, tg->height-1, yellow); mapTrackBackground(tg, hvg, xOff, yOff); /*nothing to do? */ if (tg->items==NULL) return; /* initialize arrays to convert from ascii encoding to color values */ plInitColorLookup(tg, hvg, FALSE); /* Loop through all items to get values and initial coordinates (a and b) */ for (dPtr=tg->items; dPtr!=NULL && dPtr->next!=NULL; dPtr=dPtr->next) { a = dPtr->chromStart; b = a+1; //dPtr->next->chromStart; rnaPLFoldVal = dPtr->colorIndex; i = 0; c = a/*+1*/; d = b/*+1*/; while(rnaPLFoldVal[i] != 'Z') { /* Loop through all items again to get end coordinates (c and d): used to be 'drawNecklace' */ while(rnaPLFoldVal[i] != 'Y' && rnaPLFoldVal[i] != 'Z') // for ( sPtr=dPtr; i<dPtr->score && sPtr!=NULL && sPtr->next!=NULL; sPtr=sPtr->next ) { basePairOffset = 16 * (rnaPLFoldVal[i]-'A') + (rnaPLFoldVal[i+1]-'A'); //basePairOffset = (int)rnaPLFoldVal[i+1]-(int)'A'; // if(basePairOffset > 70) // errAbort("Invalid Offset %d, %c, %d, %s",i+1,rnaPLFoldVal[i+1],basePairOffset,rnaPLFoldVal); i+=2; // c = sPtr->chromStart; // d = sPtr->next->chromStart; c+=basePairOffset; d+=basePairOffset; shade = colorLookup[(int)rnaPLFoldVal[i]]; if(b-a >1 || d-c>1) errAbort("Invalid distance: a:%d, b:%d, c:%d, d:%d",a,b,c,d); //if(c-a>70) // shade = plHighLodLowDprime; // if ( vis==tvFull && ( !tg->limitedVisSet || ( tg->limitedVisSet && tg->limitedVis==tvFull ) ) ) // emphasize stable base-pairs if(shade == plShadesPos[9] || shade == plShadesPos[19] || shade == plShadesPos[29]) outlineColor=plOutlineColor; else outlineColor=0; rnaPLFoldDrawDiamond(hvg, tg, width, xOff, yOff, a, b, c, d, shade, outlineColor, scale, drawMap, "", vis, rnaPLFoldTrm); // else if ( vis==tvDense || ( tg->limitedVisSet && tg->limitedVis==tvDense ) ) // { // rnaPLFoldAddToDenseValueHash(rnaPLFoldHash, a, rnaPLFoldVal[i]); // rnaPLFoldAddToDenseValueHash(rnaPLFoldHash, d, rnaPLFoldVal[i]); // } // else // errAbort("Visibility '%s' is not supported for the RNALPFOLD track yet.", hStringFromTv(vis)); i++; } if(rnaPLFoldVal[i] == 'Y') { a++; b++; i++; c=a/*+1*/; d=b/*+1*/; } } } // draw diagonals Color pColorDarkGray; Color pColorLightGray; pColorDarkGray = hvGfxFindColorIx(hvg, 128, 128, 128); /* dark gray */ pColorLightGray = hvGfxFindColorIx(hvg, 200, 200, 200); /* light gray */ int diagDark = atoi(cartCgiUsualString(cart, RNAPLFOLD_DIAGDARK, RNAPLFOLD_DIAGDARK_DEF)); int diagLight = atoi(cartCgiUsualString(cart, RNAPLFOLD_DIAGLIGHT, RNAPLFOLD_DIAGLIGHT_DEF)); int x,r; if(winEnd-winStart<1500) // do not show diags when zoom out too far { double xAdd; xAdd=(double)insideWidth / (double)(winEnd-winStart); x=xOff; // for(i=winStart-(winEnd-winStart),r=winStart-winEnd;i<winEnd;i++,r++) for(i=winStart-(int)(basePairSpan*xOff),r=-(int)(basePairSpan*xOff);i<winEnd;i++,r++) { if(diagDark && i%diagDark == 0) { hvGfxLine(hvg, x+(int)(xAdd*(double)r), yOff+tg->height, x+(int)(xAdd*(double)r+(basePairSpan*xAdd)), yOff-tg->height, pColorDarkGray); hvGfxLine(hvg, x+(int)(xAdd*(double)r), yOff-tg->height, x+(int)(xAdd*(double)r+(basePairSpan*xAdd)), yOff+tg->height , pColorDarkGray); } else { if(diagLight && i%diagLight == 0) { hvGfxLine(hvg, x+(int)(xAdd*(double)r), yOff+tg->height, x+(int)(xAdd*(double)r+(basePairSpan*xAdd)), yOff-tg->height, pColorLightGray); hvGfxLine(hvg, x+(int)(xAdd*(double)r), yOff-tg->height, x+(int)(xAdd*(double)r+(basePairSpan*xAdd)), yOff+tg->height, pColorLightGray); } } } } //if ( vis==tvDense || ( tg->limitedVisSet && tg->limitedVis==tvDense ) ) // rnaPLFoldDrawDenseValueHash(hvg, tg, xOff, yOff, scale, outlineColor, rnaPLFoldHash); } void rnaPLFoldDrawLeftLabels(struct track *tg, int seqStart, int seqEnd, struct hvGfx *hvg, int xOff, int yOff, int width, int height, boolean withCenterLabels, MgFont *font, Color color, enum trackVisibility vis) /* Draw left labels. */ { char label[16]; int yVisOffset = 0 + tl.fontHeight; // ( vis == tvDense ? 0 : tg->heightPer + height/2 ); safecpy(label, sizeof(label), tg->shortLabel); hvGfxUnclip(hvg); hvGfxSetClip(hvg, leftLabelX, yOff+yVisOffset, leftLabelWidth, tg->heightPer); hvGfxTextRight(hvg, leftLabelX, yOff+yVisOffset, leftLabelWidth, tg->heightPer, color, font, label); hvGfxUnclip(hvg); hvGfxSetClip(hvg, insideX, yOff, insideWidth, tg->height); } void rnaPLFoldMethods(struct track *tg) /* setup special methods for the RNA LP FOLD track */ { if(tg->subtracks != 0) /* Only load subtracks, not top level track. */ return; tg->loadItems = rnaPLFoldLoadItems; tg->totalHeight = rnaPLFoldTotalHeight; tg->drawItems = rnaPLFoldDrawItems; tg->freeItems = ldFreeItems; tg->drawLeftLabels = rnaPLFoldDrawLeftLabels; tg->mapsSelf = TRUE; tg->canPack = FALSE; } /* ------ END RNA LP FOLD ------ */
Bestmer/CommonAnimations
Animations/RegexManager.h
// // RegexManager.h // Regex // // Created by YouXianMing on 2017/7/5. // Copyright © 2017年 TechCode. All rights reserved. // #import <Foundation/Foundation.h> @interface RegexManager : NSObject /** The source string. */ @property (nonatomic, strong) NSString *string; /** The regex pattern. */ @property (nonatomic, strong) NSString *pattern; /** The search's option. */ @property (nonatomic) NSRegularExpressionOptions options; /** Start to search. @return RegexManager's instance. */ - (instancetype)start; /** The search's result, NSRange's values array. */ @property (nonatomic, strong, readonly) NSMutableArray <NSValue *> *matchs; /** The search's result, number of matches. */ @property (nonatomic, readonly) NSUInteger numberOfMatches; /** The replacing's result. @param string The templete. @return The result string. */ - (NSString *)replacingWithTemplate:(NSString *)string; /** [ Constructor ] @param string The source string. @param pattern The regex pattern. @param options The search's option. @return RegexManager's instance. */ + (instancetype)regexManagerWithString:(NSString *)string pattern:(NSString *)pattern options:(NSRegularExpressionOptions)options; /** [ Constructor ] @param string The source string. @param pattern The regex pattern. @return RegexManager's instance. */ + (instancetype)regexManagerWithString:(NSString *)string pattern:(NSString *)pattern; @end #pragma mark - RegexManager's NSString category. @interface NSString (RegexManager) - (BOOL)existWithRegexPattern:(NSString *)pattern; - (BOOL)existWithRegexPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options; - (NSMutableArray <NSValue *> *)matchsWithRegexPattern:(NSString *)pattern; - (NSMutableArray <NSValue *> *)matchsWithRegexPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options; - (NSMutableArray <NSString *> *)matchStringsArrayWithRegexPattern:(NSString *)pattern; - (NSMutableArray <NSString *> *)matchStringsArrayWithRegexPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options; - (NSString *)replacingWithPattern:(NSString *)pattern template:(NSString *)templ; - (NSString *)replacingWithPattern:(NSString *)pattern template:(NSString *)templ options:(NSRegularExpressionOptions)options; @end
BoyanPeychinov/js-applications
07-routing/lab/history-demo/app.js
console.log('it works!', date.now());
sistcoop-meanjsfiles/meanjs
modules/cooperativa/client/config/cooperativa.client.config.js
'use strict'; // Configuring the Chat module angular.module('cooperativa').run(['Menus', function (Menus) { // Set top bar menu items Menus.addMenuItem('topbar', { title: 'Cooperativa', state: 'cooperativa.app' }); } ]);
thiscouldbebetter/GameFrameworkTS
Source/Model/Combat/DamageType.js
"use strict"; var ThisCouldBeBetter; (function (ThisCouldBeBetter) { var GameFramework; (function (GameFramework) { class DamageType { constructor(name) { this.name = name; } static Instances() { if (DamageType._instances == null) { DamageType._instances = new DamageType_Instances(); } return DamageType._instances; } static byName(name) { var damageTypes = DamageType.Instances(); return damageTypes._AllByName.get(name) || damageTypes._Unspecified; } } GameFramework.DamageType = DamageType; class DamageType_Instances { constructor() { this._Unspecified = new DamageType("Unspecified"); this.Cold = new DamageType("Cold"); this.Heat = new DamageType("Heat"); this._All = [ this._Unspecified, this.Cold, this.Heat ]; this._AllByName = GameFramework.ArrayHelper.addLookupsByName(this._All); } } })(GameFramework = ThisCouldBeBetter.GameFramework || (ThisCouldBeBetter.GameFramework = {})); })(ThisCouldBeBetter || (ThisCouldBeBetter = {}));
squahtx/hal9000
plugins/base/__init__.py
from .iplugin import IPlugin from .plugin import Plugin from .terminalemulator import TerminalEmulator from .terminalemulatedprocess import TerminalEmulatedProcess from .cowsay import CowSay
jimmykarily/carrier
shim/restapi/carrier_shim_cf/organization_quota_definitions/update_organization_quota_definition.go
// Code generated by go-swagger; DO NOT EDIT. package organization_quota_definitions // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the generate command import ( "net/http" "github.com/go-openapi/runtime/middleware" ) // UpdateOrganizationQuotaDefinitionHandlerFunc turns a function with the right signature into a update organization quota definition handler type UpdateOrganizationQuotaDefinitionHandlerFunc func(UpdateOrganizationQuotaDefinitionParams) middleware.Responder // Handle executing the request and returning a response func (fn UpdateOrganizationQuotaDefinitionHandlerFunc) Handle(params UpdateOrganizationQuotaDefinitionParams) middleware.Responder { return fn(params) } // UpdateOrganizationQuotaDefinitionHandler interface for that can handle valid update organization quota definition params type UpdateOrganizationQuotaDefinitionHandler interface { Handle(UpdateOrganizationQuotaDefinitionParams) middleware.Responder } // NewUpdateOrganizationQuotaDefinition creates a new http.Handler for the update organization quota definition operation func NewUpdateOrganizationQuotaDefinition(ctx *middleware.Context, handler UpdateOrganizationQuotaDefinitionHandler) *UpdateOrganizationQuotaDefinition { return &UpdateOrganizationQuotaDefinition{Context: ctx, Handler: handler} } /*UpdateOrganizationQuotaDefinition swagger:route PUT /quota_definitions/{guid} organizationQuotaDefinitions updateOrganizationQuotaDefinition Updating a Organization Quota Definition curl --insecure -i %s/v2/quota_definitions/{guid} -X PUT -H 'Authorization: %s' -d '%s' */ type UpdateOrganizationQuotaDefinition struct { Context *middleware.Context Handler UpdateOrganizationQuotaDefinitionHandler } func (o *UpdateOrganizationQuotaDefinition) ServeHTTP(rw http.ResponseWriter, r *http.Request) { route, rCtx, _ := o.Context.RouteInfo(r) if rCtx != nil { r = rCtx } var Params = NewUpdateOrganizationQuotaDefinitionParams() if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params o.Context.Respond(rw, r, route.Produces, route, err) return } res := o.Handler.Handle(Params) // actually handle the request o.Context.Respond(rw, r, route.Produces, route, res) }
DuncanRuns/FeatureUtils
src/main/java/kaptainwutax/featureutils/decorator/ore/nether/QuartzOre.java
<reponame>DuncanRuns/FeatureUtils package kaptainwutax.featureutils.decorator.ore.nether; import kaptainwutax.biomeutils.biome.Biomes; import kaptainwutax.featureutils.decorator.ore.HeightProvider; import kaptainwutax.featureutils.decorator.ore.RegularOreDecorator; import kaptainwutax.mcutils.block.Blocks; import kaptainwutax.mcutils.state.Dimension; import kaptainwutax.mcutils.version.MCVersion; import kaptainwutax.mcutils.version.VersionMap; public class QuartzOre extends RegularOreDecorator<RegularOreDecorator.Config, RegularOreDecorator.Data<QuartzOre>> { public static final VersionMap<Config> CONFIGS = new VersionMap<Config>() .add(MCVersion.v1_13, new Config(7, 5, 14, 16, HeightProvider.range(10, 20, 128), Blocks.NETHER_QUARTZ_ORE, NETHERRACK)) .add(MCVersion.v1_16, new Config(14, 7, 14, 16, HeightProvider.range(10, 20, 128), Blocks.NETHER_QUARTZ_ORE, NETHERRACK) .add(11, 7, Biomes.CRIMSON_FOREST) .add(12, 7, Biomes.WARPED_FOREST) .add(14, 7, 14, 32, Biomes.BASALT_DELTAS)) .add(MCVersion.v1_17, new Config(14, 7, 14, 16, HeightProvider.uniformRange(10, 117), Blocks.NETHER_QUARTZ_ORE, NETHERRACK) .add(11, 7, Biomes.CRIMSON_FOREST) .add(12, 7, Biomes.WARPED_FOREST) .add(14, 7, 14, 32, Biomes.BASALT_DELTAS)); public QuartzOre(MCVersion version) { super(CONFIGS.getAsOf(version), version); } @Override public String getName() { return name(); } public static String name() { return "quartz_ore"; } @Override public Dimension getValidDimension() { return Dimension.NETHER; } }
konung/formular
test/element/bootstrap4_test.rb
require 'test_helper' require 'formular/builders/bootstrap4' require 'formular/element/bootstrap4' describe Formular::Element::Bootstrap4 do let(:builder) { Formular::Builders::Bootstrap4.new } let(:collection_array) { COLLECTION_ARRAY } describe Formular::Element::Bootstrap4::Input do it '#to_s with value' do element = builder.input(:name, value: '<NAME>') element.to_s.must_equal %(<fieldset class="form-group"><input value="<NAME>" name="name" id="name" type="text" class="form-control"/></fieldset>) end it '#to_s with label' do element = builder.input(:name, label: 'Name') element.to_s.must_equal %(<fieldset class="form-group"><label class="form-control-label" for="name">Name</label><input name="name" id="name" type="text" class="form-control"/></fieldset>) end it '#to_s with hint' do element = builder.input(:name, hint: 'Some helpful words') element.to_s.must_equal %(<fieldset class="form-group"><input name="name" id="name" type="text" aria-describedby="name_hint" class="form-control"/><small id="name_hint" class="form-text text-muted">Some helpful words</small></fieldset>) end it '#to_s with error' do element = builder.input(:name, error: 'Something nasty happened') element.to_s.must_equal %(<fieldset class="form-group has-danger"><input name="name" id="name" type="text" class="form-control form-control-danger"/><div class="form-control-feedback">Something nasty happened</div></fieldset>) end it '#to_s all together!' do element = builder.input( :name, value: '<NAME>', label: 'Name', error: 'Something nasty happened', hint: 'Some helpful words' ) element.to_s.must_equal %(<fieldset class="form-group has-danger"><label class="form-control-label" for="name">Name</label><input value="<NAME>" name="name" id="name" type="text" aria-describedby="name_hint" class="form-control form-control-danger"/><small id="name_hint" class="form-text text-muted">Some helpful words</small><div class="form-control-feedback">Something nasty happened</div></fieldset>) end describe 'file' do it '#to_s with label' do element = builder.input(:doc, type: :file, label: 'Document') element.to_s.must_equal %(<fieldset class="form-group"><label class="form-control-label" for="doc">Document</label><input type="file" name="doc" id="doc" class="form-control-file"/></fieldset>) end it '#to_s with hint' do element = builder.input(:doc, type: :file, hint: 'Some helpful words') element.to_s.must_equal %(<fieldset class="form-group"><input type="file" name="doc" id="doc" aria-describedby="doc_hint" class="form-control-file"/><small id="doc_hint" class="form-text text-muted">Some helpful words</small></fieldset>) end it '#to_s with error' do element = builder.input(:doc, type: :file, error: 'Something nasty happened') element.to_s.must_equal %(<fieldset class="form-group has-danger"><input type="file" name="doc" id="doc" class="form-control-file"/><div class="form-control-feedback">Something nasty happened</div></fieldset>) end it '#to_s all together!' do element = builder.input( :doc, type: :file, label: 'Document', error: 'Something nasty happened', hint: 'Some helpful words' ) element.to_s.must_equal %(<fieldset class="form-group has-danger"><label class="form-control-label" for="doc">Document</label><input type="file" name="doc" id="doc" aria-describedby="doc_hint" class="form-control-file"/><small id="doc_hint" class="form-text text-muted">Some helpful words</small><div class="form-control-feedback">Something nasty happened</div></fieldset>) end end end describe 'independent errors' do let(:builder) do Formular::Builders::Bootstrap4.new( errors: { body: ['This really isn\'t good enough!'] } ) end it '#error should return the error element for :body' do element = builder.error(:body) element.to_s.must_equal %(<div class="form-control-feedback">This really isn&#39;t good enough!</div>) end end describe 'independent hints' do it '#error should return the hint element for :body' do element = builder.hint(content: 'Something helpful') element.to_s.must_equal %(<small class="form-text text-muted">Something helpful</small>) end end describe 'independent labels' do it '#error should return the label element for :body' do element = builder.label(:body, content: 'Some words...') element.to_s.must_equal %(<label for="body">Some words...</label>) end end end
paige-ingram/nwhacks2022
node_modules/@fluentui/react-icons/lib/cjs/components/PeopleTeam20Filled.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const wrapIcon_1 = require("../utils/wrapIcon"); const rawSvg = (iconProps) => { const { className, primaryFill } = iconProps; return React.createElement("svg", { width: 20, height: 20, viewBox: "0 0 20 20", xmlns: "http://www.w3.org/2000/svg", className: className }, React.createElement("path", { d: "M12.47 8.01a1 1 0 011 .89v4.48a3.48 3.48 0 01-6.96.2V9a1 1 0 01.88-.99h5.08zm-6.7 0c-.14.25-.23.53-.26.82v4.76c.03.65.2 1.25.47 1.8a2.86 2.86 0 01-3.96-2.47V9.01a1 1 0 01.88-.99h2.87zm8.44 0h2.78a1 1 0 011 .89v3.85a2.86 2.86 0 01-3.98 2.63c.26-.53.42-1.11.46-1.73V8.87c-.02-.31-.12-.6-.26-.86zM9.99 3a2.23 2.23 0 110 4.45 2.23 2.23 0 010-4.45zm4.99.63a1.91 1.91 0 110 3.82 1.91 1.91 0 010-3.82zm-9.96 0a1.91 1.91 0 110 3.82 1.91 1.91 0 010-3.82z", fill: primaryFill })); }; const PeopleTeam20Filled = wrapIcon_1.default(rawSvg({}), 'PeopleTeam20Filled'); exports.default = PeopleTeam20Filled;
nizamnijj/WorkingWithListview
SourceWriter/Documentation/html/search/namespaces_2.js
var searchData= [ ['sourcewriter',['SourceWriter',['../namespace_source_writer.html',1,'']]] ];
RevansChen/online-judge
Codewars/7kyu/is-sator-square/Python/solution1.py
# Python - 3.6.0 def is_sator_square(tablet): n = len(tablet) for r in range(n): for c in range(n): if not (tablet[r][c] == tablet[-(r + 1)][-(c + 1)] == tablet[c][r] == tablet[-(c + 1)][-(r + 1)]): return False return True
zcoderz/leetcode
src/main/java/hash_maps/FirstUniqueWithLinkedHashSet.java
<filename>src/main/java/hash_maps/FirstUniqueWithLinkedHashSet.java package hash_maps; import java.util.*; /** * 1429. First Unique Number * * You have a queue of integers, you need to retrieve the first unique integer in the queue. * * Implement the FirstUnique class: * * FirstUnique(int[] nums) Initializes the object with the numbers in the queue. * int showFirstUnique() returns the value of the first unique integer of the queue, * and returns -1 if there is no such integer. * void add(int value) insert value to the queue. */ public class FirstUniqueWithLinkedHashSet { //see documentation of linked hash set here. //the class is a combination of a doubly linked list and a hash set //thus via the linked list its able to maintain the order in which data was inserted LinkedHashSet<Integer> uniqueNumsLinkedHash = new LinkedHashSet<>(); Map<Integer, Integer> intToCountMap = new HashMap<>(); public FirstUniqueWithLinkedHashSet(int[] nums) { for (int i =0; i < nums.length; i++) { add(nums[i]); } } public int showFirstUnique() { if (!uniqueNumsLinkedHash.isEmpty()) { return uniqueNumsLinkedHash.iterator().next(); } return -1; } public void add(int value) { int ct = intToCountMap.getOrDefault(value, 0); ct++; intToCountMap.put(value, ct); if (ct > 1) { uniqueNumsLinkedHash.remove(value); } else { uniqueNumsLinkedHash.add(value); } } }
ShoukriKattan/ForgedUI-Eclipse
com.forgedui.core/src/com/forgedui/model/ContainerImpl.java
// LICENSE package com.forgedui.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.forgedui.model.titanium.TitaniumUIBaseElement; /** * @author Dmitry {<EMAIL>} * */ public class ContainerImpl extends ElementImpl implements Container{ private static final long serialVersionUID = 2; protected List<Element> children; public ContainerImpl() { children = new ArrayList<Element>(); } public void addChild(Element child) { addChild(child, -1); } public void removeChild(Element child) { if ( this.children.remove(child) ){ child.setParent(null); listeners.firePropertyChange(PROPERTY_CHILDREN, child, null); } } public void addChild(Element child, int index) { child.setParent(this); if (index >= 0) children.add(index,child); else children.add(child); listeners.fireIndexedPropertyChange(PROPERTY_CHILDREN, index, null, child); } public void moveChild(Element child, int toIndex) { int currentIndex = getChildren().indexOf(child); if (currentIndex >= 0 && toIndex < getChildren().size() && toIndex >=0 && toIndex != currentIndex){ children.remove(currentIndex); if (currentIndex < toIndex){ toIndex--; } children.add(toIndex, child); listeners.fireIndexedPropertyChange(PROPERTY_CHILDREN, toIndex, null, child); } } public List<Element> getChildren() { return Collections.unmodifiableList(children); } }
danielhanchen/hiperlearn
hyperlearn/sparse/base.py
<reponame>danielhanchen/hiperlearn from numpy import uint8, uint16, uint32, uint64, float32, float64 from numpy import zeros, int8, int16, int32, int64, ndim from warnings import warn as Warn from numba import njit, prange def getDtype(p, size, uint = True): """ Computes the exact best possible data type for CSR Matrix creation. """ p = int(1.25*p) # Just in case if uint: dtype = uint64 if uint8(p) == p: dtype = uint8 elif uint16(p) == p: dtype = uint16 elif uint32(p) == p: dtype = uint32 return zeros(size, dtype = dtype) else: dtype = int64 if int8(p) == p: dtype = int8 elif int16(p) == p: dtype = int16 elif int32(p) == p: dtype = int32 return zeros(size, dtype = dtype) @njit(fastmath = True, nogil = True, cache = True) def determine_nnz(X, rowCount): """ Uses close to no memory at all when computing how many non zeros are in the matrix. Notice the difference with Scipy is HyperLearn does NOT use nonzero(). This reduces memory usage dramatically. """ nnz = 0 n,p = X.shape for i in range(n): currNNZ = 0 Xi = X[i] for j in range(p): if Xi[j] != 0: currNNZ += 1 nnz += currNNZ rowCount[i] = currNNZ return rowCount, nnz def create_csr(X, rowCount, nnz, temp): """ [Added 10/10/2018] [Edited 13/10/2018] Before used extra memory keeping a Boolean Matrix (np bytes) and a ColIndex pointer which used p memory. Now, removed (np + p) memory usage, meaning larger matrices can be handled. Algorithm is 3 fold: 1. Create RowIndices 2. For every row in data: 3. Store until a non 0 is seen. Algorithm takes approx O(n + np) time, which is similar to Scipy's. The only difference is now, parallelisation is possible, which can cut the time to approx O(n + np/c) where c = no of threads """ n = X.shape[0] val = zeros(nnz, dtype = X.dtype) rowIndices = zeros(n+1, dtype = temp.dtype) colPointer = zeros(nnz, dtype = rowCount.dtype) p = X.shape[1] k = 0 for i in range(n): a = rowCount[i] rowIndices[i] += k k += a rowIndices[n] = nnz for i in prange(n): Xi = X[i] left = rowIndices[i] right = rowIndices[i+1] k = 0 for j in range(left, right): while Xi[k] == 0: k += 1 val[j] = Xi[k] colPointer[j] = k k += 1 return val, colPointer, rowIndices create_csr_cache = njit(create_csr, fastmath = True, nogil = True, cache = True) create_csr_parallel = njit(create_csr, fastmath = True, nogil = True, parallel = True) def CreateCSR(X, n_jobs = 1): """ [Added 10/10/2018] [Edited 13/10/2018] Much much faster than Scipy. In fact, HyperLearn uses less memory, by noticing indices >= 0, hence unsigned ints are used. Likewise, parallelisation is seen possible with Numba with n_jobs. Notice, an error message will be provided if 20% of the data is only zeros. It needs to be more than 20% zeros for CSR Matrix to shine. """ n,p = X.shape rowCount = getDtype(p, n) rowCount, nnz = determine_nnz(X, rowCount) if nnz/(n*p) > 0.8: Warn("Created sparse matrix has just under 20% zeros. Not a good idea to sparsify the matrix.") temp = getDtype(nnz, 1) f = create_csr_cache if n_jobs == 1 else create_csr_parallel return f(X, rowCount, nnz, temp)
adinkwok/android_frameworks_support
webkit-codegen/src/test/java/androidx/webkit/internal/codegen/BoundaryInterfaceTest.java
<reponame>adinkwok/android_frameworks_support<filename>webkit-codegen/src/test/java/androidx/webkit/internal/codegen/BoundaryInterfaceTest.java /* * Copyright 2017 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.webkit.internal.codegen; import static org.junit.Assert.assertEquals; import androidx.webkit.internal.codegen.representations.ClassRepr; import androidx.webkit.internal.codegen.representations.MethodRepr; import com.android.tools.lint.LintCoreProjectEnvironment; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiJavaFile; import com.squareup.javapoet.JavaFile; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Arrays; @RunWith(JUnit4.class) public class BoundaryInterfaceTest { private LintCoreProjectEnvironment mProjectEnv; @Before public void setUp() throws Exception { mProjectEnv = PsiProjectSetup.sProjectEnvironment; // Add files required to resolve dependencies in the tests in this class. This is needed for // example to identify a class as being an android.webkit class (and turn it into an // InvocationHandler). mProjectEnv.registerPaths(Arrays.asList(TestUtils.getTestDepsDir())); } @After public void tearDown() throws Exception { } @Test public void testSingleClassAndMethod() { testBoundaryInterfaceGeneration("SingleClassAndMethod"); } @Ignore @Test public void testWebkitReturnTypeGeneratesInvocationHandler() { testBoundaryInterfaceGeneration("WebKitTypeAsMethodParameter"); } @Ignore @Test public void testWebkitMethodParameterTypeGeneratesInvocationHandler() { testBoundaryInterfaceGeneration("WebKitTypeAsMethodReturn"); } /** * Ensures methods are filtered correctly so only explicitly added methods are added to the * boundary interface. */ @Test public void testFilterMethods() { PsiFile inputFile = TestUtils.getTestFile(mProjectEnv.getProject(), "FilterMethods"); PsiClass psiClass = TestUtils.getSingleClassFromFile(inputFile); MethodRepr method2 = MethodRepr.fromPsiMethod(psiClass.findMethodsByName("method2", false)[0]); ClassRepr classRepr = new ClassRepr(Arrays.asList(method2), psiClass); JavaFile actualBoundaryInterface = BoundaryGeneration.createBoundaryInterface(classRepr); assertBoundaryInterfaceCorrect(psiClass.getName(), actualBoundaryInterface); } // TODO(gsennton) add test case including a (static) inner class which should create a // separate boundary interface file. /** * Generates a boundary interface from the test-file with name {@param className}.java, and * compares the result to the test-file {@param className}BoundaryInterface.java. */ private void testBoundaryInterfaceGeneration(String className) { PsiFile inputFile = TestUtils.getTestFile(mProjectEnv.getProject(), className); ClassRepr classRepr = ClassRepr.fromPsiClass(TestUtils.getSingleClassFromFile(inputFile)); JavaFile actualBoundaryInterface = BoundaryGeneration.createBoundaryInterface(classRepr); assertBoundaryInterfaceCorrect(className, actualBoundaryInterface); } private void assertBoundaryInterfaceCorrect(String className, JavaFile actualBoundaryInterface) { PsiJavaFile expectedBoundaryFile = TestUtils.getExpectedTestFile(mProjectEnv.getProject(), className + "BoundaryInterface"); assertEquals(expectedBoundaryFile.getText(), actualBoundaryInterface.toString()); } }
fossas/m3
src/cluster/client/etcd/client_test.go
<gh_stars>1-10 // Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package etcd import ( "os" "testing" "github.com/m3db/m3/src/cluster/kv" "github.com/m3db/m3/src/cluster/services" "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/integration" "github.com/stretchr/testify/require" ) func TestETCDClientGen(t *testing.T) { cs, err := NewConfigServiceClient(testOptions()) require.NoError(t, err) c := cs.(*csclient) // a zone that does not exist _, err = c.etcdClientGen("not_exist") require.Error(t, err) require.Equal(t, 0, len(c.clis)) c1, err := c.etcdClientGen("zone1") require.NoError(t, err) require.Equal(t, 1, len(c.clis)) c2, err := c.etcdClientGen("zone2") require.NoError(t, err) require.Equal(t, 2, len(c.clis)) require.False(t, c1 == c2) _, err = c.etcdClientGen("zone3") require.Error(t, err) require.Equal(t, 2, len(c.clis)) // TODO(pwoodman): bit of a cop-out- this'll error no matter what as it's looking for // a file that won't be in the test environment. So, expect error. _, err = c.etcdClientGen("zone4") require.Error(t, err) _, err = c.etcdClientGen("zone5") require.Error(t, err) c1Again, err := c.etcdClientGen("zone1") require.NoError(t, err) require.Equal(t, 2, len(c.clis)) require.True(t, c1 == c1Again) t.Run("TestNewDirectoryMode", func(t *testing.T) { require.Equal(t, defaultDirectoryMode, c.opts.NewDirectoryMode()) expect := os.FileMode(0744) opts := testOptions().SetNewDirectoryMode(expect) require.Equal(t, expect, opts.NewDirectoryMode()) cs, err := NewConfigServiceClient(opts) require.NoError(t, err) require.Equal(t, expect, cs.(*csclient).opts.NewDirectoryMode()) }) } func TestKVAndHeartbeatServiceSharingETCDClient(t *testing.T) { sid := services.NewServiceID().SetName("s1") cs, err := NewConfigServiceClient(testOptions().SetZone("zone1").SetEnv("env")) require.NoError(t, err) c := cs.(*csclient) _, err = c.KV() require.NoError(t, err) require.Equal(t, 1, len(c.clis)) _, err = c.heartbeatGen()(sid.SetZone("zone1")) require.NoError(t, err) require.Equal(t, 1, len(c.clis)) _, err = c.heartbeatGen()(sid.SetZone("zone2")) require.NoError(t, err) require.Equal(t, 2, len(c.clis)) _, err = c.heartbeatGen()(sid.SetZone("not_exist")) require.Error(t, err) require.Equal(t, 2, len(c.clis)) } func TestClient(t *testing.T) { _, err := NewConfigServiceClient(NewOptions()) require.Error(t, err) cs, err := NewConfigServiceClient(testOptions()) require.NoError(t, err) _, err = cs.KV() require.NoError(t, err) cs, err = NewConfigServiceClient(testOptions()) require.NoError(t, err) c := cs.(*csclient) fn, closer := testNewETCDFn(t) defer closer() c.newFn = fn txn, err := c.Txn() require.NoError(t, err) kv1, err := c.KV() require.NoError(t, err) require.Equal(t, kv1, txn) kv2, err := c.KV() require.NoError(t, err) require.Equal(t, kv1, kv2) kv3, err := c.Store(kv.NewOverrideOptions().SetNamespace("ns").SetEnvironment("test_env1")) require.NoError(t, err) require.NotEqual(t, kv1, kv3) kv4, err := c.Store(kv.NewOverrideOptions().SetNamespace("ns")) require.NoError(t, err) require.NotEqual(t, kv3, kv4) // KV store will create an etcd cli for local zone only require.Equal(t, 1, len(c.clis)) _, ok := c.clis["zone1"] require.True(t, ok) kv5, err := c.Store(kv.NewOverrideOptions().SetZone("zone2").SetNamespace("ns")) require.NoError(t, err) require.NotEqual(t, kv4, kv5) require.Equal(t, 2, len(c.clis)) _, ok = c.clis["zone2"] require.True(t, ok) sd1, err := c.Services(nil) require.NoError(t, err) err = sd1.SetMetadata( services.NewServiceID().SetName("service").SetZone("zone2"), services.NewMetadata(), ) require.NoError(t, err) // etcd cli for zone1 will be reused require.Equal(t, 2, len(c.clis)) _, ok = c.clis["zone2"] require.True(t, ok) err = sd1.SetMetadata( services.NewServiceID().SetName("service").SetZone("zone3"), services.NewMetadata(), ) require.NoError(t, err) // etcd cli for zone2 will be created since the request is going to zone2 require.Equal(t, 3, len(c.clis)) _, ok = c.clis["zone3"] require.True(t, ok) } func TestServicesWithNamespace(t *testing.T) { cs, err := NewConfigServiceClient(testOptions()) require.NoError(t, err) c := cs.(*csclient) fn, closer := testNewETCDFn(t) defer closer() c.newFn = fn sd1, err := c.Services(services.NewOverrideOptions()) require.NoError(t, err) nOpts := services.NewNamespaceOptions().SetPlacementNamespace("p").SetMetadataNamespace("m") sd2, err := c.Services(services.NewOverrideOptions().SetNamespaceOptions(nOpts)) require.NoError(t, err) require.NotEqual(t, sd1, sd2) sid := services.NewServiceID().SetName("service").SetZone("zone2") err = sd1.SetMetadata(sid, services.NewMetadata()) require.NoError(t, err) _, err = sd1.Metadata(sid) require.NoError(t, err) _, err = sd2.Metadata(sid) require.Error(t, err) sid2 := services.NewServiceID().SetName("service").SetZone("zone2").SetEnvironment("test") err = sd2.SetMetadata(sid2, services.NewMetadata()) require.NoError(t, err) _, err = sd1.Metadata(sid2) require.Error(t, err) } func newOverrideOpts(zone, namespace, environment string) kv.OverrideOptions { return kv.NewOverrideOptions(). SetZone(zone). SetNamespace(namespace). SetEnvironment(environment) } func TestCacheFileForZone(t *testing.T) { c, err := NewConfigServiceClient(testOptions()) require.NoError(t, err) cs := c.(*csclient) kvOpts := cs.newkvOptions(newOverrideOpts("z1", "namespace", ""), cs.cacheFileFn()) require.Equal(t, "", kvOpts.CacheFileFn()(kvOpts.Prefix())) cs.opts = cs.opts.SetCacheDir("/cacheDir") kvOpts = cs.newkvOptions(newOverrideOpts("z1", "", ""), cs.cacheFileFn()) require.Equal(t, "/cacheDir/test_app_z1.json", kvOpts.CacheFileFn()(kvOpts.Prefix())) kvOpts = cs.newkvOptions(newOverrideOpts("z1", "namespace", ""), cs.cacheFileFn()) require.Equal(t, "/cacheDir/namespace_test_app_z1.json", kvOpts.CacheFileFn()(kvOpts.Prefix())) kvOpts = cs.newkvOptions(newOverrideOpts("z1", "namespace", ""), cs.cacheFileFn()) require.Equal(t, "/cacheDir/namespace_test_app_z1.json", kvOpts.CacheFileFn()(kvOpts.Prefix())) kvOpts = cs.newkvOptions(newOverrideOpts("z1", "namespace", "env"), cs.cacheFileFn()) require.Equal(t, "/cacheDir/namespace_env_test_app_z1.json", kvOpts.CacheFileFn()(kvOpts.Prefix())) kvOpts = cs.newkvOptions(newOverrideOpts("z1", "namespace", ""), cs.cacheFileFn("f1", "", "f2")) require.Equal(t, "/cacheDir/namespace_test_app_z1_f1_f2.json", kvOpts.CacheFileFn()(kvOpts.Prefix())) kvOpts = cs.newkvOptions(newOverrideOpts("z2", "", ""), cs.cacheFileFn("/r2/m3agg")) require.Equal(t, "/cacheDir/test_app_z2__r2_m3agg.json", kvOpts.CacheFileFn()(kvOpts.Prefix())) } func TestSanitizeKVOverrideOptions(t *testing.T) { opts := testOptions() cs, err := NewConfigServiceClient(opts) require.NoError(t, err) client := cs.(*csclient) opts1, err := client.sanitizeOptions(kv.NewOverrideOptions()) require.NoError(t, err) require.Equal(t, opts.Env(), opts1.Environment()) require.Equal(t, opts.Zone(), opts1.Zone()) require.Equal(t, kvPrefix, opts1.Namespace()) } func TestReuseKVStore(t *testing.T) { opts := testOptions() cs, err := NewConfigServiceClient(opts) require.NoError(t, err) store1, err := cs.Txn() require.NoError(t, err) store2, err := cs.KV() require.NoError(t, err) require.Equal(t, store1, store2) store3, err := cs.Store(kv.NewOverrideOptions()) require.NoError(t, err) require.Equal(t, store1, store3) store4, err := cs.TxnStore(kv.NewOverrideOptions()) require.NoError(t, err) require.Equal(t, store1, store4) store5, err := cs.Store(kv.NewOverrideOptions().SetNamespace("foo")) require.NoError(t, err) require.NotEqual(t, store1, store5) store6, err := cs.TxnStore(kv.NewOverrideOptions().SetNamespace("foo")) require.NoError(t, err) require.Equal(t, store5, store6) client := cs.(*csclient) client.storeLock.Lock() require.Equal(t, 2, len(client.stores)) client.storeLock.Unlock() } func TestValidateNamespace(t *testing.T) { inputs := []struct { ns string expectErr bool }{ { ns: "ns", expectErr: false, }, { ns: "/ns", expectErr: false, }, { ns: "/ns/ab", expectErr: false, }, { ns: "ns/ab", expectErr: false, }, { ns: "_ns", expectErr: true, }, { ns: "/_ns", expectErr: true, }, { ns: "", expectErr: true, }, { ns: "/", expectErr: true, }, } for _, input := range inputs { err := validateTopLevelNamespace(input.ns) if input.expectErr { require.Error(t, err) } } } func testOptions() Options { clusters := []Cluster{ NewCluster().SetZone("zone1").SetEndpoints([]string{"i1"}), NewCluster().SetZone("zone2").SetEndpoints([]string{"i2"}), NewCluster().SetZone("zone3").SetEndpoints([]string{"i3"}). SetTLSOptions(NewTLSOptions().SetCrtPath("foo.crt.pem")), NewCluster().SetZone("zone4").SetEndpoints([]string{"i4"}). SetTLSOptions(NewTLSOptions().SetCrtPath("foo.crt.pem").SetKeyPath("foo.key.pem")), NewCluster().SetZone("zone5").SetEndpoints([]string{"i5"}). SetTLSOptions(NewTLSOptions().SetCrtPath("foo.crt.pem").SetKeyPath("foo.key.pem").SetCACrtPath("foo_ca.pem")), } return NewOptions(). SetClusters(clusters). SetService("test_app"). SetZone("zone1"). SetEnv("env") } func testNewETCDFn(t *testing.T) (newClientFn, func()) { ecluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1}) ec := ecluster.RandClient() newFn := func(Cluster) (*clientv3.Client, error) { return ec, nil } closer := func() { ecluster.Terminate(t) } return newFn, closer }
Hamiltonsjr/CursoJava
Ex20.java
//Leia um valor inteiro N. Este valor será a quantidade de valores inteiros X que serão lidos em seguida. //Mostre quantos destes valores X estão dentro do intervalo [10,20] e quantos estão fora do intervalo, mostrando //essas informações conforme exemplo (use a palavra "in" para dentro do intervalo, e "out" para fora do intervalo). import java.util.Scanner; public class Ex20 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num, valor; int in = 0, out = 0; System.out.print("Quantidade de leitura:"); num = sc.nextInt(); for (int i = 1; i<= num; i++){ System.out.printf("Valor %d :", i); valor = sc.nextInt(); if(valor < 10 || valor > 20){ out += 1; } else { in += 1; } } System.out.printf("%d in\n", in); System.out.printf("%d out\n", out); sc.close(); } }
sacloud/open-service-broker-sacloud
util/random/random.go
<gh_stars>1-10 package random import ( "math/rand" "time" ) var r *rand.Rand const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func init() { r = rand.New(rand.NewSource(time.Now().UnixNano())) } // String generates random strings with specified length // Only letters in [a-zA-z] are used as strings func String(strlen int) string { result := make([]byte, strlen) for i := range result { result[i] = chars[r.Intn(len(chars))] } return string(result) }
antonmedv/year
packages/1973/11/08/index.js
module.exports = new Date(1973, 10, 8)