repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
PlatONnetwork/client-sdk-java
core/src/main/java/com/platon/contracts/ppos/StakingContract.java
package com.platon.contracts.ppos; import com.platon.abi.solidity.datatypes.BytesType; import com.platon.abi.solidity.datatypes.generated.Uint16; import com.platon.abi.solidity.datatypes.generated.Uint256; import com.platon.contracts.ppos.abi.Function; import com.platon.contracts.ppos.dto.CallResponse; import com.platon.contracts.ppos.dto.TransactionResponse; import com.platon.contracts.ppos.dto.common.FunctionType; import com.platon.contracts.ppos.dto.enums.StakingAmountType; import com.platon.contracts.ppos.dto.req.StakingParam; import com.platon.contracts.ppos.dto.req.UpdateStakingParam; import com.platon.contracts.ppos.dto.resp.Node; import com.platon.contracts.ppos.exception.EstimateGasException; import com.platon.contracts.ppos.exception.NoSupportFunctionType; import com.platon.crypto.Credentials; import com.platon.parameters.NetworkParameters; import com.platon.protocol.Web3j; import com.platon.protocol.core.RemoteCall; import com.platon.protocol.core.methods.response.PlatonSendTransaction; import com.platon.tx.TransactionManager; import com.platon.tx.gas.GasProvider; import com.platon.utils.Numeric; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; public class StakingContract extends BaseContract { /** * 加载合约, 默认ReadonlyTransactionManager事务管理 * * @param web3j * @return */ public static StakingContract load(Web3j web3j) { return new StakingContract(NetworkParameters.getPposContractAddressOfStaking(), web3j); } /** * 加载合约 * * @param web3j * @param transactionManager * @return */ public static StakingContract load(Web3j web3j, TransactionManager transactionManager) { return new StakingContract(NetworkParameters.getPposContractAddressOfStaking(), web3j, transactionManager); } /** * 加载合约, 默认RawTransactionManager事务管理 * * @param web3j * @param credentials * @return */ public static StakingContract load(Web3j web3j, Credentials credentials) { return new StakingContract(NetworkParameters.getPposContractAddressOfStaking(), web3j, credentials); } private StakingContract(String contractAddress, Web3j web3j) { super(contractAddress, web3j); } private StakingContract(String contractAddress, Web3j web3j, Credentials credentials) { super(contractAddress, web3j, credentials); } private StakingContract(String contractAddress, Web3j web3j, TransactionManager transactionManager) { super(contractAddress, web3j, transactionManager); } /** * 获取质押信息 * * @param nodeId * @return */ public RemoteCall<CallResponse<Node>> getStakingInfo(String nodeId) { Function function = new Function(FunctionType.GET_STAKINGINFO_FUNC_TYPE, Arrays.asList(new BytesType(Numeric.hexStringToByteArray(nodeId)))); return executeRemoteCallObjectValueReturn(function, Node.class); } /** * 查询当前结算周期的区块奖励 * * @return */ public RemoteCall<CallResponse<BigInteger>> getPackageReward() { Function function = new Function(FunctionType.GET_PACKAGEREWARD_FUNC_TYPE); return executeRemoteCallObjectValueReturn(function, BigInteger.class); } /** * 查询当前结算周期的质押奖励 * * @return */ public RemoteCall<CallResponse<BigInteger>> getStakingReward() { Function function = new Function(FunctionType.GET_STAKINGREWARD_FUNC_TYPE); return executeRemoteCallObjectValueReturn(function, BigInteger.class); } /** * 查询打包区块的平均时间 * * @return */ public RemoteCall<CallResponse<BigInteger>> getAvgPackTime() { Function function = new Function(FunctionType.GET_AVGPACKTIME_FUNC_TYPE); return executeRemoteCallObjectValueReturn(function, BigInteger.class); } /** * 发起质押 * * @param stakingParam * @return * @see StakingParam */ public RemoteCall<TransactionResponse> staking(StakingParam stakingParam) { Function function = createStakingFunction(stakingParam); return executeRemoteCallTransaction(function); } /** * 发起质押 * * @param stakingParam * @param gasProvider * @return * @see StakingParam */ public RemoteCall<TransactionResponse> staking(StakingParam stakingParam, GasProvider gasProvider) { Function function = createStakingFunction(stakingParam); return executeRemoteCallTransaction(function, gasProvider); } /** * 获取质押gasProvider * * @param stakingParam * @return */ public GasProvider getStakingGasProvider(StakingParam stakingParam) throws IOException, EstimateGasException, NoSupportFunctionType { Function function = createStakingFunction(stakingParam); return getDefaultGasProvider(function); } /** * 发起质押 * * @param stakingParam * @return * @see StakingParam */ public RemoteCall<PlatonSendTransaction> stakingReturnTransaction(StakingParam stakingParam) { Function function = createStakingFunction(stakingParam); return executeRemoteCallTransactionStep1(function); } /** * 发起质押 * * @param stakingParam * @param gasProvider * @return * @see StakingParam */ public RemoteCall<PlatonSendTransaction> stakingReturnTransaction(StakingParam stakingParam, GasProvider gasProvider) { Function function = createStakingFunction(stakingParam); return executeRemoteCallTransactionStep1(function, gasProvider); } private Function createStakingFunction(StakingParam stakingParam) { Function function = new Function( FunctionType.STAKING_FUNC_TYPE, stakingParam.getSubmitInputParameters()); return function; } /** * 撤销质押 * * @param nodeId 64bytes 被质押的节点Id(也叫候选人的节点Id) * @return */ public RemoteCall<TransactionResponse> unStaking(String nodeId) { Function function = createUnStakingFunction(nodeId); return executeRemoteCallTransaction(function); } /** * 撤销质押 * * @param nodeId 64bytes 被质押的节点Id(也叫候选人的节点Id) * @return */ public RemoteCall<TransactionResponse> unStaking(String nodeId, GasProvider gasProvider) { Function function = createUnStakingFunction(nodeId); return executeRemoteCallTransaction(function, gasProvider); } /** * 获取撤销质押的gasProvider * * @param nodeId * @return */ public GasProvider getUnStakingGasProvider(String nodeId) throws IOException, EstimateGasException, NoSupportFunctionType { Function function = createUnStakingFunction(nodeId); return getDefaultGasProvider(function); } /** * 撤销质押 * * @param nodeId 64bytes 被质押的节点Id(也叫候选人的节点Id) * @return */ public RemoteCall<PlatonSendTransaction> unStakingReturnTransaction(String nodeId) { Function function = createUnStakingFunction(nodeId); return executeRemoteCallTransactionStep1(function); } /** * 撤销质押 * * @param nodeId 64bytes 被质押的节点Id(也叫候选人的节点Id) * @param gasProvider 自定义的gasProvider * @return */ public RemoteCall<PlatonSendTransaction> unStakingReturnTransaction(String nodeId, GasProvider gasProvider) { Function function = createUnStakingFunction(nodeId); return executeRemoteCallTransactionStep1(function, gasProvider); } private Function createUnStakingFunction(String nodeId) { Function function = new Function(FunctionType.WITHDREW_STAKING_FUNC_TYPE, Arrays.asList(new BytesType(Numeric.hexStringToByteArray(nodeId)))); return function; } /** * 更新质押信息 * * @param updateStakingParam * @return */ public RemoteCall<TransactionResponse> updateStakingInfo(UpdateStakingParam updateStakingParam) { Function function = createUpdateStakingFunction(updateStakingParam); return executeRemoteCallTransaction(function); } /** * 更新质押信息 * * @param updateStakingParam * @param gasProvider * @return */ public RemoteCall<TransactionResponse> updateStakingInfo(UpdateStakingParam updateStakingParam, GasProvider gasProvider) { Function function = createUpdateStakingFunction(updateStakingParam); return executeRemoteCallTransaction(function,gasProvider); } /** * 获取更新质押信息GasProvider * * @param updateStakingParam * @return */ public GasProvider getUpdateStakingInfoGasProvider(UpdateStakingParam updateStakingParam) throws IOException, EstimateGasException, NoSupportFunctionType { Function function = createUpdateStakingFunction(updateStakingParam); return getDefaultGasProvider(function); } /** * 更新质押信息 * * @param updateStakingParam * @return */ public RemoteCall<PlatonSendTransaction> updateStakingInfoReturnTransaction(UpdateStakingParam updateStakingParam) { Function function = createUpdateStakingFunction(updateStakingParam); return executeRemoteCallTransactionStep1(function); } /** * 更新质押信息 * * @param updateStakingParam * @return */ public RemoteCall<PlatonSendTransaction> updateStakingInfoReturnTransaction(UpdateStakingParam updateStakingParam, GasProvider gasProvider) { Function function = createUpdateStakingFunction(updateStakingParam); return executeRemoteCallTransactionStep1(function, gasProvider); } private Function createUpdateStakingFunction(UpdateStakingParam updateStakingParam) { Function function = new Function(FunctionType.UPDATE_STAKING_INFO_FUNC_TYPE, updateStakingParam.getSubmitInputParameters()); return function; } /** * 增持质押 * * @param nodeId 被质押的节点Id(也叫候选人的节点Id) * @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做质押,0: 自由金额; 1: 锁仓金额 * @param amount 增持的von * @return */ public RemoteCall<TransactionResponse> addStaking(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) { Function function = createAddStakingFunction(nodeId, stakingAmountType, amount); return executeRemoteCallTransaction(function); } /** * 增持质押 * * @param nodeId 被质押的节点Id(也叫候选人的节点Id) * @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做质押,0: 自由金额; 1: 锁仓金额 * @param amount 增持的von * @param gasProvider * @return */ public RemoteCall<TransactionResponse> addStaking(String nodeId, StakingAmountType stakingAmountType, BigInteger amount, GasProvider gasProvider) { Function function = createAddStakingFunction(nodeId, stakingAmountType, amount); return executeRemoteCallTransaction(function, gasProvider); } /** * 获取增持质押gasProvider * * @param nodeId * @param stakingAmountType * @param amount * @return */ public GasProvider getAddStakingGasProvider(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) throws IOException, EstimateGasException, NoSupportFunctionType { Function function = createAddStakingFunction(nodeId, stakingAmountType, amount); return getDefaultGasProvider(function); } /** * 增持质押 * * @param nodeId 被质押的节点Id(也叫候选人的节点Id) * @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做质押,0: 自由金额; 1: 锁仓金额 * @param amount 增持的von * @return */ public RemoteCall<PlatonSendTransaction> addStakingReturnTransaction(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) { Function function = createAddStakingFunction(nodeId, stakingAmountType, amount); return executeRemoteCallTransactionStep1(function); } /** * 增持质押 * * @param nodeId 被质押的节点Id(也叫候选人的节点Id) * @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做质押,0: 自由金额; 1: 锁仓金额 * @param amount 增持的von * @param gasProvider * @return */ public RemoteCall<PlatonSendTransaction> addStakingReturnTransaction(String nodeId, StakingAmountType stakingAmountType, BigInteger amount, GasProvider gasProvider) { Function function = createAddStakingFunction(nodeId, stakingAmountType, amount ); return executeRemoteCallTransactionStep1(function, gasProvider); } private Function createAddStakingFunction(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) { Function function = new Function(FunctionType.ADD_STAKING_FUNC_TYPE, Arrays.asList(new BytesType(Numeric.hexStringToByteArray(nodeId)), new Uint16(stakingAmountType.getValue()), new Uint256(amount))); return function; } }
vlasy/dx-scanner
lib/services/git/__MOCKS__/gitLabServiceMockFolder/listIssuesResponse.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockListIssuesResponseForUser = exports.listIssuesResponse = void 0; exports.listIssuesResponse = (items, pagination) => { const defaultItems = [ { user: { id: '9970', login: 'gitlab-org', url: 'https://gitlab.com/groups/gitlab-org', }, url: 'https://gitlab.com/gitlab-org/gitlab/issues/207825', body: 'Follow-up for https://gitlab.com/gitlab-org/database-team/team-tasks/issues/30#note_292428210:\n' + '\n' + "Marginalia's line references often end up pointing to database load balancer code or similar:\n" + '\n' + '```\n' + '/*application:web,correlation_id:HnFTVEMUC\n' + "J3,line:/ee/lib/gitlab/database/load_balancing/connection_proxy.rb:63:in `block in read_using_load_balancer'*/\n" + '```\n' + '\n' + '> :line supports a configuration by setting a regexp in Marginalia::Comment.lines_to_ignore to exclude parts of the stacktrace from inclusion in the line comment.\n' + '\n' + 'Marginalia supports to filter particular lines, so perhaps we can tune it more to our needs. The goal is to show the line in the codebase where the query originated from.\n' + '\n' + 'As [noted](https://gitlab.com/gitlab-org/database-team/team-tasks/issues/30#note_292679100) by @sribalakumar, there might be performance implications coming out of this.', createdAt: '2020-02-24T12:49:46.119Z', updatedAt: '2020-03-02T11:14:16.842Z', closedAt: null, state: 'opened', id: 207825, }, ]; return { items: items || defaultItems, totalCount: (items === null || items === void 0 ? void 0 : items.length) || 1, hasNextPage: true, hasPreviousPage: false, page: (pagination === null || pagination === void 0 ? void 0 : pagination.page) || 1, perPage: (pagination === null || pagination === void 0 ? void 0 : pagination.perPage) || 1, }; }; exports.mockListIssuesResponseForUser = [ { user: { id: '3045721', login: 'Homolova', url: 'https://gitlab.com/Homolova', }, url: 'https://gitlab.com/Homolova/ted_ontouml_kom/issues/1', body: 'test', createdAt: '2020-03-05T14:13:37.362Z', updatedAt: '2020-03-05T14:13:37.362Z', closedAt: null, state: 'opened', id: 1, }, ]; //# sourceMappingURL=listIssuesResponse.js.map
Hamed-kshiem/CE-IoT
src/main/java/iotpanel/CE/Security/APISecurityConfig.java
/* * Copyright (c) 2020. Hamed CE * */ package iotpanel.CE.Security; import net.minidev.json.JSONUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.w3c.dom.ls.LSOutput; @Configuration @EnableWebSecurity public class APISecurityConfig extends WebSecurityConfigurerAdapter { @Value("${principalRequestValue}") private String principalRequestValue; @Override protected void configure(HttpSecurity httpSecurity) throws Exception { String principalRequestHeader = "API_KEY"; APIKeyAuthFilter filter = new APIKeyAuthFilter(principalRequestHeader); filter.setAuthenticationManager(new AuthenticationManager() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String principal = (String) authentication.getPrincipal(); if (!principalRequestValue.equals(principal)) { System.out.println("failed"); throw new BadCredentialsException("The API key was not found or not the expected value."); } authentication.setAuthenticated(true); return authentication; } }); System.out.println(principalRequestHeader); System.out.println(principalRequestValue); /* httpSecurity. antMatcher("/auth/**"). csrf().disable(). sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS). and().addFilter(filter).authorizeRequests().anyRequest().authenticated();*/ } }
pettyferlove/rich
rich-common/rich-common-message/src/main/java/com/github/rich/message/domain/dto/message/EmailMessage.java
package com.github.rich.message.domain.dto.message; import com.github.rich.message.domain.dto.Message; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; /** * @author Petty */ @Data @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class EmailMessage extends Message { private static final long serialVersionUID = -1319965212586428898L; private String subject; }
hleclerc/Evel
src/Evel/TlsConnection_WF.cpp
#include "TlsConnection_WF.h" namespace Evel { TlsConnection_WF::~TlsConnection_WF() { if ( f_close ) f_close( this ); } void TlsConnection_WF::on_rdy() { if ( f_rdy ) f_rdy( this ); } void TlsConnection_WF::parse( char **data, size_t size, size_t rese ) { if ( f_parse ) f_parse( this, data, size, rese ); } } // namespace Evel
triceo/kogito-apps
jitexecutor/jitexecutor-dmn/src/main/java/org/kie/kogito/jitexecutor/dmn/responses/JITDMNResult.java
<filename>jitexecutor/jitexecutor-dmn/src/main/java/org/kie/kogito/jitexecutor/dmn/responses/JITDMNResult.java /* * Copyright 2022 Red Hat, Inc. and/or its affiliates. * * 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 org.kie.kogito.jitexecutor.dmn.responses; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.kie.dmn.api.core.DMNContext; import org.kie.dmn.api.core.DMNDecisionResult; import org.kie.dmn.api.core.DMNMessage; import org.kie.dmn.api.core.DMNMessage.Severity; import org.kie.dmn.core.internal.utils.MapBackedDMNContext; import org.kie.dmn.core.internal.utils.MarshallingStubUtils; import com.fasterxml.jackson.annotation.JsonIgnore; public class JITDMNResult implements Serializable, org.kie.dmn.api.core.DMNResult { private String namespace; private String modelName; private Map<String, Object> dmnContext = new HashMap<>(); private List<JITDMNMessage> messages = new ArrayList<>(); private Map<String, JITDMNDecisionResult> decisionResults = new HashMap<>(); public JITDMNResult() { // Intentionally blank. } public JITDMNResult(String namespace, String modelName, org.kie.dmn.api.core.DMNResult dmnResult) { this.namespace = namespace; this.modelName = modelName; this.setDmnContext(dmnResult.getContext().getAll()); this.setMessages(dmnResult.getMessages()); this.setDecisionResults(dmnResult.getDecisionResults()); } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public Map<String, Object> getDmnContext() { return dmnContext; } public void setDmnContext(Map<String, Object> dmnContext) { this.dmnContext = new HashMap<>(); for (Entry<String, Object> kv : dmnContext.entrySet()) { this.dmnContext.put(kv.getKey(), MarshallingStubUtils.stubDMNResult(kv.getValue(), String::valueOf)); } } public void setMessages(List<? extends DMNMessage> messages) { this.messages = new ArrayList<>(); for (DMNMessage m : messages) { this.messages.add(JITDMNMessage.of(m)); } } public void setDecisionResults(List<? extends DMNDecisionResult> decisionResults) { this.decisionResults = new HashMap<>(); for (DMNDecisionResult dr : decisionResults) { this.decisionResults.put(dr.getDecisionId(), JITDMNDecisionResult.of(dr)); } } @JsonIgnore @Override public DMNContext getContext() { return MapBackedDMNContext.of(dmnContext); } @Override public List<DMNMessage> getMessages() { return (List) messages; } @Override public List<DMNMessage> getMessages(Severity... sevs) { return this.messages.stream() .filter(m -> Arrays.asList(sevs).stream().anyMatch(f -> f.equals(m.getSeverity()))) .collect(Collectors.toList()); } @Override public boolean hasErrors() { return messages.stream().anyMatch(m -> DMNMessage.Severity.ERROR.equals(m.getSeverity())); } @Override public List<DMNDecisionResult> getDecisionResults() { return new ArrayList<>(decisionResults.values()); } @Override public DMNDecisionResult getDecisionResultByName(String name) { return decisionResults.values().stream() .filter(dr -> dr.getDecisionName().equals(name)) .findFirst() .orElseThrow(() -> new RuntimeException("Unknown decision result name.")); } @Override public DMNDecisionResult getDecisionResultById(String id) { return decisionResults.get(id); } @Override public String toString() { return new StringBuilder("JITDMNResult [") .append("namespace=").append(namespace) .append(", modelName=").append(modelName) .append(", dmnContext=").append(dmnContext) .append(", messages=").append(messages) .append(", decisionResults=").append(decisionResults) .append("]").toString(); } }
wsw2008new/iBase4J
iBase4J-SYS-Service/src/main/java/org/ibase4j/provider/sys/SysMenuProviderImpl.java
package org.ibase4j.provider.sys; import java.util.Map; import org.ibase4j.core.base.BaseProviderImpl; import org.ibase4j.core.support.dubbo.spring.annotation.DubboService; import org.ibase4j.dao.sys.SysMenuExpandMapper; import org.ibase4j.model.generator.SysMenu; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import com.github.pagehelper.PageInfo; /** * @author ShenHuaJie * @version 2016年5月20日 下午3:19:19 */ @CacheConfig(cacheNames = "sysMenu") @DubboService(interfaceClass = SysMenuProvider.class) public class SysMenuProviderImpl extends BaseProviderImpl<SysMenu> implements SysMenuProvider { @Autowired private SysMenuExpandMapper sysMenuExpandMapper; @Autowired private SysDicProviderImpl sysDicService; public PageInfo<SysMenu> query(Map<String, Object> params) { this.startPage(params); PageInfo<SysMenu> pageInfo = getPage(sysMenuExpandMapper.query(params)); Map<String, String> menuTypeMap = sysDicService.queryDicByDicIndexKey("MENUTYPE"); for (SysMenu sysMenu : pageInfo.getList()) { if (sysMenu.getMenuType() != null) { sysMenu.setRemark(menuTypeMap.get(sysMenu.getMenuType().toString())); } } return pageInfo; } }
scala-steward/reactive-aws-clients
reactive-aws-kms/core/src/main/scala/com/github/j5ik2o/reactive/aws/kms/model/ops/CreateKeyRequestOps.scala
<gh_stars>10-100 // Auto-Generated package com.github.j5ik2o.reactive.aws.kms.model.ops import software.amazon.awssdk.services.kms.model._ final class CreateKeyRequestBuilderOps(val self: CreateKeyRequest.Builder) extends AnyVal { @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def policyAsScala(value: Option[String]): CreateKeyRequest.Builder = { value.fold(self) { v => self.policy(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def descriptionAsScala(value: Option[String]): CreateKeyRequest.Builder = { value.fold(self) { v => self.description(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def keyUsageAsScala(value: Option[KeyUsageType]): CreateKeyRequest.Builder = { value.fold(self) { v => self.keyUsage(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def customerMasterKeySpecAsScala(value: Option[CustomerMasterKeySpec]): CreateKeyRequest.Builder = { value.fold(self) { v => self.customerMasterKeySpec(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def originAsScala(value: Option[OriginType]): CreateKeyRequest.Builder = { value.fold(self) { v => self.origin(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def customKeyStoreIdAsScala(value: Option[String]): CreateKeyRequest.Builder = { value.fold(self) { v => self.customKeyStoreId(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def bypassPolicyLockoutSafetyCheckAsScala(value: Option[Boolean]): CreateKeyRequest.Builder = { value.fold(self) { v => self.bypassPolicyLockoutSafetyCheck(v) } } @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def tagsAsScala(value: Option[Seq[Tag]]): CreateKeyRequest.Builder = { value.filter(_.nonEmpty).fold(self) { v => import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; self.tags(v.asJava) } } } final class CreateKeyRequestOps(val self: CreateKeyRequest) extends AnyVal { @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def policyAsScala: Option[String] = Option(self.policy) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def descriptionAsScala: Option[String] = Option(self.description) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def keyUsageAsScala: Option[KeyUsageType] = Option(self.keyUsage) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def customerMasterKeySpecAsScala: Option[CustomerMasterKeySpec] = Option(self.customerMasterKeySpec) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def originAsScala: Option[OriginType] = Option(self.origin) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def customKeyStoreIdAsScala: Option[String] = Option(self.customKeyStoreId) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def bypassPolicyLockoutSafetyCheckAsScala: Option[Boolean] = Option(self.bypassPolicyLockoutSafetyCheck) @SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf")) final def tagsAsScala: Option[Seq[Tag]] = Option(self.tags).map { v => import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; v.asScala } } @SuppressWarnings(Array("org.wartremover.warts.ImplicitConversion")) trait ToCreateKeyRequestOps { implicit def toCreateKeyRequestBuilderOps(v: CreateKeyRequest.Builder): CreateKeyRequestBuilderOps = new CreateKeyRequestBuilderOps(v) implicit def toCreateKeyRequestOps(v: CreateKeyRequest): CreateKeyRequestOps = new CreateKeyRequestOps(v) }
lycantropos/voronoi
tests/integration_tests/utils_tests/test_compare_floats.py
<gh_stars>0 from _voronoi import compare_floats as bound from hypothesis import given from voronoi.utils import compare_floats as ported from . import strategies @given(strategies.floats, strategies.floats, strategies.sizes) def test_basic(left: float, right: float, max_ulps: int) -> None: assert bound(left, right, max_ulps) == ported(left, right, max_ulps)
gadge/spare
packages/padder/matrix-padder/src/matrixPadder.js
<filename>packages/padder/matrix-padder/src/matrixPadder.js import { Pad } from '@texting/padder' import { mapper } from '@vect/matrix-mapper' import { matrixPadderFull } from './matrixPadderFull' import { columnWidth } from './columnWidth' /** * * @param {string[][]} mx * @param {object} [config] * @param {boolean} [config.ansi] * @param {boolean} [config.full] * @param {string} [config.fill] * @returns {string[][]} */ export const matrixPadder = (mx, config = {}) => { if (config.full) return matrixPadderFull(mx, config) const widths = columnWidth(mx, config.ansi) const pad = Pad(config) return mapper(mx, (tx, i, j) => pad(tx, widths[j])) } // let zipper // return dye // ? (zipper = Trizipper((tx, va, dy, i, j) => pad(tx, widths[j], va) |> dy), // zipper(mx, mx, dye)) // : (zipper = Duozipper((tx, va, i, j) => pad(tx, widths[j], va)), // zipper(mx, mx))
joelpinheiro/craft-store
sd_second_project/src/communication/package-info.java
<reponame>joelpinheiro/craft-store<gh_stars>1-10 /** * Infraestruturas comuns. * Solução do Problema dos Barbeiros Sonolentos que implementa o modelo cliente-servidor * de tipo 2 (replicação do servidor) com lançamento estático dos threads barbeiro. * A comunicação baseia-se em passagem de mensagens sobre sockets usando o protocolo TCP. */ package communication;
tobyapi/online-judge-solutions
poj/3254.cpp
<filename>poj/3254.cpp #include<iostream> #include<algorithm> #define mod 100000000 using namespace std; int dp[145][1<<12]; int main(void){ int n,m,g[12][12],in; cin >> n >> m; for(int i=0;i<n;i++) for(int j=0;j<m;j++)cin >> g[i][j]; dp[0][0]=1; for(int i=0;i<n*m;i++){ int x=i%m,y=i/m; for(int S=0;S<(1<<m);S++){ int nx=(S<<1)&~(1<<m); dp[i+1][nx]+=dp[i][S]; dp[i+1][nx]%=mod; if(g[y][x] && !((S&1)*x) && !((S>>(m-1))&1)){ dp[i+1][nx|1]+=dp[i][S]; dp[i+1][nx|1]%=mod; } } } int ans=0; for(int i=0;i<(1<<m);i++)ans+=dp[n*m][i]; cout << ans%mod << endl; return 0; }
certcomm/CertProof
app/js/components/Thread/js/stores/ThreadStore.js
import { observable } from "mobx" export class ThreadStore { @observable thread = {}; setData(data) { this.thread = data; } setError(err) { this.error = err; } getError() { return this.error; } getData() { return this.thread; } } export default new ThreadStore
zagura/aoc-2017
2019/14day/task2.cpp
<filename>2019/14day/task2.cpp /* * ===================================================================================== * * Filename: task1.cpp * * Description: Day 14 - Space Stoichometry * * Version: 1.0 * Created: 17.12.2019 * * Author: <NAME> (zagura), <<EMAIL>> * Organization: AGH University of Science and Technology, Kraków * * ===================================================================================== */ #include <iostream> #include <map> #include <sstream> #include <vector> #include <string> #include <array> #include <algorithm> #include <queue> using namespace std; using amount_type = int64_t; constexpr amount_type kTrillion = 1000000000000; struct Node { int id; amount_type target_amount; vector<pair<int, amount_type>> neighbors; }; string over_trillion(amount_type amount) { if (amount >= kTrillion) { return "true"; } return "false"; } bool program(vector<Node>& nodes, amount_type total_amount) { map<int, amount_type> amounts { { 1, total_amount}}; queue<int> q; q.push(1); while (not q.empty()) { int node_id = q.front(); q.pop(); // if (amounts[node_id] < 0) { // cout << "node: " << node_id << " | amount: " << amounts[node_id] << endl; // } Node& node = nodes[node_id]; if (node_id == 0) { continue; } amount_type base_amount = node.target_amount; amount_type required_amount = amounts[node_id]; amount_type mul = required_amount / base_amount + ((required_amount % base_amount > 0) ? 1 : 0); for (auto& p: node.neighbors) { q.push(p.first); amounts[p.first] += mul * p.second; } if (node_id != 0) { amounts[node_id] -= mul * base_amount; } } cout << total_amount << ": " << amounts[0] << " | " << over_trillion(amounts[0]) << endl; return (amounts[0] > kTrillion); // int current_node = 1; } int main() { map <string, int> names; names["ORE"] = 0; names["FUEL"] = 1; string line; vector<Node> nodes; nodes.resize(100); while (getline(std::cin, line)) { stringstream ss { line }; string ingridients; vector<pair<int, amount_type>> receipt; getline(ss, ingridients, '='); // cout << "Ingridients: " << ingridients << endl; { stringstream left_side { ingridients }; for(string single; getline(left_side, single, ',');) { stringstream single_part { single }; amount_type amount; string name; single_part >> amount >> name; // cout << "Ingridient: " << amount << " " << name << endl; int id; if (names.find(name) != names.end()) { id = names.at(name); } else { id = names.size(); names[name] = id; } receipt.emplace_back(id, amount); } } string result; getline(ss, result, '='); // cout << "Right side: " << result.substr(1) << endl; stringstream result_ss { result.substr(1) }; amount_type amount; string name; int id; result_ss >> amount >> name; if (names.find(name) != names.end()) { id = names.at(name); } else { id = names.size(); names[name] = id; } Node node; node.id = id; node.neighbors = receipt; node.target_amount = amount; nodes[id] = node; } nodes.resize(names.size()); /// Here we have full graph, let's find path from 1 to 0 and get count. /// Part 2 made semi-manual. Find the amount of fuel, when needed ORE overflow 10^12. amount_type init_amount = 6226100; for (amount_type a = init_amount; init_amount < init_amount + 100 ; a+= 1) { if (program(nodes, a)) { break; } } return 0; }
CresTechGlobalPractice/DBS_Automation
src/main/java/com/crestech/common/utilities/CommonAlertElements.java
package com.crestech.common.utilities; import java.time.Duration; import java.util.List; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.PageFactory; import com.crestech.annotation.values.ElementDescription; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AppiumFieldDecorator; public class CommonAlertElements { public AppiumDriver<RemoteWebElement> driver1; public CommonAlertElements(AppiumDriver<RemoteWebElement> driver) { this.driver1 = driver; PageFactory.initElements(new AppiumFieldDecorator(driver, Duration.ofSeconds(5)), this); } public AppiumDriver<RemoteWebElement> driver; @ElementDescription(value = "Toast Message Element") @AndroidFindBy(xpath = "//android.widget.Toast") private MobileElement ToastMessageElement; @ElementDescription(value = "Toast Message Element List") @AndroidFindBy(xpath = "//android.widget.Toast") private List<MobileElement> ToastMessageElementList; @ElementDescription(value = "Toggle List") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='android:id/switch_widget']") private List<MobileElement> toggleList; @ElementDescription(value = "Title Alert") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='android:id/alertTitle']") private MobileElement TitleAlert; @ElementDescription(value = "Message Alert") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='android:id/message']") private MobileElement MessageAlert; @ElementDescription(value = "Ok Alert") @AndroidFindBy(xpath = "//android.widget.TextView[@text='OK']") private MobileElement OKAlert; @ElementDescription(value = "Cancel Alert") @AndroidFindBy(xpath = "//android.widget.TextView[@text='CANCEL']") private MobileElement CancelAlert; @ElementDescription(value = "AllOW Button") @AndroidFindBy(xpath = "//android.widget.TextView[@text='AllOW']") private MobileElement AllOWAlert; @ElementDescription(value = "DENY Button") @AndroidFindBy(xpath = "//android.widget.TextView[@text='DENY']") private MobileElement DENYAlert; @ElementDescription(value = "DENY ANYWAY Button") @AndroidFindBy(xpath = "//android.widget.TextView[@text='DENY ANYWAY']") private MobileElement DENYANYWAYAlert; @ElementDescription(value = "Not Responding Title") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='android:id/alertTitle']") private MobileElement NotRespondingTitle; @ElementDescription(value = "Not Responding Close") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='android:id/aerr_close']") private MobileElement NotRespondingClose; @ElementDescription(value = "Not Responding Wait") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='android:id/aerr_wait']") private MobileElement NotRespondingWait; @ElementDescription(value = "Permission Aler Message") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='com.android.permissioncontroller:id/permissions_message']") private MobileElement PermissionAlertMessage; @ElementDescription(value = "Permission Alert Cancel") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='com.android.permissioncontroller:id/cancel_button']") private MobileElement PermissionAlertCancel; @ElementDescription(value = "Permission Alert Continue") @AndroidFindBy(xpath = "//android.widget.TextView[@resource-id='com.android.permissioncontroller:id/continue_button']") private MobileElement PermissionAlertContinue; public MobileElement getToastMessageElement() { return ToastMessageElement; } public List<MobileElement> getToastMessageElementList() { return ToastMessageElementList; } public List<MobileElement> toggleList() { return toggleList; } public MobileElement PermissionAlertContinueButton() { return PermissionAlertContinue; } public MobileElement PermissionAlertCancelButton() { return PermissionAlertCancel; } public MobileElement getPermissionMessage() { return PermissionAlertMessage; } public MobileElement NotRespondingWaitButton() { return NotRespondingWait; } public MobileElement NotRespondingCloseButton() { return NotRespondingClose; } public MobileElement getNotRespondingTitle() { return NotRespondingTitle; } public MobileElement DenyAnywayButton() { return DENYANYWAYAlert; } public MobileElement DenyButton() { return DENYAlert; } public MobileElement OkButton() { return OKAlert; } public MobileElement CancelButton() { return CancelAlert; } public MobileElement AllowButton() { return AllOWAlert; } public MobileElement getalertMessage() { return MessageAlert; } public MobileElement getalertTitle() { return TitleAlert; } /** * This is applications alert element asking to relaunch the application */ @ElementDescription(value = "Message") @AndroidFindBy(xpath = "/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.TextView[2]") private MobileElement Message; @ElementDescription(value = "Quit Button") @AndroidFindBy(xpath = "/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.Button") private MobileElement QuitButton; @ElementDescription(value = "Title") @AndroidFindBy(xpath = "//android.widget.TextView[@text='Alert']") private MobileElement Title; public MobileElement getMessage() { return Message; } public MobileElement getTitle() { return Title; } public MobileElement quitButton() { return QuitButton; } /** * */ /** * This is applications alert element After login */ @ElementDescription(value = "Alert header") @AndroidFindBy(xpath = "//android.widget.TextView[contains(@resource-id,'txt_header')]") private MobileElement headerMessage; @ElementDescription(value = "Swipe Button") @AndroidFindBy(xpath = "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.view.View") private MobileElement swipeButton; public MobileElement headerMessage() { return headerMessage; } public MobileElement swipeButton() { return swipeButton; } /** * */ /** * This is applications alert element asking to enable fingerprint */ @ElementDescription(value = "Alert Fingerprint Message") @AndroidFindBy(xpath = "//android.widget.TextView[contains(@resource-id,'id/desc')]") private MobileElement headerFingerprintMessage; @ElementDescription(value = "Close Button") @AndroidFindBy(xpath = "//android.widget.ImageView[@content-desc='CLOSE']") private MobileElement closeButton; public MobileElement headerFingerprintMessage() { return headerFingerprintMessage; } public MobileElement closeButton() { return closeButton; } /** * */ /** * This is applications alert element asking to enable recording */ @ElementDescription(value = "Alert recordingt Message") @AndroidFindBy(xpath = "//android.widget.TextView[contains(@resource-id,'id/title')]") private MobileElement headerRecordingMessage; //android.widget.ImageView[@content-desc="CLOSE"] // closed button is same as previous popup public MobileElement headerRecordingMessage() { return headerRecordingMessage; } }
creepyCaller/minecraft-analysis
src/net/minecraft/network/play/client/CPacketRecipePlacement.java
<filename>src/net/minecraft/network/play/client/CPacketRecipePlacement.java package net.minecraft.network.play.client; import com.google.common.collect.Lists; import java.io.IOException; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; public class CPacketRecipePlacement implements Packet<INetHandlerPlayServer> { private int field_192616_a; private short field_192617_b; private List<CPacketRecipePlacement.ItemMove> field_192618_c; private List<CPacketRecipePlacement.ItemMove> field_192619_d; public CPacketRecipePlacement() { } public CPacketRecipePlacement(int p_i47425_1_, List<CPacketRecipePlacement.ItemMove> p_i47425_2_, List<CPacketRecipePlacement.ItemMove> p_i47425_3_, short p_i47425_4_) { this.field_192616_a = p_i47425_1_; this.field_192617_b = p_i47425_4_; this.field_192618_c = p_i47425_2_; this.field_192619_d = p_i47425_3_; } public int func_192613_a() { return this.field_192616_a; } public short func_192614_b() { return this.field_192617_b; } /** * Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer buf) throws IOException { this.field_192616_a = buf.readByte(); this.field_192617_b = buf.readShort(); this.field_192618_c = this.func_192611_c(buf); this.field_192619_d = this.func_192611_c(buf); } private List<CPacketRecipePlacement.ItemMove> func_192611_c(PacketBuffer p_192611_1_) throws IOException { int i = p_192611_1_.readShort(); List<CPacketRecipePlacement.ItemMove> list = Lists.<CPacketRecipePlacement.ItemMove>newArrayListWithCapacity(i); for (int j = 0; j < i; ++j) { ItemStack itemstack = p_192611_1_.readItemStackFromBuffer(); byte b0 = p_192611_1_.readByte(); byte b1 = p_192611_1_.readByte(); list.add(new CPacketRecipePlacement.ItemMove(itemstack, b0, b1)); } return list; } /** * Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer buf) throws IOException { buf.writeByte(this.field_192616_a); buf.writeShort(this.field_192617_b); this.func_192612_a(buf, this.field_192618_c); this.func_192612_a(buf, this.field_192619_d); } private void func_192612_a(PacketBuffer p_192612_1_, List<CPacketRecipePlacement.ItemMove> p_192612_2_) { p_192612_1_.writeShort(p_192612_2_.size()); for (CPacketRecipePlacement.ItemMove cpacketrecipeplacement$itemmove : p_192612_2_) { p_192612_1_.writeItemStackToBuffer(cpacketrecipeplacement$itemmove.field_192673_a); p_192612_1_.writeByte(cpacketrecipeplacement$itemmove.field_192674_b); p_192612_1_.writeByte(cpacketrecipeplacement$itemmove.field_192675_c); } } /** * Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer handler) { handler.func_191985_a(this); } public List<CPacketRecipePlacement.ItemMove> func_192615_c() { return this.field_192619_d; } public List<CPacketRecipePlacement.ItemMove> func_192610_d() { return this.field_192618_c; } public static class ItemMove { public ItemStack field_192673_a; public int field_192674_b; public int field_192675_c; public ItemMove(ItemStack p_i47401_1_, int p_i47401_2_, int p_i47401_3_) { this.field_192673_a = p_i47401_1_.copy(); this.field_192674_b = p_i47401_2_; this.field_192675_c = p_i47401_3_; } } }
daddykotex/smithy4s
modules/aws-kernel/src/smithy4s/aws/AwsCredentials.scala
/* * Copyright 2021 <NAME> * * Licensed under the Tomorrow Open Source Technology License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://disneystreaming.github.io/TOST-1.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package smithy4s.aws.kernel trait AwsCredentials { def accessKeyId: String def secretAccessKey: String def sessionToken: Option[String] } trait AwsTemporaryCredentials extends AwsCredentials { def expiration: Timestamp } object AwsCredentials { final case class Default( accessKeyId: String, secretAccessKey: String, sessionToken: Option[String] ) extends AwsCredentials }
v-2vikc/weblogic-kubernetes-operator
operator/src/main/java/oracle/kubernetes/operator/Main.java
// Copyright 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved. // Licensed under the Universal Permissive License v 1.0 as shown at // http://oss.oracle.com/licenses/upl. package oracle.kubernetes.operator; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import io.kubernetes.client.models.V1EventList; import io.kubernetes.client.models.V1Pod; import io.kubernetes.client.models.V1PodList; import io.kubernetes.client.models.V1Service; import io.kubernetes.client.models.V1ServiceList; import oracle.kubernetes.operator.calls.CallResponse; import oracle.kubernetes.operator.helpers.CallBuilder; import oracle.kubernetes.operator.helpers.CallBuilderFactory; import oracle.kubernetes.operator.helpers.ClientPool; import oracle.kubernetes.operator.helpers.ConfigMapHelper; import oracle.kubernetes.operator.helpers.CrdHelper; import oracle.kubernetes.operator.helpers.DomainPresenceInfo; import oracle.kubernetes.operator.helpers.HealthCheckHelper; import oracle.kubernetes.operator.helpers.KubernetesVersion; import oracle.kubernetes.operator.helpers.PodHelper; import oracle.kubernetes.operator.helpers.ResponseStep; import oracle.kubernetes.operator.helpers.ServiceHelper; import oracle.kubernetes.operator.logging.LoggingFacade; import oracle.kubernetes.operator.logging.LoggingFactory; import oracle.kubernetes.operator.logging.MessageKeys; import oracle.kubernetes.operator.rest.RestConfigImpl; import oracle.kubernetes.operator.rest.RestServer; import oracle.kubernetes.operator.steps.ConfigMapAfterStep; import oracle.kubernetes.operator.work.Component; import oracle.kubernetes.operator.work.Container; import oracle.kubernetes.operator.work.ContainerResolver; import oracle.kubernetes.operator.work.Engine; import oracle.kubernetes.operator.work.Fiber; import oracle.kubernetes.operator.work.Fiber.CompletionCallback; import oracle.kubernetes.operator.work.FiberGate; import oracle.kubernetes.operator.work.NextAction; import oracle.kubernetes.operator.work.Packet; import oracle.kubernetes.operator.work.Step; import oracle.kubernetes.operator.work.ThreadFactorySingleton; import oracle.kubernetes.weblogic.domain.model.Domain; import oracle.kubernetes.weblogic.domain.model.DomainList; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; /** A Kubernetes Operator for WebLogic. */ public class Main { private static final LoggingFacade LOGGER = LoggingFactory.getLogger("Operator", "Operator"); private static final String DPI_MAP = "DPI_MAP"; private static final Container container = new Container(); private static final ThreadFactory threadFactory = new WrappedThreadFactory(); private static final ScheduledExecutorService wrappedExecutorService = Engine.wrappedExecutorService("operator", container); private static final TuningParameters tuningAndConfig; private static final CallBuilderFactory callBuilderFactory = new CallBuilderFactory(); private static final Map<String, AtomicBoolean> isNamespaceStarted = new ConcurrentHashMap<>(); private static final Map<String, AtomicBoolean> isNamespaceStopping = new ConcurrentHashMap<>(); private static final Map<String, ConfigMapWatcher> configMapWatchers = new ConcurrentHashMap<>(); private static final Map<String, DomainWatcher> domainWatchers = new ConcurrentHashMap<>(); private static final Map<String, EventWatcher> eventWatchers = new ConcurrentHashMap<>(); private static final Map<String, ServiceWatcher> serviceWatchers = new ConcurrentHashMap<>(); private static final Map<String, PodWatcher> podWatchers = new ConcurrentHashMap<>(); private static final String operatorNamespace = computeOperatorNamespace(); private static final AtomicReference<DateTime> lastFullRecheck = new AtomicReference<>(DateTime.now()); private static final DomainProcessorDelegateImpl delegate = new DomainProcessorDelegateImpl(); private static final DomainProcessor processor = new DomainProcessorImpl(delegate); private static final String READINESS_PROBE_FAILURE_EVENT_FILTER = "reason=Unhealthy,type=Warning,involvedObject.fieldPath=spec.containers{weblogic-server}"; private static final Semaphore shutdownSignal = new Semaphore(0); private static Engine engine = new Engine(wrappedExecutorService); private static String principal; private static KubernetesVersion version = null; static { try { // suppress System.err since we catch all necessary output with Logger OutputStream output = new FileOutputStream("/dev/null"); PrintStream nullOut = new PrintStream(output); System.setErr(nullOut); ClientPool.initialize(threadFactory); TuningParameters.initializeInstance(wrappedExecutorService, "/operator/config"); tuningAndConfig = TuningParameters.getInstance(); } catch (IOException e) { LOGGER.warning(MessageKeys.EXCEPTION, e); throw new RuntimeException(e); } } static { container .getComponents() .put( ProcessingConstants.MAIN_COMPONENT_NAME, Component.createFor( ScheduledExecutorService.class, wrappedExecutorService, TuningParameters.class, tuningAndConfig, ThreadFactory.class, threadFactory, callBuilderFactory)); } /** * Entry point. * * @param args none, ignored */ public static void main(String[] args) { try (final InputStream stream = Main.class.getResourceAsStream("/version.properties")) { Properties buildProps = new Properties(); buildProps.load(stream); String operatorVersion = buildProps.getProperty("git.build.version"); String operatorImpl = buildProps.getProperty("git.branch") + "." + buildProps.getProperty("git.commit.id.abbrev"); String operatorBuildTime = buildProps.getProperty("git.build.time"); // print startup log message LOGGER.info(MessageKeys.OPERATOR_STARTED, operatorVersion, operatorImpl, operatorBuildTime); } catch (IOException e) { LOGGER.warning(MessageKeys.EXCEPTION, e); } try { engine.getExecutor().execute(Main::begin); // now we just wait until the pod is terminated waitForDeath(); // stop the REST server stopRestServer(); } finally { LOGGER.info(MessageKeys.OPERATOR_SHUTTING_DOWN); } } private static void begin() { String serviceAccountName = Optional.ofNullable(tuningAndConfig.get("serviceaccount")).orElse("default"); principal = "system:serviceaccount:" + operatorNamespace + ":" + serviceAccountName; LOGGER.info(MessageKeys.OP_CONFIG_NAMESPACE, operatorNamespace); JobWatcher.defineFactory( threadFactory, tuningAndConfig.getWatchTuning(), Main::isNamespaceStopping); Collection<String> targetNamespaces = getTargetNamespaces(); LOGGER.info(MessageKeys.OP_CONFIG_TARGET_NAMESPACES, StringUtils.join(targetNamespaces, ", ")); LOGGER.info(MessageKeys.OP_CONFIG_SERVICE_ACCOUNT, serviceAccountName); try { version = HealthCheckHelper.performK8sVersionCheck(); runSteps( CrdHelper.createDomainCrdStep(version, new StartNamespacesStep(targetNamespaces)), Main::completeBegin); } catch (Throwable e) { LOGGER.warning(MessageKeys.EXCEPTION, e); } } private static void completeBegin() { try { // start the REST server startRestServer(principal, isNamespaceStopping.keySet()); // start periodic retry and recheck int recheckInterval = tuningAndConfig.getMainTuning().targetNamespaceRecheckIntervalSeconds; engine .getExecutor() .scheduleWithFixedDelay( recheckDomains(), recheckInterval, recheckInterval, TimeUnit.SECONDS); // Wait until all other initialization is done before marking ready and // starting liveness thread // mark ready and start liveness thread markReadyAndStartLivenessThread(); } catch (Throwable e) { LOGGER.warning(MessageKeys.EXCEPTION, e); } } private static void stopNamespaces(Collection<String> namespacesToStop) { for (String ns : namespacesToStop) { processor.stopNamespace(ns); AtomicBoolean stopping = isNamespaceStopping.remove(ns); if (stopping != null) { stopping.set(true); } isNamespaceStarted.remove(ns); } } private static AtomicBoolean isNamespaceStopping(String ns) { return isNamespaceStopping.computeIfAbsent(ns, (key) -> new AtomicBoolean(false)); } private static void runSteps(Step firstStep) { runSteps(firstStep, null); } private static void runSteps(Step firstStep, Runnable completionAction) { Fiber f = engine.createFiber(); f.start(firstStep, new Packet(), andThenDo(completionAction)); } private static NullCompletionCallback andThenDo(Runnable completionAction) { return new NullCompletionCallback(completionAction); } private static Runnable recheckDomains() { return () -> { Collection<String> targetNamespaces = getTargetNamespaces(); // Check for removed namespaces Set<String> namespacesToStop = new TreeSet<>(isNamespaceStopping.keySet()); namespacesToStop.removeAll(targetNamespaces); stopNamespaces(namespacesToStop); Collection<String> namespacesToStart = targetNamespaces; int recheckInterval = tuningAndConfig.getMainTuning().domainPresenceRecheckIntervalSeconds; DateTime now = DateTime.now(); if (lastFullRecheck.get().plusSeconds(recheckInterval).isBefore(now)) { lastFullRecheck.set(now); } else { namespacesToStart = new TreeSet<>(targetNamespaces); namespacesToStart.removeAll(isNamespaceStarted.keySet()); } if (!namespacesToStart.isEmpty()) { runSteps(new StartNamespacesStep(namespacesToStart)); } }; } static Step readExistingResources(String operatorNamespace, String ns) { return Step.chain( new ReadExistingResourcesBeforeStep(), ConfigMapHelper.createScriptConfigMapStep(operatorNamespace, ns), createConfigMapStep(ns), readExistingPods(ns), readExistingEvents(ns), readExistingServices(ns), readExistingDomains(ns)); } private static Step readExistingDomains(String ns) { LOGGER.fine(MessageKeys.LISTING_DOMAINS); return callBuilderFactory.create().listDomainAsync(ns, new DomainListStep(ns)); } private static Step readExistingServices(String ns) { return new CallBuilder() .withLabelSelectors(LabelConstants.DOMAINUID_LABEL, LabelConstants.CREATEDBYOPERATOR_LABEL) .listServiceAsync(ns, new ServiceListStep(ns)); } private static Step readExistingEvents(String ns) { return new CallBuilder() .withFieldSelector(Main.READINESS_PROBE_FAILURE_EVENT_FILTER) .listEventAsync(ns, new EventListStep(ns)); } private static Step readExistingPods(String ns) { return new CallBuilder() .withLabelSelectors(LabelConstants.DOMAINUID_LABEL, LabelConstants.CREATEDBYOPERATOR_LABEL) .listPodAsync(ns, new PodListStep(ns)); } private static ConfigMapAfterStep createConfigMapStep(String ns) { return new ConfigMapAfterStep( ns, configMapWatchers, tuningAndConfig.getWatchTuning(), isNamespaceStopping(ns), processor::dispatchConfigMapWatch); } /** * Obtain the list of target namespaces. * * @return the collection of target namespace names */ @SuppressWarnings("SameParameterValue") private static Collection<String> getTargetNamespaces(String tnValue, String namespace) { Collection<String> targetNamespaces = new ArrayList<>(); if (tnValue != null) { StringTokenizer st = new StringTokenizer(tnValue, ","); while (st.hasMoreTokens()) { targetNamespaces.add(st.nextToken().trim()); } } // If no namespaces were found, default to the namespace of the operator if (targetNamespaces.isEmpty()) { targetNamespaces.add(namespace); } return targetNamespaces; } private static Collection<String> getTargetNamespaces() { return getTargetNamespaces( Optional.ofNullable(System.getenv("OPERATOR_TARGET_NAMESPACES")) .orElse(tuningAndConfig.get("targetNamespaces")), operatorNamespace); } private static void startRestServer(String principal, Collection<String> targetNamespaces) throws Exception { RestServer.create(new RestConfigImpl(principal, targetNamespaces)); RestServer.getInstance().start(container); } // ----------------------------------------------------------------------------- // // Below this point are methods that are called primarily from watch handlers, // after watch events are received. // // ----------------------------------------------------------------------------- private static void stopRestServer() { RestServer.getInstance().stop(); RestServer.destroy(); } private static void markReadyAndStartLivenessThread() { try { OperatorReady.create(); LOGGER.info(MessageKeys.STARTING_LIVENESS_THREAD); // every five seconds we need to update the last modified time on the liveness file wrappedExecutorService.scheduleWithFixedDelay(new OperatorLiveness(), 5, 5, TimeUnit.SECONDS); } catch (IOException io) { LOGGER.severe(MessageKeys.EXCEPTION, io); } } private static void waitForDeath() { Runtime.getRuntime().addShutdownHook(new Thread(shutdownSignal::release)); try { shutdownSignal.acquire(); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } isNamespaceStopping.forEach((key, value) -> value.set(true)); } private static EventWatcher createEventWatcher(String ns, String initialResourceVersion) { return EventWatcher.create( threadFactory, ns, READINESS_PROBE_FAILURE_EVENT_FILTER, initialResourceVersion, tuningAndConfig.getWatchTuning(), processor::dispatchEventWatch, isNamespaceStopping(ns)); } private static PodWatcher createPodWatcher(String ns, String initialResourceVersion) { return PodWatcher.create( threadFactory, ns, initialResourceVersion, tuningAndConfig.getWatchTuning(), processor::dispatchPodWatch, isNamespaceStopping(ns)); } private static ServiceWatcher createServiceWatcher(String ns, String initialResourceVersion) { return ServiceWatcher.create( threadFactory, ns, initialResourceVersion, tuningAndConfig.getWatchTuning(), processor::dispatchServiceWatch, isNamespaceStopping(ns)); } private static DomainWatcher createDomainWatcher(String ns, String initialResourceVersion) { return DomainWatcher.create( threadFactory, ns, initialResourceVersion, tuningAndConfig.getWatchTuning(), processor::dispatchDomainWatch, isNamespaceStopping(ns)); } private static String computeOperatorNamespace() { return Optional.ofNullable(System.getenv("OPERATOR_NAMESPACE")).orElse("default"); } private static class WrappedThreadFactory implements ThreadFactory { private final ThreadFactory delegate = ThreadFactorySingleton.getInstance(); @Override public Thread newThread(@Nonnull Runnable r) { return delegate.newThread( () -> { ContainerResolver.getDefault().enterContainer(container); r.run(); }); } } private static class StartNamespacesStep extends Step { private final Collection<String> targetNamespaces; StartNamespacesStep(Collection<String> targetNamespaces) { this.targetNamespaces = targetNamespaces; } @Override protected String getDetail() { return String.join(",", targetNamespaces); } @Override public NextAction apply(Packet packet) { // check for any existing resources and add the watches on them // this would happen when the Domain was running BEFORE the Operator starts up Collection<StepAndPacket> startDetails = new ArrayList<>(); for (String ns : targetNamespaces) { startDetails.add( new StepAndPacket( Step.chain( new StartNamespaceBeforeStep(ns), readExistingResources(operatorNamespace, ns)), packet.clone())); } return doForkJoin(getNext(), packet, startDetails); } } private static class StartNamespaceBeforeStep extends Step { private final String ns; StartNamespaceBeforeStep(String ns) { this.ns = ns; } @Override public NextAction apply(Packet packet) { AtomicBoolean a = isNamespaceStarted.computeIfAbsent(ns, (key) -> new AtomicBoolean(false)); if (!a.getAndSet(true)) { try { HealthCheckHelper.performSecurityChecks(version, operatorNamespace, ns); } catch (Throwable e) { LOGGER.warning(MessageKeys.EXCEPTION, e); } return doNext(packet); } return doEnd(packet); } } private static class ReadExistingResourcesBeforeStep extends Step { @SuppressWarnings("rawtypes") @Override public NextAction apply(Packet packet) { packet.put(DPI_MAP, new ConcurrentHashMap()); return doNext(packet); } } private static class DomainListStep extends ResponseStep<DomainList> { private final String ns; DomainListStep(String ns) { this.ns = ns; } @Override public NextAction onFailure(Packet packet, CallResponse<DomainList> callResponse) { return callResponse.getStatusCode() == CallBuilder.NOT_FOUND ? onSuccess(packet, callResponse) : super.onFailure(packet, callResponse); } @Override public NextAction onSuccess(Packet packet, CallResponse<DomainList> callResponse) { @SuppressWarnings("unchecked") Map<String, DomainPresenceInfo> dpis = (Map<String, DomainPresenceInfo>) packet.get(DPI_MAP); DomainProcessor x = packet.getSpi(DomainProcessor.class); DomainProcessor dp = x != null ? x : processor; Set<String> domainUids = new HashSet<>(); if (callResponse.getResult() != null) { for (Domain dom : callResponse.getResult().getItems()) { String domainUid = dom.getDomainUid(); domainUids.add(domainUid); DomainPresenceInfo info = dpis.compute( domainUid, (k, v) -> { if (v == null) { return new DomainPresenceInfo(dom); } v.setDomain(dom); return v; }); info.setPopulated(true); dp.makeRightDomainPresence(info, true, false, false); } } dpis.forEach( (key, value) -> { if (!domainUids.contains(key)) { // This is a stranded DomainPresenceInfo. value.setDeleting(true); value.setPopulated(true); dp.makeRightDomainPresence(value, true, true, false); } }); if (!domainWatchers.containsKey(ns)) { domainWatchers.put( ns, createDomainWatcher(ns, getResourceVersion(callResponse.getResult()))); } return doNext(packet); } String getResourceVersion(DomainList result) { return result != null ? result.getMetadata().getResourceVersion() : ""; } } private static class ServiceListStep extends ResponseStep<V1ServiceList> { private final String ns; ServiceListStep(String ns) { this.ns = ns; } @Override public NextAction onFailure(Packet packet, CallResponse<V1ServiceList> callResponse) { return callResponse.getStatusCode() == CallBuilder.NOT_FOUND ? onSuccess(packet, callResponse) : super.onFailure(packet, callResponse); } @Override public NextAction onSuccess(Packet packet, CallResponse<V1ServiceList> callResponse) { V1ServiceList result = callResponse.getResult(); @SuppressWarnings("unchecked") Map<String, DomainPresenceInfo> dpis = (Map<String, DomainPresenceInfo>) packet.get(DPI_MAP); if (result != null) { for (V1Service service : result.getItems()) { String domainUid = ServiceHelper.getServiceDomainUid(service); if (domainUid != null) { DomainPresenceInfo info = dpis.computeIfAbsent(domainUid, k -> new DomainPresenceInfo(ns, domainUid)); ServiceHelper.addToPresence(info, service); } } } if (!serviceWatchers.containsKey(ns)) { serviceWatchers.put(ns, createServiceWatcher(ns, getInitialResourceVersion(result))); } return doNext(packet); } private String getInitialResourceVersion(V1ServiceList result) { return result != null ? result.getMetadata().getResourceVersion() : ""; } } private static class EventListStep extends ResponseStep<V1EventList> { private final String ns; EventListStep(String ns) { this.ns = ns; } @Override public NextAction onFailure(Packet packet, CallResponse<V1EventList> callResponse) { return callResponse.getStatusCode() == CallBuilder.NOT_FOUND ? onSuccess(packet, callResponse) : super.onFailure(packet, callResponse); } @Override public NextAction onSuccess(Packet packet, CallResponse<V1EventList> callResponse) { V1EventList result = callResponse.getResult(); // don't bother processing pre-existing events if (!eventWatchers.containsKey(ns)) { eventWatchers.put(ns, createEventWatcher(ns, getInitialResourceVersion(result))); } return doNext(packet); } private String getInitialResourceVersion(V1EventList result) { return result != null ? result.getMetadata().getResourceVersion() : ""; } } private static class PodListStep extends ResponseStep<V1PodList> { private final String ns; PodListStep(String ns) { this.ns = ns; } @Override public NextAction onFailure(Packet packet, CallResponse<V1PodList> callResponse) { return callResponse.getStatusCode() == CallBuilder.NOT_FOUND ? onSuccess(packet, callResponse) : super.onFailure(packet, callResponse); } @Override public NextAction onSuccess(Packet packet, CallResponse<V1PodList> callResponse) { V1PodList result = callResponse.getResult(); @SuppressWarnings("unchecked") Map<String, DomainPresenceInfo> dpis = (Map<String, DomainPresenceInfo>) packet.get(DPI_MAP); if (result != null) { for (V1Pod pod : result.getItems()) { String domainUid = PodHelper.getPodDomainUid(pod); String serverName = PodHelper.getPodServerName(pod); if (domainUid != null && serverName != null) { DomainPresenceInfo info = dpis.computeIfAbsent(domainUid, k -> new DomainPresenceInfo(ns, domainUid)); info.setServerPod(serverName, pod); } } } if (!podWatchers.containsKey(ns)) { podWatchers.put(ns, createPodWatcher(ns, getInitialResourceVersion(result))); } return doNext(packet); } private String getInitialResourceVersion(V1PodList result) { return result != null ? result.getMetadata().getResourceVersion() : ""; } } private static class NullCompletionCallback implements CompletionCallback { private Runnable completionAction; NullCompletionCallback(Runnable completionAction) { this.completionAction = completionAction; } @Override public void onCompletion(Packet packet) { if (completionAction != null) { completionAction.run(); } } @Override public void onThrowable(Packet packet, Throwable throwable) { LOGGER.severe(MessageKeys.EXCEPTION, throwable); } } private static class DomainProcessorDelegateImpl implements DomainProcessorDelegate { @Override public String getOperatorNamespace() { return operatorNamespace; } @Override public PodAwaiterStepFactory getPodAwaiterStepFactory(String namespace) { return podWatchers.get(namespace); } @Override public boolean isNamespaceRunning(String namespace) { return !isNamespaceStopping.get(namespace).get(); } @Override public KubernetesVersion getVersion() { return version; } @Override public FiberGate createFiberGate() { return new FiberGate(Main.engine); } @Override public void runSteps(Step firstStep) { Main.runSteps(firstStep); } @Override public ScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit) { return Main.engine.getExecutor().scheduleWithFixedDelay(command, initialDelay, delay, unit); } } }
smgdream/Odyink
install.c
#include <stdio.h> #include <stdlib.h> #include "include/def.h" #include "include/format.h" #define SIZE_MED 256 void install(void) { char index[INDEX_LEN]; char logs[SIZE_MED]; // Install Odyink Server printf("Enter to start installation\n"); getchr(); clear(); printf("Instailling Odyink Server...\n"); // Make dir odydata if (OSNUM) system("mkdir odydata\\doc nul 2> nul"); else system("mkdir -p odydata/doc"); fnewout("./odydata/docnum.ini", "1"); fnewout("./odydata/allocid.ini", "0"); sprintf(index, "%s%c", fill("0.Hello Odyink", -(INDEX_LEN -1), '\v'), '\t'); fnewout("./odydata/docindex.ini", index); // It have a space after type fnewout("./odydata/doctype.ini", "0000000 txt\t"); fnewout("./odydata/doc/0.txt", "Hello this is Odyink\n"); faddout("./odydata/doc/0.txt", "\n"); faddout("./odydata/doc/0.txt", "Odyink is make by smgdream & Andyccr\n"); sprintf(logs, "%s (UTC)\t %s\n", timeStr(UTC), "Install Odyink Server"); fnewout("./odydata/odyink.log", logs); printf("\nFinish\n"); genSleep(2); clear(); return; }
LucidSigma/stardust
Stardust/src/system/gpu/GPU.cpp
<reponame>LucidSigma/stardust #include "stardust/system/gpu/GPU.h" #include <glad/glad.h> namespace stardust { namespace system { namespace { GPUInfo gpuInfo{ }; bool hasGPUInfoBeenQueried = false; } [[nodiscard]] const GPUInfo& GetGPUInfo() { if (!hasGPUInfoBeenQueried) { gpuInfo.name = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); gpuInfo.vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR)); gpuInfo.openGLVersionString = reinterpret_cast<const char*>(glGetString(GL_VERSION)); if (!gpuInfo.openGLVersionString.empty()) { const String openGLVersion = string::Split(string::Trim(gpuInfo.openGLVersionString), ' ').front(); gpuInfo.openGLVersion = CreateVersionFromString(openGLVersion); } gpuInfo.glslVersionString = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)); if (!gpuInfo.glslVersionString.empty()) { const String glslVersion = string::Split(string::Trim(gpuInfo.glslVersionString), ' ').front(); gpuInfo.glslVersion = CreateVersionFromString(glslVersion); } GLint maxTextureSizeDimension = 0; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSizeDimension); gpuInfo.maxTextureSize = static_cast<u64>(maxTextureSizeDimension) * static_cast<u64>(maxTextureSizeDimension) * 4ull; hasGPUInfoBeenQueried = true; } return gpuInfo; } } }
fugue/fugue-client
cmd/listEvents.go
<reponame>fugue/fugue-client package cmd import ( "fmt" "github.com/fugue/fugue-client/client/events" "github.com/fugue/fugue-client/format" "github.com/spf13/cobra" ) type listEventsOptions struct { Offset int64 MaxItems int64 RangeFrom int64 RangeTo int64 EventType []string Change []string Remediated []string ResourceType []string Columns []string } type listEventsViewItem struct { EventID string EventType string CreatedAt string ResourceID string ResourceType string Change string OldState string NewState string Error string } // NewListEventsCommand returns a command that lists events in an environment func NewListEventsCommand() *cobra.Command { var opts listEventsOptions cmd := &cobra.Command{ Use: "events [environment_id]", Short: "List environment events", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { client, auth := getClient() params := events.NewListEventsParams() params.EnvironmentID = args[0] if opts.Offset > 0 { params.Offset = &opts.Offset } if opts.MaxItems > 0 { params.MaxItems = &opts.MaxItems } if opts.RangeFrom > 0 { params.RangeFrom = &opts.RangeFrom } if opts.RangeTo > 0 { params.RangeTo = &opts.RangeTo } if len(opts.EventType) > 0 { params.EventType = opts.EventType } if len(opts.Change) > 0 { params.Change = opts.Change } if len(opts.Remediated) > 0 { params.Remediated = opts.Remediated } if len(opts.ResourceType) > 0 { params.ResourceType = opts.ResourceType } resp, err := client.Events.ListEvents(params, auth) CheckErr(err) events := resp.Payload.Items empty := "-" rows := make([]interface{}, len(events)) for i, event := range events { item := listEventsViewItem{ EventID: event.ID, EventType: event.EventType, CreatedAt: format.Unix(event.CreatedAt), Error: event.Error, ResourceID: empty, ResourceType: empty, OldState: empty, NewState: empty, Change: empty, } if event.ComplianceDiff != nil { diff := event.ComplianceDiff item.ResourceID = diff.ResourceID item.ResourceType = diff.ResourceType item.OldState = diff.OldState item.NewState = diff.NewState // This will happen when a resource type is "UNKNOWN" if item.ResourceID == "" { item.ResourceID = empty } } if event.ResourceDiff != nil { diff := event.ResourceDiff item.ResourceID = diff.ResourceID item.ResourceType = diff.ResourceType item.Change = diff.Change } // Resource IDs can be extremely long. // Truncate at a max length for now. idLen := len(item.ResourceID) if idLen > 50 { item.ResourceID = "..." + item.ResourceID[idLen-50:] } rows[i] = item } table, err := format.Table(format.TableOpts{ Rows: rows, Columns: opts.Columns, ShowHeader: true, }) CheckErr(err) for _, tableRow := range table { fmt.Println(tableRow) } }, } defaultCols := []string{ // "EventID", "EventType", "CreatedAt", "ResourceID", "ResourceType", "Change", "OldState", "NewState", } cmd.Flags().Int64Var(&opts.Offset, "offset", 0, "Offset") cmd.Flags().Int64Var(&opts.MaxItems, "max-items", 20, "Max items") cmd.Flags().Int64Var(&opts.RangeFrom, "range-from", 0, "Range from") cmd.Flags().Int64Var(&opts.RangeTo, "range-to", 0, "Range to") cmd.Flags().StringSliceVar(&opts.EventType, "event-type", nil, "Event types") cmd.Flags().StringSliceVar(&opts.Change, "change", nil, "Change") cmd.Flags().StringSliceVar(&opts.Remediated, "remediated", nil, "Remediated") cmd.Flags().StringSliceVar(&opts.ResourceType, "resource-type", nil, "Resource types") cmd.Flags().StringSliceVar(&opts.Columns, "columns", defaultCols, "columns to show") return cmd } func init() { listCmd.AddCommand(NewListEventsCommand()) }
muthukumaravel7/armnn
Documentation/navtreeindex29.js
var NAVTREEINDEX29 = { "_types_8hpp.xhtml#a1cfaa710db2a54673b21d2ea2da757c8afb278fa5defd7e699fcbc930c3e76ccd":[8,0,0,0,28,26,4], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58c":[8,0,0,0,28,16], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58ca19bb0af2c3c530538cb41aff7f235b96":[8,0,0,0,28,16,5], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58ca1cfdf0e8d0c87a228c1f40d9bee7888b":[8,0,0,0,28,16,3], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58ca6f2f0aefb3d22da0f3839453add5f937":[8,0,0,0,28,16,2], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58ca8768a6821cd735aea4f5b0df88c1fc6a":[8,0,0,0,28,16,1], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58caa4cbdbb6070a5abb35fc95ecf1e22c14":[8,0,0,0,28,16,4], "_types_8hpp.xhtml#a2d299363c9fc33334c571fa29ca4f58caf5f286e73bda105e538310b3190f75c5":[8,0,0,0,28,16,0], "_types_8hpp.xhtml#a3888429b6ebc79f9a7df549e5e4d9a2f":[8,0,0,0,28,22], "_types_8hpp.xhtml#a3888429b6ebc79f9a7df549e5e4d9a2fa843f2812f595e7ec7c5036e89fde02d6":[8,0,0,0,28,22,1], "_types_8hpp.xhtml#a3888429b6ebc79f9a7df549e5e4d9a2faad301514192636ad34210adce598a45a":[8,0,0,0,28,22,0], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9ea":[8,0,0,0,28,14], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa0877e5b3fbe9d7569df6399609ed0186":[8,0,0,0,28,14,11], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa1e34af023adeb7d5f484f8eb4b9826b6":[8,0,0,0,28,14,7], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa21eebb164e4b8b9bcf64fdb4d8d5dff4":[8,0,0,0,28,14,0], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa23b68da1de2b77d74da9da2635722a3e":[8,0,0,0,28,14,1], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa32a843da6ea40ab3b17a3421ccdf671b":[8,0,0,0,28,14,2], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa3d90c0a5ab3fcf8e6f6608cb3d3a1559":[8,0,0,0,28,14,3], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaa6bba7052636d1740303b1b2ef3b53fef":[8,0,0,0,28,14,5], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaaae77f3ad25595e35b327334d89410054":[8,0,0,0,28,14,8], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaabc5a0f0d6e7cf7fca73299dcd46c0f0d":[8,0,0,0,28,14,4], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaacb7667f5ec2f6e8a5943b781ba6c2735":[8,0,0,0,28,14,6], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaaceb46ca115d05c51aa5a16a8867c3304":[8,0,0,0,28,14,9], "_types_8hpp.xhtml#a56297e0f7b215eea46c818cb7528d9eaaed67cf7d54c570e4c4891800f085f41d":[8,0,0,0,28,14,10], "_types_8hpp.xhtml#a5a665483e56a688e9f8180accdf72d80":[8,0,0,0,28,11], "_types_8hpp.xhtml#a602ddc6408c3347ba4c1eba623003984":[8,0,0,0,28,27], "_types_8hpp.xhtml#a67a0db04d321a74b7e7fcfd3f1a3f70b":[8,0,0,0,28,25], "_types_8hpp.xhtml#a67a0db04d321a74b7e7fcfd3f1a3f70ba505a83f220c02df2f85c3810cd9ceb38":[8,0,0,0,28,25,0], "_types_8hpp.xhtml#a67a0db04d321a74b7e7fcfd3f1a3f70bae139a585510a502bbf1841cf589f5086":[8,0,0,0,28,25,1], "_types_8hpp.xhtml#a961bbfe1db71a848eff5a1f0ab775718":[8,0,0,0,28,23], "_types_8hpp.xhtml#a961bbfe1db71a848eff5a1f0ab775718a6a061313d22e51e0f25b7cd4dc065233":[8,0,0,0,28,23,0], "_types_8hpp.xhtml#a961bbfe1db71a848eff5a1f0ab775718a7e6aa2d53f6ee2b1a34b017fa403cb76":[8,0,0,0,28,23,2], "_types_8hpp.xhtml#a961bbfe1db71a848eff5a1f0ab775718ab1897515d548a960afe49ecf66a29021":[8,0,0,0,28,23,1], "_types_8hpp.xhtml#a9a2af2f8c4af4f9efa8e79417d505ac4":[8,0,0,0,28,24], "_types_8hpp.xhtml#a9a2af2f8c4af4f9efa8e79417d505ac4aaa020331bb30d2fa2ecf7c3a0777823f":[8,0,0,0,28,24,1], "_types_8hpp.xhtml#a9a2af2f8c4af4f9efa8e79417d505ac4aaf17c98bbd83c27d6426d2ff3fa81d7f":[8,0,0,0,28,24,0], "_types_8hpp.xhtml#ab8cf8f9fb6792e654c2d8d8382f6f01b":[8,0,0,0,28,12], "_types_8hpp.xhtml#abdcd184ed3bd648bb31d385040cafd5d":[8,0,0,0,28,28], "_types_8hpp.xhtml#abe18a5033f2ab9c0de82c676b48f5437":[8,0,0,0,28,19], "_types_8hpp.xhtml#abe18a5033f2ab9c0de82c676b48f5437a37bac6dce4f46277d89bfa3003e2e39b":[8,0,0,0,28,19,1], "_types_8hpp.xhtml#abe18a5033f2ab9c0de82c676b48f5437a810f43f3996922151c39b76143faeecc":[8,0,0,0,28,19,0], "_types_8hpp.xhtml#ad1d5cce2d9e9a5d61c243e5c989112e0":[8,0,0,0,28,17], "_types_8hpp.xhtml#ad1d5cce2d9e9a5d61c243e5c989112e0a6b99f356fe3b30a2a850b5ea897c289f":[8,0,0,0,28,17,0], "_types_8hpp.xhtml#ad1d5cce2d9e9a5d61c243e5c989112e0ad066db54b89b0912e7e7c6da51e2da51":[8,0,0,0,28,17,1], "_types_8hpp.xhtml#ad605d1661fa0d8c7fea651d82fbe11c9":[8,0,0,0,28,20], "_types_8hpp.xhtml#ad605d1661fa0d8c7fea651d82fbe11c9aa94d2fcabc6b001015aeddfa19266e6f":[8,0,0,0,28,20,1], "_types_8hpp.xhtml#ad605d1661fa0d8c7fea651d82fbe11c9ac65d2e51c610dd3853a3c777aa8bfe9d":[8,0,0,0,28,20,0], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6":[8,0,0,0,28,18], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a053c769dcf82d66ef326c86980c02ba7":[8,0,0,0,28,18,5], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a09238d8d078e53edec6700d0f74ce91c":[8,0,0,0,28,18,10], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a0a3f57c876f5a230244c38e1453a8a6e":[8,0,0,0,28,18,2], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a166495adc0d0f53bee6baecc577f5204":[8,0,0,0,28,18,1], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a26e6ed77470c6f2f830ecf874e6c0d55":[8,0,0,0,28,18,0], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a27226c864bac7454a8504f8edb15d95b":[8,0,0,0,28,18,4], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a34346ec9593088efe3a29c0dad92166d":[8,0,0,0,28,18,6], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a80292d3a80d2993040e48c32b7fa7f82":[8,0,0,0,28,18,11], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a9945327825b115e93a3b89f4302e76db":[8,0,0,0,28,18,7], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6a9d02ea768c081d4bdb2b7cab0b3f510d":[8,0,0,0,28,18,8], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6accedffbc6e5308e33d3843e8bdc0dad7":[8,0,0,0,28,18,3], "_types_8hpp.xhtml#ad8ed01ff3ff33333d8e19db4d2818bb6acdb56b2d2f73c26480207524f2dbe0af":[8,0,0,0,28,18,9], "_types_8hpp.xhtml#adf2e5515c4c36a3e7e46bb8b83c6754e":[8,0,0,0,28,21], "_types_8hpp.xhtml#adf2e5515c4c36a3e7e46bb8b83c6754ea3237fbc8204064c106cb9080088a17cb":[8,0,0,0,28,21,1], "_types_8hpp.xhtml#adf2e5515c4c36a3e7e46bb8b83c6754eaf3f6d0343d56ce88ce7958170ed05cb3":[8,0,0,0,28,21,0], "_types_8hpp.xhtml#ae18caa7ee6287aa7f8c2a5ce6bc92382":[8,0,0,0,28,10], "_types_8hpp.xhtml#ae7e8cbf71db6a490789ca6dcaa8deeae":[8,0,0,0,28,15], "_types_8hpp.xhtml#ae7e8cbf71db6a490789ca6dcaa8deeaea6a061313d22e51e0f25b7cd4dc065233":[8,0,0,0,28,15,1], "_types_8hpp.xhtml#ae7e8cbf71db6a490789ca6dcaa8deeaea78d811e98514cd165dda532286610fd2":[8,0,0,0,28,15,0], "_types_8hpp.xhtml#afad4088a9a058114ee5f87246f87bf49":[8,0,0,0,28,13], "_types_8hpp_source.xhtml":[8,0,0,0,28], "_types_utils_8cpp.xhtml":[8,0,1,0,70], "_types_utils_8cpp_source.xhtml":[8,0,1,0,70], "_types_utils_8hpp.xhtml":[8,0,0,0,29], "_types_utils_8hpp.xhtml#a129bde68152f5892e6abdedcb62aa983":[8,0,0,0,29,11], "_types_utils_8hpp.xhtml#a19a90c41ca2f46ab29918fef1a6ad72e":[8,0,0,0,29,14], "_types_utils_8hpp.xhtml#a517314c21ac5309b90408da162212f9d":[8,0,0,0,29,12], "_types_utils_8hpp.xhtml#a5cda3502382f06a64c3cbeb1829bd850":[8,0,0,0,29,3], "_types_utils_8hpp.xhtml#a637fea04314a9870c1dc4355c1bed429":[8,0,0,0,29,23], "_types_utils_8hpp.xhtml#a65645fa03bf8cddfb9d8a9f83beeb6e8":[8,0,0,0,29,21], "_types_utils_8hpp.xhtml#a67d7ce2e14ebd328f423322db88279c3":[8,0,0,0,29,10], "_types_utils_8hpp.xhtml#a6dac966f265381903c8ef4f392becced":[8,0,0,0,29,15], "_types_utils_8hpp.xhtml#a81b5ff8545adad19a1c9d4ca076d552c":[8,0,0,0,29,6], "_types_utils_8hpp.xhtml#a855293b1be0581fb61ef6a1c5b027d0f":[8,0,0,0,29,1], "_types_utils_8hpp.xhtml#a9667bea652e3a5ef81fea59b71513ced":[8,0,0,0,29,24], "_types_utils_8hpp.xhtml#aa02b9e06fb20fa3c13da0427e6ee5ab2":[8,0,0,0,29,7], "_types_utils_8hpp.xhtml#aa093207ea7c4e7a9c9abe40d2f57995b":[8,0,0,0,29,2], "_types_utils_8hpp.xhtml#aa172264d7075abf828e0b6894996a561":[8,0,0,0,29,18], "_types_utils_8hpp.xhtml#aa6d7532e14af97577c054f96d0cf23b3":[8,0,0,0,29,20], "_types_utils_8hpp.xhtml#aaa5b68f3f5bb73b1d3c85d895547a372":[8,0,0,0,29,19], "_types_utils_8hpp.xhtml#aabb76a77e95921785f576bb29b495cd8":[8,0,0,0,29,4], "_types_utils_8hpp.xhtml#ad44c007f21af2d0375e3ef9400a1b275":[8,0,0,0,29,17], "_types_utils_8hpp.xhtml#ad57460ea53cd0b519a3b3547eaf1db7c":[8,0,0,0,29,9], "_types_utils_8hpp.xhtml#ad773a034fb9983e15f3094b4c5c7c30c":[8,0,0,0,29,22], "_types_utils_8hpp.xhtml#ad91bc7bfe29186f5d78c28386c6c5309":[8,0,0,0,29,16], "_types_utils_8hpp.xhtml#aded981a42027bd3302b9c0f09d988659":[8,0,0,0,29,13], "_types_utils_8hpp.xhtml#aeadd602e128a2be97161345b48533417":[8,0,0,0,29,8], "_types_utils_8hpp.xhtml#aeef70b7611ae71e97ab55c75ef72b210":[8,0,0,0,29,5], "_types_utils_8hpp_source.xhtml":[8,0,0,0,29], "_unit_tests_8cpp.xhtml":[8,0,1,0,2,40], "_unit_tests_8cpp.xhtml#a12aa278dd0bf585d562659e2b2e74014":[8,0,1,0,2,40,2], "_unit_tests_8cpp.xhtml#a6b2a3852db8bb19ab6909bac01859985":[8,0,1,0,2,40,0], "_unit_tests_8cpp.xhtml#ad57096af99f473aca7909812a744b619":[8,0,1,0,2,40,1], "_unit_tests_8cpp_source.xhtml":[8,0,1,0,2,40], "_unit_tests_8hpp.xhtml":[8,0,1,0,2,41], "_unit_tests_8hpp.xhtml#a07e04849fc0700facf91fecce71ff733":[8,0,1,0,2,41,1], "_unit_tests_8hpp.xhtml#a10075eca890bd829a87b914c5aa18cb3":[8,0,1,0,2,41,8], "_unit_tests_8hpp.xhtml#a2d8f71b48349370e1d5c0a9b39e3d162":[8,0,1,0,2,41,4], "_unit_tests_8hpp.xhtml#a44ea827d997f1aa0e39d9a6d6675465c":[8,0,1,0,2,41,3], "_unit_tests_8hpp.xhtml#a8d26216e495ef45a749c03e6c6edcd38":[8,0,1,0,2,41,6], "_unit_tests_8hpp.xhtml#acbe506e0365feeed352effe52b1e4852":[8,0,1,0,2,41,5], "_unit_tests_8hpp.xhtml#ae6ce9102495fab6e3957f61281238e3d":[8,0,1,0,2,41,0], "_unit_tests_8hpp.xhtml#af2016edd458865d471fe1afc82b3c126":[8,0,1,0,2,41,2], "_unit_tests_8hpp.xhtml#af9e4dd62da9266a1364032ada0267f9b":[8,0,1,0,2,41,7], "_unit_tests_8hpp_source.xhtml":[8,0,1,0,2,41], "_unpack_8cpp.xhtml":[8,0,1,7,0,41], "_unpack_8cpp.xhtml#a2bf252e254de91808dda3cdae88c95d8":[8,0,1,7,0,41,2], "_unpack_8cpp.xhtml#a4823ef9c632e83baeca19ebe0668cd62":[8,0,1,7,0,41,1], "_unpack_8cpp.xhtml#a68d5a6350d517e88a7bedda2bd2d9a9e":[8,0,1,7,0,41,3], "_unpack_8cpp.xhtml#ad821cd9a1a9f4f9404d2ec0dcd9e33e3":[8,0,1,7,0,41,0], "_unpack_8cpp_source.xhtml":[8,0,1,7,0,41], "_unsupported_8cpp.xhtml":[8,0,1,7,0,42], "_unsupported_8cpp.xhtml#aa79dc79c1094831a55a21fbb8d4c12f5":[8,0,1,7,0,42,1], "_unsupported_8cpp.xhtml#aae7fa857598a8590c2efe13832774dc9":[8,0,1,7,0,42,0], "_unsupported_8cpp_source.xhtml":[8,0,1,7,0,42], "_utility_tests_8cpp.xhtml":[8,0,1,0,2,42], "_utility_tests_8cpp.xhtml#a399b20063c50329f7f7078d26e9cac4e":[8,0,1,0,2,42,0], "_utility_tests_8cpp.xhtml#a72ca2244ed7dc1b3ffde2ac0ced73b03":[8,0,1,0,2,42,2], "_utility_tests_8cpp.xhtml#a96c31e87cba45ea455f33fd0d86d6222":[8,0,1,0,2,42,3], "_utility_tests_8cpp.xhtml#a9c8843f2e977396dc97773ea9e7f0591":[8,0,1,0,2,42,1], "_utility_tests_8cpp_source.xhtml":[8,0,1,0,2,42], "_utils_8cpp.xhtml":[8,0,1,0,71], "_utils_8cpp.xhtml#aa59f7a819c3e29d10ffc41e5c0616872":[8,0,1,0,71,0], "_utils_8cpp_source.xhtml":[8,0,1,0,71], "_utils_8hpp.xhtml":[8,0,0,0,30], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3d":[8,0,0,0,30,1], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3da0eaadb4fcb48a0a0ed7bc9868be9fbaa":[8,0,0,0,30,1,3], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3da4059b0251f66a18cb56f544728796875":[8,0,0,0,30,1,2], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3da882384ec38ce8d9582b57e70861730e4":[8,0,0,0,30,1,5], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3da902b0d55fddef6f8d651fe1035b7d4bd":[8,0,0,0,30,1,4], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3daa603905470e2a5b8c13e96b579ef0dba":[8,0,0,0,30,1,1], "_utils_8hpp.xhtml#a93a3ba385cad27c4774e5fe64c025d3dadd4ec0ac4e58f7c32a01244ae91150b1":[8,0,0,0,30,1,0], "_utils_8hpp.xhtml#aa59f7a819c3e29d10ffc41e5c0616872":[8,0,0,0,30,2], "_utils_8hpp.xhtml#abbf421eb1186af0d505648ed2ea54a00":[8,0,0,0,30,0], "_utils_8hpp_source.xhtml":[8,0,0,0,30], "_utils_tests_8cpp.xhtml":[8,0,1,0,2,43], "_utils_tests_8cpp.xhtml#a0814ade1be7f4cf228342249e1cbe71b":[8,0,1,0,2,43,6], "_utils_tests_8cpp.xhtml#a1fe602be9a83fee8fb54eca4ca3ba4aa":[8,0,1,0,2,43,13], "_utils_tests_8cpp.xhtml#a3318a36fdb980622f80f76c95740018e":[8,0,1,0,2,43,0], "_utils_tests_8cpp.xhtml#a4177a0297cc117d1a0e9a5df023b911b":[8,0,1,0,2,43,2], "_utils_tests_8cpp.xhtml#a4c9f4af80112cd2651e31259b6d04157":[8,0,1,0,2,43,5], "_utils_tests_8cpp.xhtml#a51f0d67c2d9f5ca83782f23ef88f1b37":[8,0,1,0,2,43,8], "_utils_tests_8cpp.xhtml#a8b7ed18ec6dc4024e2d25e7624f96d59":[8,0,1,0,2,43,10], "_utils_tests_8cpp.xhtml#a94028e60dc9c94d940323cdb441e319c":[8,0,1,0,2,43,14], "_utils_tests_8cpp.xhtml#a97af3b0f5dd1bce84bee01f9508c42eb":[8,0,1,0,2,43,3], "_utils_tests_8cpp.xhtml#aab6bce9938905a82526bb7a33b89e91f":[8,0,1,0,2,43,4], "_utils_tests_8cpp.xhtml#abe41ea63168a5418b26c9f7fff0b27ce":[8,0,1,0,2,43,7], "_utils_tests_8cpp.xhtml#ac1e7309c6fe82de2dad673bd952eafcf":[8,0,1,0,2,43,12], "_utils_tests_8cpp.xhtml#ac5b40dacd8c5c14e92816a14cef9df3c":[8,0,1,0,2,43,1], "_utils_tests_8cpp.xhtml#af648055c5cc8f1005ea5c585eda9ca4b":[8,0,1,0,2,43,11], "_utils_tests_8cpp.xhtml#afc5e3f247107aada6cd4bfbc0d3d31d5":[8,0,1,0,2,43,9], "_utils_tests_8cpp_source.xhtml":[8,0,1,0,2,43], "_verification_helpers_8cpp.xhtml":[8,0,1,9,32], "_verification_helpers_8cpp.xhtml#a2e0aa273755368a1bf5fc65102df4a92":[8,0,1,9,32,2], "_verification_helpers_8cpp.xhtml#a97dc68ae76f04b81c833184724836c9a":[8,0,1,9,32,0], "_verification_helpers_8cpp.xhtml#ab075020544612cd151ebdd08db537396":[8,0,1,9,32,1], "_verification_helpers_8cpp_source.xhtml":[8,0,1,9,32], "_verification_helpers_8hpp.xhtml":[8,0,1,9,33], "_verification_helpers_8hpp.xhtml#a2e0aa273755368a1bf5fc65102df4a92":[8,0,1,9,33,5], "_verification_helpers_8hpp.xhtml#a479b2821a7a2cbb8fa8eb7f60a47065d":[8,0,1,9,33,0], "_verification_helpers_8hpp.xhtml#a97dc68ae76f04b81c833184724836c9a":[8,0,1,9,33,3], "_verification_helpers_8hpp.xhtml#aa693ef8620e450b6362938828002f2a6":[8,0,1,9,33,1], "_verification_helpers_8hpp.xhtml#aaef93dc9a69f51b59f3cdd0ff0165927":[8,0,1,9,33,2], "_verification_helpers_8hpp.xhtml#ab075020544612cd151ebdd08db537396":[8,0,1,9,33,4], "_verification_helpers_8hpp_source.xhtml":[8,0,1,9,33], "_version_8hpp.xhtml":[8,0,0,0,31], "_version_8hpp.xhtml#a16c0008e2647e2f123165ce5cf18a6fa":[8,0,0,0,31,0], "_version_8hpp.xhtml#a50bf0553d5c4b76d18a3d37e155b4d11":[8,0,0,0,31,3], "_version_8hpp.xhtml#a50c973b64012b42df2cd1e602dacc0e0":[8,0,0,0,31,7], "_version_8hpp.xhtml#a5412c36de79475c72f82d58e9cdcc816":[8,0,0,0,31,2], "_version_8hpp.xhtml#a54ae039762f10d070d43551bcb9b4458":[8,0,0,0,31,4], "_version_8hpp.xhtml#a6bc878927f8aa6be563c0c5949eec3b8":[8,0,0,0,31,6], "_version_8hpp.xhtml#ad26f5c26e73f264b0e343babd0bb5d37":[8,0,0,0,31,1], "_version_8hpp.xhtml#adda6509fa8f842f59ba79624632e936d":[8,0,0,0,31,5], "_version_8hpp_source.xhtml":[8,0,0,0,31], "_wall_clock_timer_8cpp.xhtml":[8,0,1,0,72], "_wall_clock_timer_8cpp_source.xhtml":[8,0,1,0,72], "_wall_clock_timer_8hpp.xhtml":[8,0,1,0,73], "_wall_clock_timer_8hpp.xhtml#ae7adfc4258f7ff8ba7d8c3f7c9372a3f":[8,0,1,0,73,1], "_wall_clock_timer_8hpp_source.xhtml":[8,0,1,0,73], "_workload_8hpp.xhtml":[8,0,1,10,1,29], "_workload_8hpp.xhtml#a0493144f15b35804a133c9aa0b63fcc9":[8,0,1,10,1,29,10], "_workload_8hpp.xhtml#a20d2055c37fedf3f39db9facf2c8c697":[8,0,1,10,1,29,5], "_workload_8hpp.xhtml#a3e4b88b993c90b274e0bd268c35d798e":[8,0,1,10,1,29,12], "_workload_8hpp.xhtml#a6486138451112140f98516c0bee18615":[8,0,1,10,1,29,9], "_workload_8hpp.xhtml#a6d4fbf927a9d8e68cab1d7965c7dbc44":[8,0,1,10,1,29,13], "_workload_8hpp.xhtml#a827d59b5a779a8089017802172817f3c":[8,0,1,10,1,29,8], "_workload_8hpp.xhtml#a9cbc0957cf0637cc3fd9702086117cc0":[8,0,1,10,1,29,6], "_workload_8hpp.xhtml#ab539ef5a0c152536da71c8fcc065efb5":[8,0,1,10,1,29,7], "_workload_8hpp.xhtml#abaedcfd0ae08790c03bfe8ba7586dd84":[8,0,1,10,1,29,11], "_workload_8hpp.xhtml#ad4d53881107428c301d43b5aad16bfe0":[8,0,1,10,1,29,14], "_workload_8hpp_source.xhtml":[8,0,1,10,1,29], "_workload_data_8cpp.xhtml":[8,0,1,10,1,30], "_workload_data_8cpp.xhtml#a872803f5667392efc3c8e5607bd453ad":[8,0,1,10,1,30,0], "_workload_data_8cpp_source.xhtml":[8,0,1,10,1,30], "_workload_data_8hpp.xhtml":[8,0,1,10,1,31], "_workload_data_8hpp.xhtml#a2231ac018fe2c465f2d42fef597d67e7":[8,0,1,10,1,31,64], "_workload_data_8hpp.xhtml#a308ba160745ba35e1de8d698d0139eb4":[8,0,1,10,1,31,65], "_workload_data_8hpp.xhtml#a37a1a6b381ccc76df203fee023234996":[8,0,1,10,1,31,66], "_workload_data_8hpp.xhtml#a872803f5667392efc3c8e5607bd453ad":[8,0,1,10,1,31,67], "_workload_data_8hpp_source.xhtml":[8,0,1,10,1,31], "_workload_data_collector_8hpp.xhtml":[8,0,1,10,1,32], "_workload_data_collector_8hpp_source.xhtml":[8,0,1,10,1,32], "_workload_data_validation_8cpp.xhtml":[8,0,1,10,1,0,52], "_workload_data_validation_8cpp.xhtml#a12def4fb1722495397eaf309cb8ef712":[8,0,1,10,1,0,52,2], "_workload_data_validation_8cpp.xhtml#a1877eca1aa5adb4c0e1302d04c96d013":[8,0,1,10,1,0,52,11], "_workload_data_validation_8cpp.xhtml#a198e5f41a13facee99cf14390282e186":[8,0,1,10,1,0,52,7], "_workload_data_validation_8cpp.xhtml#a1a76fe496d4e2ee0b0893a36736ae288":[8,0,1,10,1,0,52,4], "_workload_data_validation_8cpp.xhtml#a30f72f6909ab012842e16398984c77c0":[8,0,1,10,1,0,52,1], "_workload_data_validation_8cpp.xhtml#a454c029687438437ea707b94f88361e1":[8,0,1,10,1,0,52,6], "_workload_data_validation_8cpp.xhtml#a5133fd5b53fab2340f3655d9cb27e6c1":[8,0,1,10,1,0,52,5], "_workload_data_validation_8cpp.xhtml#a5e734b459a947759e3ca5f76e2f278f2":[8,0,1,10,1,0,52,0], "_workload_data_validation_8cpp.xhtml#a5f1870bd33bf34b70b985e24da85700f":[8,0,1,10,1,0,52,8], "_workload_data_validation_8cpp.xhtml#a77921e834125a4a2d63142cb8ac115f6":[8,0,1,10,1,0,52,9], "_workload_data_validation_8cpp.xhtml#abf20db1f5c57d502fe310198a9264b7c":[8,0,1,10,1,0,52,10], "_workload_data_validation_8cpp.xhtml#ad3a7db97268896c1bfa8df01f5834b3f":[8,0,1,10,1,0,52,12], "_workload_data_validation_8cpp.xhtml#adbdb7da153a5596e84d312e8abbd152d":[8,0,1,10,1,0,52,13], "_workload_data_validation_8cpp.xhtml#ae59870717f9ac828ab0bf3bc6804bfec":[8,0,1,10,1,0,52,3], "_workload_data_validation_8cpp_source.xhtml":[8,0,1,10,1,0,52], "_workload_factory_8cpp.xhtml":[8,0,1,10,1,33], "_workload_factory_8cpp_source.xhtml":[8,0,1,10,1,33], "_workload_factory_8hpp.xhtml":[8,0,1,10,1,34], "_workload_factory_8hpp_source.xhtml":[8,0,1,10,1,34], "_workload_factory_base_8hpp.xhtml":[8,0,1,10,1,35], "_workload_factory_base_8hpp_source.xhtml":[8,0,1,10,1,35], "_workload_factory_helper_8hpp.xhtml":[8,0,1,10,1,0,53], "_workload_factory_helper_8hpp_source.xhtml":[8,0,1,10,1,0,53], "_workload_test_utils_8hpp.xhtml":[8,0,1,10,1,0,54], "_workload_test_utils_8hpp_source.xhtml":[8,0,1,10,1,0,54], "_workload_utils_8cpp.xhtml":[8,0,1,10,1,37], "_workload_utils_8cpp.xhtml#a1e8288eac7e909fdb58b6113d816763a":[8,0,1,10,1,37,2], "_workload_utils_8cpp.xhtml#a2a9ac8ebb69307ad4ec894ffa0523dbf":[8,0,1,10,1,37,3], "_workload_utils_8cpp.xhtml#a3170fdd696155a247ecd81d445c0e2e1":[8,0,1,10,1,37,5], "_workload_utils_8cpp.xhtml#a51e8b95a429e11678ffa8b9fdc88351b":[8,0,1,10,1,37,1], "_workload_utils_8cpp.xhtml#a52b301fd3adce20b51c4482cb52f1a38":[8,0,1,10,1,37,4], "_workload_utils_8cpp.xhtml#ad69ffa576a596b9eb20ab6a41420c541":[8,0,1,10,1,37,0], "_workload_utils_8cpp_source.xhtml":[8,0,1,10,1,37], "_workload_utils_8hpp.xhtml":[8,0,1,10,1,38], "_workload_utils_8hpp.xhtml#a1e8288eac7e909fdb58b6113d816763a":[8,0,1,10,1,38,2], "_workload_utils_8hpp.xhtml#a2a9ac8ebb69307ad4ec894ffa0523dbf":[8,0,1,10,1,38,5], "_workload_utils_8hpp.xhtml#a3170fdd696155a247ecd81d445c0e2e1":[8,0,1,10,1,38,6], "_workload_utils_8hpp.xhtml#a51e8b95a429e11678ffa8b9fdc88351b":[8,0,1,10,1,38,1] };
sintefneodroid/droid
docs/cvs/structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.js
<filename>docs/cvs/structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.js var structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s = [ [ "__assign", "structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.html#af6af8965cf357ba6797f25981e9ff509", null ], [ "__init", "structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.html#a8944d55ca4a2360e62999f98239c568f", null ], [ "Points", "structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.html#a200ba420cc1dbf9461a111d4ea846703", null ], [ "ByteBuffer", "structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.html#a6e73bc899236ec817576c7c81512c88d", null ], [ "PointsLength", "structdroid_1_1_runtime_1_1_messaging_1_1_f_b_s_1_1_f_vector3s.html#a0c258255dc51f24a5a2d0022654bda61", null ] ];
ValentinKalinin1989/job4j
middle_threads/src/main/java/RectangleMove.java
<filename>middle_threads/src/main/java/RectangleMove.java import javafx.scene.shape.Rectangle; public class RectangleMove implements Runnable { private final Rectangle rect; private int x; private int y; public RectangleMove(Rectangle rect, int x, int y) { this.rect = rect; this.x = x; this.y = y; } @Override public void run() { int deltaX = 1; int deltaY = 1; while (!Thread.currentThread().isInterrupted()) { this.rect.setX(this.rect.getX() + deltaX); this.rect.setY(this.rect.getY() + deltaY); if ((rect.getX() >= this.x) || (rect.getX() <= 0)) { deltaX *= -1; } if ((rect.getY() >= this.y) || (rect.getY() <= 0)) { deltaY *= -1; } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } }
hifive/hifive-pitalium
pitalium/src/test/java/com/htmlhifive/pitalium/it/exec/frame/FrameScreenshotTest.java
package com.htmlhifive.pitalium.it.exec.frame; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import com.htmlhifive.pitalium.image.util.ImageUtils; import org.junit.Before; import org.junit.Test; import com.htmlhifive.pitalium.core.PtlTestBase; import com.htmlhifive.pitalium.core.io.PersistMetadata; import com.htmlhifive.pitalium.core.model.ScreenshotArgument; import com.htmlhifive.pitalium.core.model.SelectorType; import com.htmlhifive.pitalium.core.model.TargetResult; import com.htmlhifive.pitalium.core.result.TestResultManager; import com.htmlhifive.pitalium.image.model.RectangleArea; import java.awt.Color; import java.awt.image.BufferedImage; public class FrameScreenshotTest extends PtlTestBase { // TODO appiumで画像サイズどうなるのか。同じだったらいいなぁ、、 private TargetResult loadResult(String methodName, String screenshotId) { try { TestResultManager resultManager = TestResultManager.getInstance(); String expectedId = resultManager.getCurrentId(); PersistMetadata metadata = new PersistMetadata(expectedId, getClass().getSimpleName(), methodName, screenshotId, capabilities); return resultManager.getPersister().loadTargetResults(metadata).get(0); } catch (Exception e) { fail("TestResult JSON load error: " + e.getMessage()); // never throw new RuntimeException(); } } @Before @Override public void setUp() { super.setUp(); driver.get("iframe/iframe-test.html"); } /** * 通常のキャプチャ */ @Test public void captureDefaultContentBody() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTarget() .moveTarget(false) .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureDefaultContentBody", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getHeight(), is(1000.0)); assertThat(result.getExcludes().size(), is(0)); // widthの大きさは不定 } /** * 通常のキャプチャ */ @Test public void captureDefaultContentBody_move() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTarget() .moveTarget(true) .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureDefaultContentBody_move", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getHeight(), is(1000.0)); assertThat(result.getExcludes().size(), is(0)); // widthの大きさは不定 } /** * 通常のキャプチャ+iframe内の要素を除外指定 */ @Test public void captureDefaultContentBody_withExclude() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTarget() .moveTarget(false) .addExclude(SelectorType.CLASS_NAME, "content-left", SelectorType.CLASS_NAME, "content") .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureDefaultContentBody_withExclude", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getHeight(), is(1000.0)); assertThat(result.getExcludes().size(), is(1)); // iframeの大きさで切り取られているべき RectangleArea excludeRect = result.getExcludes().get(0).getRectangle(); assertThat(excludeRect, is(new RectangleArea(400.0, 300.0, 200.0, 200.0))); } /** * 通常のキャプチャ+iframe内の要素を除外指定 */ @Test public void captureDefaultContentBody_move_withExclude() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTarget() .moveTarget(true) .addExclude(SelectorType.CLASS_NAME, "content-left", SelectorType.CLASS_NAME, "content") .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureDefaultContentBody_move_withExclude", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getHeight(), is(1000.0)); assertThat(result.getExcludes().size(), is(1)); // iframeの大きさで切り取られているべき RectangleArea excludeRect = result.getExcludes().get(0).getRectangle(); assertThat(excludeRect, is(new RectangleArea(400.0, 300.0, 200.0, 200.0))); } /** * iframe全体をキャプチャ */ @Test public void captureFrameBody() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTargetByClassName("content") .moveTarget(false) .scrollTarget(true) .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureFrameBody", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getWidth(), is(300.0)); assertThat(targetRect.getHeight(), is(1004.0)); assertThat(result.getExcludes().size(), is(0)); } /** * iframe全体をキャプチャ+iframe内の要素を除外指定 */ @Test public void captureFrameBody_withExclude() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTargetByClassName("content") .moveTarget(false) .scrollTarget(true) .addExclude(SelectorType.CLASS_NAME, "content-left") .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureFrameBody_withExclude", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getWidth(), is(300.0)); assertThat(targetRect.getHeight(), is(1004.0)); assertThat(result.getExcludes().size(), is(1)); RectangleArea excludeRect = result.getExcludes().get(0).getRectangle(); assertThat(excludeRect, is(new RectangleArea(100.0, 100.0, 200.0, 300.0))); } /** * iframe全体をキャプチャ */ @Test public void captureFrameBody_move() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTargetByClassName("content") .moveTarget(true) .scrollTarget(true) .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureFrameBody_move", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getWidth(), is(300.0)); assertThat(targetRect.getHeight(), is(1004.0)); assertThat(result.getExcludes().size(), is(0)); } /** * iframe全体をキャプチャ+iframe内の要素を除外指定 */ @Test public void captureFrameBody_move_withExclude() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTargetByClassName("content") .moveTarget(true) .scrollTarget(true) .addExclude(SelectorType.CLASS_NAME, "content-left") .build(); // @formatter:on assertionView.assertView(args); // JSONチェック TargetResult result = loadResult("captureFrameBody_move_withExclude", "screenshot"); RectangleArea targetRect = result.getTarget().getRectangle(); assertThat(targetRect.getX(), is(0.0)); assertThat(targetRect.getY(), is(0.0)); assertThat(targetRect.getWidth(), is(300.0)); assertThat(targetRect.getHeight(), is(1004.0)); assertThat(result.getExcludes().size(), is(1)); RectangleArea excludeRect = result.getExcludes().get(0).getRectangle(); assertThat(excludeRect, is(new RectangleArea(100.0, 100.0, 200.0, 300.0))); } /** * 通常のキャプチャ + iframe内hidden */ @Test public void captureDefaultContentBody_hidden() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTarget() .moveTarget(false) .addHiddenElementsByClassName("content-left").inFrameByClassName("content") .build(); // @formatter:on assertionView.assertView(args); // 画像チェック(#795548、#455A64が無いことのチェック) TargetResult result = loadResult("captureDefaultContentBody_hidden", "screenshot"); BufferedImage image = result.getImage().get(); int width = image.getWidth(); int height = image.getHeight(); int[] colors = ImageUtils.getRGB(image, width, height); int color1 = Color.decode("0x795548").getRGB(); int color2 = Color.decode("0x455A64").getRGB(); for (int color : colors) { if (color == color1) { fail("background-color found"); } if (color == color2) { fail("border-color found"); } } } /** * 通常のキャプチャ + iframe内hidden */ @Test public void captureDefaultContentBody_move_hidden() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTarget() .moveTarget(true) .addHiddenElementsByClassName("content-left").inFrameByClassName("content") .build(); // @formatter:on assertionView.assertView(args); // 画像チェック(#795548、#455A64が無いことのチェック) TargetResult result = loadResult("captureDefaultContentBody_move_hidden", "screenshot"); BufferedImage image = result.getImage().get(); int width = image.getWidth(); int height = image.getHeight(); int[] colors = ImageUtils.getRGB(image, width, height); int color1 = Color.decode("0x795548").getRGB(); int color2 = Color.decode("0x455A64").getRGB(); for (int color : colors) { if (color == color1) { fail("background-color found"); } if (color == color2) { fail("border-color found"); } } } /** * iframe全体をキャプチャ + iframe内hidden */ @Test public void captureFrameBody_hidden() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTargetByClassName("content") .moveTarget(false) .scrollTarget(true) .addHiddenElementsByClassName("content-left").inFrameByClassName("content") .build(); // @formatter:on assertionView.assertView(args); // 画像チェック(#795548、#455A64が無いことのチェック) TargetResult result = loadResult("captureFrameBody_hidden", "screenshot"); BufferedImage image = result.getImage().get(); int width = image.getWidth(); int height = image.getHeight(); int[] colors = ImageUtils.getRGB(image, width, height); int color1 = Color.decode("0x795548").getRGB(); int color2 = Color.decode("0x455A64").getRGB(); for (int color : colors) { if (color == color1) { fail("background-color found"); } if (color == color2) { fail("border-color found"); } } } /** * iframe全体をキャプチャ + iframe内hidden */ @Test public void captureFrameBody_move_hidden() throws Exception { // @formatter:off ScreenshotArgument args = ScreenshotArgument.builder("screenshot") .addNewTargetByClassName("content") .moveTarget(true) .scrollTarget(true) .addHiddenElementsByClassName("content-left").inFrameByClassName("content") .build(); // @formatter:on assertionView.assertView(args); // 画像チェック(#795548、#455A64が無いことのチェック) TargetResult result = loadResult("captureFrameBody_move_hidden", "screenshot"); BufferedImage image = result.getImage().get(); int width = image.getWidth(); int height = image.getHeight(); int[] colors = ImageUtils.getRGB(image, width, height); int color1 = Color.decode("0x795548").getRGB(); int color2 = Color.decode("0x455A64").getRGB(); for (int color : colors) { if (color == color1) { fail("background-color found"); } if (color == color2) { fail("border-color found"); } } } }
Tattus/Space-Invadus
Space-Invadus/resourcesManagerus.cpp
/* resourcesManagerus.cpp ---------------------- Créé par : Tattus le : 03/05/2015 Modifié le : 15/05/2015 */ #include "resourcesManagerus.hpp" static C_ResourcesManager *myInstanceRM = NULL; C_ResourcesManager::C_ResourcesManager() { myErrorCode = NO_ERROR; myFileName = ""; myRcContainer = "resources.dat"; myRcPrefix = "rc_"; } C_ResourcesManager::C_ResourcesManager(string rcContainer, string rcPrefix) { myErrorCode = NO_ERROR; myFileName = ""; if (rcContainer.length() > FILENAME_MAX) { myRcContainer = "resources.dat"; myErrorCode = RC_CONTAINER_NAME_TOO_LONG; } else { myRcContainer = rcContainer; } if (rcPrefix.length() > 9) { myRcPrefix = "rc_"; myErrorCode = RC_PREFIX_TOO_LONG; } else { myRcPrefix = rcPrefix; } } C_ResourcesManager::~C_ResourcesManager() { //cout << "Destructor Resource Manager" << endl; } C_ResourcesManager *C_ResourcesManager::getInstance(void) { if (myInstanceRM == NULL) { myInstanceRM = new C_ResourcesManager(); } return myInstanceRM; } C_ResourcesManager *C_ResourcesManager::getInstance(string rcContainer, string rcPrefix) { if (myInstanceRM == NULL) { myInstanceRM = new C_ResourcesManager(rcContainer, rcPrefix); } return myInstanceRM; } void C_ResourcesManager::kill(void) { if (myInstanceRM != NULL) { delete(myInstanceRM); myInstanceRM = NULL; } } bool C_ResourcesManager::setRcContainer(string rcContainer) { bool returnValue = true; if (rcContainer.length() > FILENAME_MAX) { myRcContainer = "resources.dat"; myErrorCode = RC_CONTAINER_NAME_TOO_LONG; returnValue = false; } else { myRcContainer = rcContainer; } return returnValue; } bool C_ResourcesManager::setRcPrefix(string rcPrefix) { bool returnValue = true; if (rcPrefix.length() > 9) { myRcPrefix = "rc_"; myErrorCode = RC_PREFIX_TOO_LONG; returnValue = false; } else { myRcPrefix = rcPrefix; } return returnValue; } void C_ResourcesManager::closeRcFile(void) { struct dirent *ent = NULL; DIR *dir = opendir("."); string fileName = ""; if (dir != NULL) { while ((ent = readdir(dir)) != NULL) { fileName = ent->d_name; if (fileName.compare(0, myRcPrefix.length(), myRcPrefix) == 0) { remove(fileName.c_str()); } } } } void C_ResourcesManager::closeRcFile(string rcFile) { string fileName = ""; fileName = myRcPrefix + rcFile; remove(fileName.c_str()); } int C_ResourcesManager::getErrorCode(void) { return myErrorCode; } //********************************************************************************************************************************** // getRcFile : //**************** // cette fonction prend en arguments : // le nom d'une ressource contenant un fichier,texte ou binaire . par exemple "monfic.txt". // un pointeur sur un int qui sera renvoyé/chargé avec la taille utilisable des données // Elle va créer un fichier temporaire "rc_monfic.txt", puis allouer (malloc) une zone de mémoire équivalente à la taille // du fichier, puis charger le contenu du fichier temporaire dans cette zone de mémoire allouée, + 1 octet pour un 0x00 à la fin. // le fichier temporaire rc_monfichier.txt est immédiatement détruit. // La fonction renvoie le contenu dans un string. //********************************************************************************************************************************** string C_ResourcesManager::getRcFile(string a_pResName) { char *ptrdata; string *tempFileName; string contenu; int taille; FILE *fp; tempFileName = getTempResFile(a_pResName, &taille, NULL); if(!tempFileName) { return ""; } fp = fopen(tempFileName->c_str(), "rb"); if(!fp) { return ""; } ptrdata = (char*)malloc(taille + 1); fread((unsigned char *)ptrdata, taille, 1, fp); ptrdata[taille] = 0x00; fclose(fp); remove(tempFileName->c_str()); contenu = ptrdata; free(ptrdata); return contenu; } #ifdef DEF_RCFMODCORE FMOD_RESULT C_ResourcesManager::FMOD_System_CreateRcSound(FMOD_SYSTEM *a_system, string a_rcname, FMOD_MODE a_mode, FMOD_CREATESOUNDEXINFO *a_finfo, FMOD_SOUND **a_ppsound) { string *tempFileName; FMOD_RESULT result; tempFileName = getTempResFile(a_rcname, NULL, NULL); if (!tempFileName) { return FMOD_ERR_FILE_NOTFOUND; } result = FMOD_System_CreateSound(a_system, tempFileName->c_str(), a_mode, a_finfo, a_ppsound); remove(tempFileName->c_str()); return result; } FMOD_RESULT C_ResourcesManager::FMOD_System_CreateRcSoundNoDel(FMOD_SYSTEM *a_system, string a_rcname, FMOD_MODE a_mode, FMOD_CREATESOUNDEXINFO *a_finfo, FMOD_SOUND **a_ppsound) { string *tempFileName; FMOD_RESULT result; tempFileName = getTempResFile(a_rcname, NULL, NULL); if (!tempFileName) { return FMOD_ERR_FILE_NOTFOUND; } result = FMOD_System_CreateSound(a_system, tempFileName->c_str(), a_mode, a_finfo, a_ppsound); remove(tempFileName->c_str()); return result; } #endif //DEF_RCFMODCORE #ifdef DEF_RCSDL2TTF TTF_Font *C_ResourcesManager::TTF_OpenRcFontNoDel(string a_FontName, int ptsize) { TTF_Font *fontsToReturn; string *tempFileName; tempFileName = getTempResFile(a_FontName, NULL, NULL); if (!tempFileName) { return NULL; } fontsToReturn = TTF_OpenFont(tempFileName->c_str(), ptsize); return fontsToReturn; } #endif // DEF_RCSDL2FONTS #ifdef DEF_RCSDL2IMAGE SDL_Surface *C_ResourcesManager::IMG_RcLoad(string a_ImgName) { SDL_Surface *surfaceToReturn; string *tempFileName; tempFileName = getTempResFile(a_ImgName, NULL, NULL); if (!tempFileName) { return NULL; } surfaceToReturn = IMG_Load(tempFileName->c_str()); remove(tempFileName->c_str()); return surfaceToReturn; } #endif // DEF_RCSDL2IMAGE #ifdef DEF_RCSDL2 SDL_Surface *C_ResourcesManager::LoadRcBitmap(string a_BmpName) { SDL_Surface *surfaceToReturn; string *tempFileName; tempFileName = getTempResFile(a_BmpName, NULL, NULL); if (!tempFileName) { return NULL; } surfaceToReturn = SDL_LoadBMP(tempFileName->c_str()); remove(tempFileName->c_str()); return surfaceToReturn; } #endif // DEF_RCSDL2 //******************************************************************************************************************* // fonction: bIsRcNameFound // objet: va rechercher dans le fichier RC si une ressource existe. // La ressource est connue avec son nom original de fichier, par exemple "monfic.bmp" // Arguments: // FILE *fp : Le fichier de ressources doit être ouvert (fopen déjà effectué) // char *a_pResourceName : Le nom de la ressource à trouver, par exemple "monfic.bmp" // int *a_nRcOffset : Pointeur sur un int. la fonction mettra dedans l'offset dans le fichier de ressources // correspondant aux data de la ressource concernée // int *a_nRcSize : Contiendra la taille de la partie data de la ressource si elle est trouvée // a_nOrder : Le numéro d'ordre de la ressource concernée, commence à zéro //******************************************************************************************************************* int C_ResourcesManager::bIsRcNameFound(FILE *fp, const char *a_pResourceName, int *a_nRcOffset, int *a_nRcSize, int a_nOrder) { int offsetRcStruct; // Contiendra le int qui définit l'offset dans le fichier de ressources pour trouver l'entête de la ressource considérée int resourceSize; // Contendra le nombre d'octets (la taille) de la ressource int resourceNameLength; // Longeur du nom de la ressource sans le zéro final. par exemple, si c'est toto.bmp, contiendra 8 char resourceName[FILENAME_MAX]; //** Buffer qui recevra le nom de la ressource int rc; // Se positionner au début du pointeur d'offset dans le fichier de ressources pour ce N° de ressource // fseek retourne zéro si c'est ok. Sinon je fais un return( 0 ) pour dire que l'on ne l'a pas trouvé //if( fseek( fp, (4+(4*a_nOrder)), SEEK_SET ) ) return( 0 ); rc = fseek(fp, (4 + (4 * a_nOrder)) + 1, SEEK_SET); if (rc != 0) return 0; // Lire le déplacement de cette ressource rc = freadRcCrypted((unsigned char *)&offsetRcStruct, sizeof(int), 1, fp); if (rc != 1) return 0; // Se déplacer au début du nom de cette ressource dans le fichier de ressources rc = fseek(fp, offsetRcStruct, SEEK_SET); if (rc != 0) return 0; // Nous pointons maintenant sur la taille des datas de cette structure. La lire rc = freadRcCrypted( (unsigned char *)&resourceSize, sizeof(int), 1, fp ); if (rc != 1) return 0; // Lire maintenant la taille du nom de cette ressource rc = freadRcCrypted( (unsigned char *)&resourceNameLength, sizeof(int), 1, fp ); if (rc != 1) return 0; if (resourceNameLength >= (int)(FILENAME_MAX - myRcPrefix.length())) return 0; // - strlen(gs_rcTempPrefix) car je vais préfixer avec "gs_rcTempPrefix" en créant le fichier temporaire // Lire maintenant le nom de ectte ressource rc = freadRcCrypted((unsigned char *)resourceName, resourceNameLength, 1, fp); if (rc != 1) return 0; // Mettre un zéro binaire pour terminer le string resourceName[resourceNameLength] = 0x00; // Comparer avec le nom de ressource demandé if (!strcmp(resourceName, a_pResourceName)) { // Oui c'est la bonne ressource // Garder le déplacement sur les data de cette ressource *a_nRcOffset = ftell(fp); *a_nRcSize = resourceSize; return 1; } else { //** Non, le nom ne correspond pas *a_nRcOffset = -1; return 0; } return 1; } //*************************************************************************************************************************************************** // getTempResFile : //******************** // Fonction interne. // Elle va chercher dans le fichier de ressources gs_NomFichierResources et essayer de trouver la ressource dont le nom est dans a_pResName. // Arguments: // a_pResName : Nom de la ressource, par exemple mymage.bmp // a_pnSize : Pointeur sur un int, peut être NULL. Si pas NULL, je mets dedans la taille trouvée pour al ressource // a_pnOffset : Pointeur sur un int, offset de la ressource par rapport au début du fichier de ressources. peut être NULL // // Valeurs de retour : // NULL = Ressource non trouvée // non NULL = Nom du fichier temporaire créé (et chargé et non-ouvert) si la ressource est trouvée //*************************************************************************************************************************************************** string *C_ResourcesManager::getTempResFile(string a_pResName, int *a_pnSize, int *a_pnOffset) { FILE *fp; int nbFilesInRc; int i; int rcOffset; int bFlagRcFound; int rcSize; void *ptrdata; FILE *fpTemp; fp = fopen(myRcContainer.c_str(), "rb"); if (!fp) { myErrorCode = RC_CONTAINER_UNKNOWN; return NULL; } // Lire le 1er octet pour savoir si c'est crypté isCrypted = 0; freadRcCrypted((unsigned char *)&isCrypted, 1, 1, fp); // Combien de ressources dans ce fichier de ressources ? freadRcCrypted((unsigned char *)&nbFilesInRc, sizeof(int), 1, fp); // Si pas de fichiers, RC_FILE_EMPTY if (!nbFilesInRc) { fclose(fp); myErrorCode = RC_CONTAINER_EMPTY; return NULL; } // Balayer les noms des ressources bFlagRcFound = 0; for (i = 0 ; i < nbFilesInRc ; i++) { if (bIsRcNameFound(fp, a_pResName.c_str(), &rcOffset, &rcSize, i)) { bFlagRcFound = 1; if(a_pnSize) { *a_pnSize = rcSize; } if(a_pnOffset) { *a_pnOffset = rcOffset; } break; } } if (!bFlagRcFound) { fclose(fp); myErrorCode = RC_FILE_NOT_FOUND; return NULL; } // Ici la ressource a été trouvée, rcOffset est le déplacement dans le fichier de ressources des data de la ressource cherchée // En attendant de faire mieux, je vais créer un fichier temporaire pour cette ressource, la charger, puis effacer le fichier myFileName = myRcPrefix + a_pResName; fpTemp = fopen(myFileName.c_str(), "w+b"); ptrdata = malloc(rcSize); freadRcCrypted((unsigned char *)ptrdata, rcSize, 1, fp); fwrite(ptrdata, rcSize, 1, fpTemp); fclose(fpTemp); fclose(fp); free(ptrdata); return &myFileName; } int C_ResourcesManager::freadRcCrypted(unsigned char *a_buffer, int a_size, int a_nbElem, FILE *a_fp) { int i; unsigned char temp; unsigned char l_cX; int crypted; int rc; crypted = isCrypted; rc = fread((void *)a_buffer, a_size, a_nbElem, a_fp); if (crypted > 0) { for (i = 0 ; i < (a_size * a_nbElem) ; i++) { l_cX = a_buffer[i]<<6; temp = a_buffer[i]>>2; a_buffer[i] = l_cX | temp; } } return rc; }
batchblue/chiketto
lib/chiketto/ticket_class.rb
<reponame>batchblue/chiketto module Chiketto class TicketClass < Resource attr_accessor :name, :cost, :fee, :currency, :free, :minimum_quantity, :maximum_quantity, :quantity_total, :quantity_sold attr_date :sales_start, :sales_end end end
rayoack/yeep-mobile
App/Services/api.js
import axios from 'axios' import BaseURL from '../Config/BaseURL' // import { store } from '../redux/store' export const API = { getUriForProvider(provider) { switch (provider) { case 'facebook': return `${BaseURL.api}/auth/facebook` case 'google': return `${BaseURL.api}/auth/google_oauth2` case 'apple': return `${BaseURL.api}/auth/apple` default: return null } }, extractAccessTokenHeaders(headers) { return { 'access-token': headers['access-token'], 'client': headers.client, 'uid': headers.uid, 'expiry': headers.expiry, 'token-type': 'Bearer' } }, extractAccessTokenFromUser(user) { return { 'access-token': user.auth_token, 'client': user.client_id, 'uid': user.uid, 'expiry': user.expiry, 'token-type': 'Bearer' } }, get(path, params = {}, customHeaders = {}) { return this.makeRequest(path, params, customHeaders, 'get') }, post(path, params = {}, customHeaders = {}) { return this.makeRequest(path, params, customHeaders, 'post') }, put(path, params = {}, customHeaders = {}) { return this.makeRequest(path, params, customHeaders, 'put') }, delete(path, params = {}, customHeaders = {}) { return this.makeRequest(path, params, customHeaders, 'delete') }, // getAuthHeaders() { // return store.getState().auth.token || {} // }, makeRequest(path, params, customHeaders, method) { // const externalRequest = path.includes('https') || path.includes('http') let axiosConfig = { headers: { 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json', 'Access-Control-Allow-Origin': '*', 'X-Client': 'mobile', ...customHeaders } } // if (!externalRequest) { // const authHeaders = this.getAuthHeaders() // axiosConfig.baseURL = BaseURL.api // axiosConfig.headers = {...axiosConfig.headers, ...authHeaders } // } axiosConfig.baseURL = BaseURL.api const AXIOS_REQUEST = axios.create(axiosConfig) switch (method) { case 'get': return AXIOS_REQUEST.get(path, {params}).then(response => { return response }) case 'post': return AXIOS_REQUEST.post(path, params).then(response => { return response }) case 'put': return AXIOS_REQUEST.put(path, params).then(response => { return response }) case 'delete': return AXIOS_REQUEST.delete(path, params).then(response => { return response }) default: return new Promise((resolve, _) => { resolve(null) }) } } } export default API
clairempr/bureau
bureau/personnel/apps.py
from django.apps import AppConfig class PersonnelConfig(AppConfig): name = 'bureau.personnel'
TristenSeth/campy
campy/graphics/gbufferedimage.py
<filename>campy/graphics/gbufferedimage.py """ """ import campy.datastructures.grid as _grid import campy.gui.ginteractors as _ginteractors import campy.graphics.gcolor as _gcolor import campy.graphics.gtypes as _gtypes import campy.private.platform as _platform import campy.io.base64helper as _base64helper GBUFFEREDIMAGE_DEFAULT_DIFF_PIXEL_COLOR = 0xdd00dd # def _char_to_hex(ch): # return ord('0') <= ch <= ord('9') ? (ch - ord('0')) : (ch - ord('a') + 10) class GBufferedImage(_ginteractors.GInteractor): WIDTH_HEIGHT_MAX = 65535 @classmethod def load_from_file(cls, filename): inst = cls() inst.load(filename) return inst @property def bounds(self): return _gtypes.GRectangle(self.x, self.y, self.width, self.height) def clear(self): self.fill(self.bg_color) def count_diff_pixels(self, other, bounds=None): # TODO(sredmond): This API differs from the CPP lib. # TODO(sredmond): Include bounds min_width = min(self.width, other.width) min_height = min(self.height, other.height) overlap = min_width * min_height diff_pixel_count = (self.width * self.height - overlap) + (other.width * other.height - overlap) for y in range(min_height): for x in range(min_width): if self.pixels.get(y, x) != other.pixels.get(y, x): diff_pixel_count += 1 return diff_pixel_count def diff(self, other, diff_color=GBUFFEREDIMAGE_DEFAULT_DIFF_PIXEL_COLOR): pass def fill(self, color): # color = _gcolor.normalize(color) self.pixels.fill(color) _platform.Platform().gbufferedimage_fill(self, color) # TODO(get rgb value) pass def fill_region(self, x, y, width, height, TODO): pass def from_grid(self, grid): pass def get_height(self): pass def get_rgb(self, x, y): pass def get_rgb_string(self, x, y): pass def get_width(self): pass def in_bounds(self, x, y): pass def load(self, filename): # TODO(sredmond): Ensure file exists. result = _platform.Platform().gbufferedimage_load(self, filename) decoded = _base64helper.decode(result) self._pixel_string_to_grid(decoded) def resize(self, width, height, retain=True): pass def save(self, filename): pass def set_rgb(x, y, TODO): pass def to_grid(self): pass def _pixel_string_to_grid(self, decoded): # Read width (2B) and height (2B) # TODO(sredmond): Seriously check this bit fiddling w = (decoded[0] << 8) | decoded[1]; h = (decoded[2] << 8) | decoded[3]; if w != self.pixels.width() or h != self.pixels.height(): self.pixels.resize(h, w, retain=False) # Check that we received approximately the right length of bytes. expected = (w * h * 3) + 4 actual = len(decoded) if actual != decoded: print('Expected {} but saw {} bytes'.format(expected, actual)) # TODO(sredmond): Abort abort import sys sys.exit(1) pixels = [] for red, green, blue in zip(decoded[4::3], decoded[5::3], decoded[6::3]): pixels.append(Pixel(red=red, green=green, blue=blue)) i = 0 for row in range(h): for col in range(w): self.pixels.set(row, col, pixels[i]) i += 1 self.width = pixels.width self.height = pixels.height # "Private" constructor, called by class method constructors. def __init__(self, x=0, y=0, width=1, height=1, bg_color=0x000000): self.x = x self.y = y self.width = width self.height = height self.bg_color = bg_color self.pixels = _grid.Grid() def __str__(self): return 'GBufferedImage()' if __name__ == '__main__': from campy.graphics.gwindow import GWindow gw = GWindow() # gbi = GBufferedImage(width=50, height=80, bg_color=0xFFFFFF) # gbi.resize(100, 800) # gbi.fill(0xFFFFFF) gbi = GBufferedImage.load_from_file('/Users/sredmond/Pictures/wallpapers/8to5/car.jpg') gw.add(gbi) input('>')
ChromaPIE/Never-Enough-Currency
src/main/java/com/zundrel/currency/common/inventory/SlotSameItem.java
<reponame>ChromaPIE/Never-Enough-Currency<gh_stars>1-10 package com.zundrel.currency.common.inventory; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class SlotSameItem extends Slot { public SlotSameItem(IInventory inv, int index, int xPos, int yPos) { super(inv, index, xPos, yPos); } // This is the only method we need to override so that // we can't place our inventory-storing Item within // its own inventory (thus making it permanently inaccessible) // as well as preventing abuse of storing backpacks within backpacks /** * Check if the stack is a valid item for this slot. */ @Override public boolean isItemValid(ItemStack itemstack) { boolean isEmpty = true; for (int i = 0; i < this.inventory.getSizeInventory(); i++) { if (!this.inventory.getStackInSlot(i).isEmpty()) { isEmpty = false; break; } } if (isEmpty) { return true; } else if (!itemstack.isEmpty()) { for (int i = 0; i < this.inventory.getSizeInventory(); i++) { if (!this.inventory.getStackInSlot(i).isEmpty() && this.inventory.getStackInSlot(i).getItem() == itemstack.getItem()) { return true; } } } return false; } }
abrams27/mimuw
sem4/so/zadania/zad4/minix_source/usr/src/minix/lib/libsys/sys_schedule.c
#include "syslib.h" int sys_schedule(endpoint_t proc_ep, int priority, int quantum, int cpu) { message m; m.m_lsys_krn_schedule.endpoint = proc_ep; m.m_lsys_krn_schedule.priority = priority; m.m_lsys_krn_schedule.quantum = quantum; m.m_lsys_krn_schedule.cpu = cpu; return(_kernel_call(SYS_SCHEDULE, &m)); }
tony2u/Medusa
Example/Client/HelloWorld/Game/HelloWorldLayer.cpp
<reponame>tony2u/Medusa // Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #include "HelloWorldLayer.h" #include "Core/Chrono/ProfileSample.h" #include "Node/Panel/PanelFactory.h" HelloWorldLayer::HelloWorldLayer(StringRef name/*=StringRef::Empty*/,const IEventArg& e/*=IEventArg::Empty*/):ILayer(name,e) { } HelloWorldLayer::~HelloWorldLayer(void) { } bool HelloWorldLayer::Initialize() { RETURN_FALSE_IF_FALSE(ILayer::Initialize()); /*auto* sprite=NodeFactory::Instance().CreateQuadSprite("HelloWorld.png"); sprite->SetAnchorPoint(AnchorPoint::MiddleCenter); sprite->SetDock(DockPoint::MiddleCenter); AddChild(sprite);*/ /*auto state=this->MutableRenderState().AllocState<RasterizerRenderState>(); state->SetCullMode(GraphicsFace::Back); state->Enable(true); auto depthState = this->MutableRenderState().AllocState<DepthStencilRenderState>(); depthState->EnableDepthTest(true);*/ //auto* shape1 = NodeFactory::Instance().CreatePODSprite("Scene.pod"); ////shape1->SetAnchor(0.5f, 0.5f); ////shape1->SetDock(DockPoint::MiddleCenter); //AddChild(shape1); return true; } bool HelloWorldLayer::OnEnter() { /*auto winSize = ResolutionAdapter::Instance().WinSize(); auto camera = CameraFactory::Instance().CreateFromModel("Camera01", "Scene.pod", winSize, false); IScene* scene = (IScene*)mParent; scene->SetCamera(camera);*/ return true; } MEDUSA_IMPLEMENT_NODE(HelloWorldLayer);
tilm4nn/ebc4j
ebc4j/src/main/java/net/objectzoo/ebc/executor/FlowExecutor.java
<reponame>tilm4nn/ebc4j /* * The MIT License * * Copyright (C) 2011 <NAME> * * http://www.object-zoo.net * * mailto:<EMAIL> * * 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 net.objectzoo.ebc.executor; import net.objectzoo.ebc.CanProcess; import net.objectzoo.ebc.CanStart; import net.objectzoo.ebc.ProcessAndResultFlow; import net.objectzoo.ebc.StartAndResultFlow; /** * The {@code FlowExecuter} supports both: Execution of existing flows with one of it's * {@code static} methods and the execution of flows created per execution using the given * {@link FlowFactory}. * * @author tilmann */ public class FlowExecutor { private final FlowFactory flowCreator; /** * Creates a new {@code FlwoExecutor} using the given {@link FlowFactory} to create new flow * instances * * @param theFlowCreator * the {@link FlowFactory} used to create flow instances */ public FlowExecutor(FlowFactory theFlowCreator) { flowCreator = theFlowCreator; } /** * Creates the flow determined by the given flow class using this executor's {@link FlowFactory} * instance and then executes the flow as described by {@link #process(CanProcess, Object)} * * @param flowClass * the {@link Class} of the flow to be created * @param input * the input parameter to be processed by the flow */ public <ProcessParameter, FlowType extends CanProcess<ProcessParameter>> void process(Class<FlowType> flowClass, ProcessParameter input) { FlowType flow = FlowExecutorHelpers.createFlow(flowClass, flowCreator); process(flow, input); } /** * Creates the flow determined by the given flow class using this executor's {@link FlowFactory} * instance and then executes the flow as described by * {@link #processAndReturnResult(ProcessAndResultFlow, Object)} * * @param flowClass * the {@link Class} of the flow to be created * @param input * the input parameter to be processed by the flow * @return the final result sent by the flow */ public <ProcessParameter, ResultParameter, FlowType extends ProcessAndResultFlow<ProcessParameter, ResultParameter>> ResultParameter processAndReturnResult(Class<FlowType> flowClass, ProcessParameter input) { FlowType flow = FlowExecutorHelpers.createFlow(flowClass, flowCreator); return processAndReturnResult(flow, input); } /** * Creates the flow determined by the given flow class using this executor's {@link FlowFactory} * instance and then executes the flow as described by {@link #start(CanStart)} * * @param flowClass * the {@link Class} of the flow to be created */ public <FlowType extends CanStart> void start(Class<FlowType> flowClass) { FlowType flow = FlowExecutorHelpers.createFlow(flowClass, flowCreator); start(flow); } /** * Creates the flow determined by the given flow class using this executor's {@link FlowFactory} * instance and then executes the flow as described by * {@link #startAndReturnResult(StartAndResultFlow)} * * @param flowClass * the {@link Class} of the flow to be created * @return the final result sent by the flow */ public <ResultParameter, FlowType extends StartAndResultFlow<ResultParameter>> ResultParameter startAndReturnResult(Class<FlowType> flowClass) { FlowType flow = FlowExecutorHelpers.createFlow(flowClass, flowCreator); return startAndReturnResult(flow); } /** * Executes the given {@link CanProcess} flow with the given input parameter * * @param flow * the flow to be executed * @param input * the input parameter provided to the flow */ public static <ProcessParameter, FlowType extends CanProcess<ProcessParameter>> void process(FlowType flow, ProcessParameter input) { flow.processAction().accept(input); } /** * Executes the given {@link ProcessAndResultFlow} flow with the given input parameter and * returns the final result. This method is not thread save regarding simultaneous executions of * the flow! * * @param flow * the flow to be executed * @param input * the input parameter to be processed by the flow * @return the final result sent by the flow */ public static <ProcessParameter, ResultParameter, FlowType extends ProcessAndResultFlow<ProcessParameter, ResultParameter>> ResultParameter processAndReturnResult(FlowType flow, ProcessParameter input) { return new ProcessAndResultFlowToFunctionAdapter<ProcessParameter, ResultParameter>(flow).apply(input); } /** * Executes the given {@link CanStart} flow * * @param flow * the flow to be executed */ public static <FlowType extends CanStart> void start(FlowType flow) { flow.startAction().start(); } /** * Executes the given {@link StartAndResultFlow} flow and returns the final result. This method * is not thread save regarding simultaneous executions of the flow! * * @param flow * the flow to be executed * @return the final result sent by the flow */ public static <ResultParameter, FlowType extends StartAndResultFlow<ResultParameter>> ResultParameter startAndReturnResult(FlowType flow) { return new StartAndResultFlowToSupplierAdapter<ResultParameter>(flow).get(); } }
EnderNightLord-ChromeBook/zircon-rpi
src/sys/pkg/tests/system-tests/check/check.go
// Copyright 2020 The Fuchsia 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 check import ( "context" "fmt" "go.fuchsia.dev/fuchsia/src/testing/host-target-testing/device" "go.fuchsia.dev/fuchsia/src/testing/host-target-testing/sl4f" "go.fuchsia.dev/fuchsia/tools/lib/logger" ) // IsDeviceUpToDate checks if the device's /system/meta matches the expected // system image merkle. func IsDeviceUpToDate( ctx context.Context, device *device.Client, expectedSystemImageMerkle string, ) (bool, error) { remoteSystemImageMerkle, err := device.GetSystemImageMerkle(ctx) if err != nil { return false, fmt.Errorf("failed to get system image merkle while checking if device is up to date: %w", err) } logger.Infof(ctx, "current system image merkle: %q", remoteSystemImageMerkle) logger.Infof(ctx, "expected system image merkle: %q", expectedSystemImageMerkle) return expectedSystemImageMerkle == remoteSystemImageMerkle, nil } func determineActiveABRConfig( ctx context.Context, rpcClient *sl4f.Client, ) (*sl4f.Configuration, error) { if rpcClient == nil { logger.Infof(ctx, "sl4f not running, cannot determine active partition") return nil, nil } currentConfig, err := rpcClient.PaverQueryActiveConfiguration(ctx) if err == sl4f.ErrNotSupported { logger.Infof(ctx, "device does not support querying the active configuration") return nil, nil } else if err != nil { return nil, err } logger.Infof(ctx, "device booted to slot %s", currentConfig) return &currentConfig, nil } func DetermineCurrentABRConfig( ctx context.Context, rpcClient *sl4f.Client, ) (*sl4f.Configuration, error) { if rpcClient == nil { logger.Infof(ctx, "sl4f not running, cannot determine current partition") return nil, nil } currentConfig, err := rpcClient.PaverQueryCurrentConfiguration(ctx) if err == sl4f.ErrNotSupported { logger.Infof(ctx, "device does not support querying the current configuration") return nil, nil } else if err == sl4f.ErrInvalidPaverMethod { // The currently running version of Fuchsia doesn't support QueryCurrentConfiguration. // Log a warning and fall back to using the active config. // For the purposes of these OTA tests, current should always equal active. // TODO(60425): once the minimum supported version of Fuchsia supports QueryCurrentConfiguration, // remove this fallback. logger.Warningf(ctx, "current version on target does not support QueryCurrentConfiguration, falling back to QueryActiveConfiguration") return determineActiveABRConfig(ctx, rpcClient) } else if err != nil { return nil, err } logger.Infof(ctx, "device booted to slot %s", currentConfig) return &currentConfig, nil } func DetermineTargetABRConfig( ctx context.Context, rpcClient *sl4f.Client, ) (*sl4f.Configuration, error) { currentConfig, err := DetermineCurrentABRConfig(ctx, rpcClient) if err != nil { return nil, fmt.Errorf("could not determine target config when querying active config: %w", err) } if currentConfig == nil { return nil, nil } var targetConfig sl4f.Configuration if *currentConfig == sl4f.ConfigurationA { targetConfig = sl4f.ConfigurationB } else { targetConfig = sl4f.ConfigurationA } return &targetConfig, nil } func CheckABRConfig( ctx context.Context, rpcClient *sl4f.Client, expectedConfig *sl4f.Configuration, ) error { if expectedConfig == nil { logger.Infof(ctx, "no configuration expected, so not checking ABR configuration") return nil } if rpcClient == nil { logger.Infof(ctx, "not connected to sl4f, cannot check ABR configuration") return nil } // Ensure the device is booting from the expected boot slot. currentConfig, err := DetermineCurrentABRConfig(ctx, rpcClient) if err != nil { return fmt.Errorf("unable to determine current boot configuration: %w", err) } if currentConfig == nil { return fmt.Errorf("expected device to boot from slot %q, got <nil>", *expectedConfig) } else if *currentConfig != *expectedConfig { return fmt.Errorf("expected device to boot from slot %q, got %q", *expectedConfig, *currentConfig) } return nil } func ValidateDevice( ctx context.Context, device *device.Client, rpcClient *sl4f.Client, expectedSystemImageMerkle string, expectedConfig *sl4f.Configuration, warnOnABR bool, ) error { // At the this point the system should have been updated to the target // system version. Confirm the update by fetching the device's current // /system/meta, and making sure it is the correct version. if expectedSystemImageMerkle != "" { upToDate, err := IsDeviceUpToDate(ctx, device, expectedSystemImageMerkle) if err != nil { return fmt.Errorf("failed to check if device is up to date: %w", err) } if !upToDate { return fmt.Errorf("system version failed to update to %q", expectedSystemImageMerkle) } } // Make sure the device doesn't have any broken static packages. // FIXME(40913): every builder should at least build sl4f as a universe package. if rpcClient == nil { if err := device.ValidateStaticPackages(ctx); err != nil { return fmt.Errorf("failed to validate static packages without sl4f: %w", err) } } else { if err := rpcClient.ValidateStaticPackages(ctx); err != nil { return fmt.Errorf("failed to validate static packages with sl4f: %w", err) } if err := CheckABRConfig(ctx, rpcClient, expectedConfig); err != nil { // FIXME(43336): during the rollout of ABR, the N-1 build might // not be writing to the inactive partition, so don't // err out during that phase. This will be removed once // ABR has rolled through GI. if warnOnABR { logger.Infof(ctx, "ignoring error during ABR rollout: %v", err) } else { return fmt.Errorf("failed to validate device: %w", err) } } } return nil }
Ascend/modelzoo
built-in/ACL_TensorFlow/Official/cv/RetinaNet_for_ACL/scripts/retinanet_postprocess/retinaPostprocess.py
<gh_stars>10-100 # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import os import sys labels_to_names = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'trafficlight', 10: 'firehydrant', 11: 'stopsign', 12: 'parkingmeter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sportsball', 33: 'kite', 34: 'baseballbat', 35: 'baseballglove', 36: 'skateboard', 37: 'surfboard', 38: 'tennisracket', 39: 'bottle', 40: 'wineglass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hotdog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'pottedplant', 59: 'bed', 60: 'diningtable', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cellphone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddybear', 78: 'hairdrier', 79: 'toothbrush'} targetDir = sys.argv[1] txtPath = sys.argv[2] #targetDir = "result_Files/" allFiles = os.listdir(targetDir) #txtPath = "detections/" outputs = [] rawScaleFile = "./rawScale.txt" for i in allFiles: if i.split(".")[0][:-1] not in outputs: outputs.append(i.split(".")[0][:-1]) print("Number of files to be handled : {}".format(len(outputs))) print(outputs) def readAsFP16(f): return np.fromfile(targetDir+f, np.float16) def writeResult(path, filename, b, s, l): file_to_be_write = open(path+filename.split('_')[1]+'.txt', "w") for box, score, label in zip(b, s, l): # scores are sorted so we can break if score < 0.5: break file_to_be_write.write(labels_to_names[label]+" "+str(score)+" "+ str(int(box[0]))+" "+str(int(box[1]))+" "+str(int(box[2])-int(box[0]))+" "+str(int(box[3])-int(box[1]))+"\n") file_to_be_write.close() def readRawScale(rawScaleTxt): with open(rawScaleTxt) as f: content = f.readlines() content = [x.strip() for x in content] lineDict = {} for line in content: lineSpl = line.split(" ") lineDict[lineSpl[0].split(".")[0]]=[float(lineSpl[1]), float(lineSpl[2])] return lineDict def getBox(raw, x, y): cnter = 0 res = [] while cnter<len(raw): singleBbox = [raw[cnter]/x, raw[cnter+1]/y, raw[cnter+2]/x, raw[cnter+3]/y] res.append(singleBbox) cnter+=4 return res dic = readRawScale(rawScaleFile) for cnt,f in enumerate(outputs): print("{} ---> ".format(cnt)+f) rawBoxes = readAsFP16(f+"0.bin") scores = readAsFP16(f+"1.bin") classes = readAsFP16(f+"2.bin") boxes = getBox(rawBoxes, dic[f.split('_')[1]][0], dic[f.split('_')[1]][1]) writeResult(txtPath, f, boxes, scores, classes) ''' for k,j in enumerate(scores): if j<0.5: continue print("Score:\t"+str(j)+"\t"+"Class: "+"\t"+str(classes[k])+"-"+labels_to_names[int(classes[k])]+"\t"+getBox(k, boxes)) '''
JacobsonMT/Gemma
gemma-web/src/main/webapp/scripts/api/entities/gene/GenePage.js
<filename>gemma-web/src/main/webapp/scripts/api/entities/gene/GenePage.js Ext.namespace('Gemma'); Gemma.DIFF_THRESHOLD = 0.01; Gemma.MAX_DIFF_RESULTS = 125; /** * * Top level container for all sections of gene info * * To open the page at a specific tab, include ?tab=[tabName] suffix in the URL. Tab names are each tab's itemId. * * @class Gemma.GenePage * @extends Ext.TabPanel * */ Gemma.GenePage = Ext.extend(Ext.TabPanel, { defaults: { width: 850, autoScroll: true }, deferredRender: true, listeners: { 'tabchange': function (tabPanel, newTab) { newTab.fireEvent('tabChanged'); }, 'beforetabchange': function (tabPanel, newTab, currTab) { // if false is returned, tab isn't changed if (currTab) { return currTab.fireEvent('leavingTab'); } return true; } }, initComponent: function () { var geneId = this.geneId; Gemma.GenePage.superclass.initComponent.call(this); // DETAILS TAB var details = new Gemma.GeneDetails({ title: 'Overview', itemId: 'details', geneId: geneId }); details.on('changeTab', function (tabName) { this.setActiveTab(tabName); }, this); this.add(details); this.add(new Gemma.GeneElementsPanel({ title: 'Elements', itemId: 'elements', geneId: geneId })); this.add(this.initDiffExTab(geneId)); this.add(this.initCoexTab(geneId)); // Phenotype tab: don't show unless supported 13=fly, 14=worm if (this.geneTaxonId == 1 || this.geneTaxonId == 2 || this.geneTaxonId == 3 || this.geneTaxonId == 13 || this.geneTaxonId == 14) { this.add(this.initPhenotypeTab(geneId)); } this.add({ title: 'Gene Ontology Terms', xtype: 'genegogrid', border: true, geneid: this.geneId, minHeight: 150, deferLoadToRender: true, itemId: 'goGrid' }); // console.log( this.geneTaxonId ); // ALLEN BRAIN ATLAS IMAGES don't add unless it's a mammal (human, mouse rat; taxon ids 1,2,3) if (this.geneTaxonId == 1 || this.geneTaxonId == 2 || this.geneTaxonId == 3) { this.add({ xtype: 'geneallenbrainatlasimages', geneId: geneId, title: 'Expression Images', itemId: 'expression' }); } var initialTab = 'details'; this.loadSpecificTab = (document.URL.indexOf("?") > -1 && (document.URL.indexOf("tab=") > -1)); if (this.loadSpecificTab) { var param = Ext.urlDecode(document.URL.substr(document.URL.indexOf("?") + 1)); if (param.tab) { if (this.getComponent(param.tab) != undefined) { initialTab = param.tab; } } } this.on('render', function () { this.setActiveTab(initialTab); }); }, initCoexTab: function (geneId) { var coexpressedGeneGrid = new Gemma.CoexpressionGridLight({ title: 'Coexpression', colspan: 2, noSmallGemma: true, itemId: 'coex' }); /* */ coexpressedGeneGrid.on('render', function () { coexpressedGeneGrid.doSearch({ geneIds: [geneId], quick: true, stringency: 1 }); }); return coexpressedGeneGrid; }, initDiffExTab: function (geneId) { var diffExGrid = new Gemma.ProbeLevelDiffExGrid({ title: 'Differential Expression', itemId: 'diffEx' }); diffExGrid.on('render', function () { var visColumnIndex = diffExGrid.getColumnModel().getIndexById('visualize'); diffExGrid.getColumnModel().setHidden(visColumnIndex, false); // this should go in grid itself, but it wasn't working properly (or at all) if (!this.loadMask && this.getEl()) { this.loadMask = new Ext.LoadMask(this.getEl(), { msg: Gemma.StatusText.Loading.generic, msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading' }); } this.loadMask.show(); diffExGrid.getStore().load({ params: [geneId, Gemma.DIFF_THRESHOLD, Gemma.MAX_DIFF_RESULTS] }); }); return diffExGrid; }, /** * @memberOf Gemma.GenePage */ initPhenotypeTab: function (geneId) { var phenotypeEvidenceGridPanel = new Gemma.PhenotypeEvidenceGridPanel({ title: 'Phenocarta', iconCls: 'icon-neurocarta', itemId: 'phenotypes', hasRelevanceColumn: false, displayPhenotypeAsLink: true, displayEvidenceCodeFullName: true, deferLoadToRender: true, currentGene: { id: this.geneId, ncbiId: this.geneNcbiId, officialSymbol: this.geneSymbol, officialName: this.geneName, taxonCommonName: this.geneTaxonName, taxonId: this.geneTaxonId }, listeners: { phenotypeAssociationChanged: function (phenotypes, gene) { this.getStore().reload(); } } }); phenotypeEvidenceGridPanel.getView().emptyText = Gemma.HelpText.WidgetDefaults.PhenotypePanel.noRecordEmptyText; // This code fails because reload() is called when there are no valid parameters for the call. See bug 4348 // In PhenotypePanel, when a user logs in, PhenotypeGridPanel will be reloaded first, followed by // PhenotypeGeneGridPanel and then PhenotypeEvidenceGridPanel. So, the following code should not // be done in PhenotypeEvidenceGridPanel. Otherwise, PhenotypeEvidenceGridPanel would be reloaded twice. // Gemma.Application.currentUser.on( "logIn", function( userName, isAdmin ) { // phenotypeEvidenceGridPanel.getStore().reload(); // }, this ); return phenotypeEvidenceGridPanel; } });
arunrajora/algorithms
codes/maths/hcf.cpp
// HCF (Highest Common Factor) #include<iostream> using namespace std; int hcf(int a,int b){ return b?hcf(b,a%b):a; } int main(){ cout<<hcf(9,12); }
krattai/AEBL
blades/xbmc/xbmc/network/linux/ZeroconfAvahi.h
<reponame>krattai/AEBL #pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "system.h" #ifdef HAS_AVAHI #include <memory> #include <map> #include <vector> #include <string> #include "network/Zeroconf.h" #include <memory> #include <avahi-client/client.h> #include <avahi-client/publish.h> #include <avahi-common/defs.h> struct AvahiThreadedPoll; class CZeroconfAvahi : public CZeroconf { public: CZeroconfAvahi(); ~CZeroconfAvahi(); protected: //implement base CZeroConf interface virtual bool doPublishService(const std::string& fcr_identifier, const std::string& fcr_type, const std::string& fcr_name, unsigned int f_port, const std::vector<std::pair<std::string, std::string> >& txt); virtual bool doForceReAnnounceService(const std::string& fcr_identifier); virtual bool doRemoveService(const std::string& fcr_ident); virtual void doStop(); private: ///this is where the client calls us if state changes static void clientCallback(AvahiClient* fp_client, AvahiClientState f_state, void*); ///here we get notified of group changes static void groupCallback(AvahiEntryGroup *fp_group, AvahiEntryGroupState f_state, void *); //shutdown callback; works around a problem in avahi < 0.6.24 see destructor for details static void shutdownCallback(AvahiTimeout *fp_e, void *); ///creates the avahi client; ///@return true on success bool createClient(); //don't access stuff below without stopping the client thread //see http://avahi.org/wiki/RunningAvahiClientAsThread //and use struct ScopedEventLoopBlock //helper struct for holding information about creating a service / AvahiEntryGroup //we have to hold that as it's needed to recreate the service class ServiceInfo; typedef std::map<std::string, std::shared_ptr<ServiceInfo> > tServiceMap; //goes through a list of todos and publishs them (takes the client a param, as it might be called from // from the callbacks) void updateServices(AvahiClient* fp_client); //helper that actually does the work of publishing void addService(tServiceMap::mapped_type fp_service_info, AvahiClient* fp_client); AvahiClient* mp_client; AvahiThreadedPoll* mp_poll; //this holds all published and unpublished services including info on howto create them tServiceMap m_services; //2 variables below are needed for workaround of avahi bug (see destructor for details) bool m_shutdown; pthread_t m_thread_id; }; #endif // HAS_AVAHI
okonomi/homebrew-cask
Casks/slack.rb
class Slack < Cask url 'https://rink.hockeyapp.net/api/2/apps/89dc0a9e3d01fb65e383b13c9ce0d3ac?format=zip' homepage 'http://slack.com' version 'latest' sha256 :no_check link 'Slack.app' end
jmaff/rover-ruckus
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmodes/auto/AutoOpMode.java
package org.firstinspires.ftc.teamcode.opmodes.auto; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; public abstract class AutoOpMode extends LinearOpMode { public static final long POLL_INTERVAL = 5; // ms public static final double LATERAL_BIAS = 1.25; // in protected abstract void setup(); protected abstract void run(); @Override public final void runOpMode() throws InterruptedException { setup(); displayInitTelemetry(); waitForStart(); telemetry.clearAll(); telemetry.update(); if (isStopRequested()) { return; } run(); } private void displayInitTelemetry() { telemetry.update(); } }
ndtung01061999/catiny
src/main/java/com/regitiny/catiny/service/impl/FileInfoServiceImpl.java
<filename>src/main/java/com/regitiny/catiny/service/impl/FileInfoServiceImpl.java package com.regitiny.catiny.service.impl; import static org.elasticsearch.index.query.QueryBuilders.*; import com.regitiny.catiny.GeneratedByJHipster; import com.regitiny.catiny.domain.FileInfo; import com.regitiny.catiny.repository.FileInfoRepository; import com.regitiny.catiny.repository.search.FileInfoSearchRepository; import com.regitiny.catiny.service.FileInfoService; import com.regitiny.catiny.service.dto.FileInfoDTO; import com.regitiny.catiny.service.mapper.FileInfoMapper; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing {@link FileInfo}. */ @Service @Transactional @GeneratedByJHipster public class FileInfoServiceImpl implements FileInfoService { private final Logger log = LoggerFactory.getLogger(FileInfoServiceImpl.class); private final FileInfoRepository fileInfoRepository; private final FileInfoMapper fileInfoMapper; private final FileInfoSearchRepository fileInfoSearchRepository; public FileInfoServiceImpl( FileInfoRepository fileInfoRepository, FileInfoMapper fileInfoMapper, FileInfoSearchRepository fileInfoSearchRepository ) { this.fileInfoRepository = fileInfoRepository; this.fileInfoMapper = fileInfoMapper; this.fileInfoSearchRepository = fileInfoSearchRepository; } @Override public FileInfoDTO save(FileInfoDTO fileInfoDTO) { log.debug("Request to save FileInfo : {}", fileInfoDTO); FileInfo fileInfo = fileInfoMapper.toEntity(fileInfoDTO); fileInfo = fileInfoRepository.save(fileInfo); FileInfoDTO result = fileInfoMapper.toDto(fileInfo); fileInfoSearchRepository.save(fileInfo); return result; } @Override public Optional<FileInfoDTO> partialUpdate(FileInfoDTO fileInfoDTO) { log.debug("Request to partially update FileInfo : {}", fileInfoDTO); return fileInfoRepository .findById(fileInfoDTO.getId()) .map( existingFileInfo -> { fileInfoMapper.partialUpdate(existingFileInfo, fileInfoDTO); return existingFileInfo; } ) .map(fileInfoRepository::save) .map( savedFileInfo -> { fileInfoSearchRepository.save(savedFileInfo); return savedFileInfo; } ) .map(fileInfoMapper::toDto); } @Override @Transactional(readOnly = true) public Page<FileInfoDTO> findAll(Pageable pageable) { log.debug("Request to get all FileInfos"); return fileInfoRepository.findAll(pageable).map(fileInfoMapper::toDto); } @Override @Transactional(readOnly = true) public Optional<FileInfoDTO> findOne(Long id) { log.debug("Request to get FileInfo : {}", id); return fileInfoRepository.findById(id).map(fileInfoMapper::toDto); } @Override public void delete(Long id) { log.debug("Request to delete FileInfo : {}", id); fileInfoRepository.deleteById(id); fileInfoSearchRepository.deleteById(id); } @Override @Transactional(readOnly = true) public Page<FileInfoDTO> search(String query, Pageable pageable) { log.debug("Request to search for a page of FileInfos for query {}", query); return fileInfoSearchRepository.search(queryStringQuery(query), pageable).map(fileInfoMapper::toDto); } }
herculeshssj/servidores-oportunidades
OpenXava/src/org/openxava/util/Classes.java
<gh_stars>1-10 package org.openxava.util; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; /** * Utility class to work with classes. <p> * * @author: <NAME> */ public class Classes { /** * If the class contains the exact method without argumetns. <p> */ public static boolean hasMethod(Class theClass, String method) { try { theClass.getMethod(method, (Class<?> []) null); return true; } catch (NoSuchMethodException ex) { return false; } } /** * All fields from all superclasess and including private, protected and public. * * @param theClass * @return */ public static Collection<Field> getFieldsAnnotatedWith(Class theClass, Class<? extends Annotation> annotation) { Collection<Field> result = new ArrayList<Field>(); fillFieldsAnnotatedWith(result, theClass, annotation); return result; } private static void fillFieldsAnnotatedWith(Collection<Field> result, Class theClass, Class<? extends Annotation> annotation) { if (Object.class.equals(theClass)) return; for (Field field: theClass.getDeclaredFields()) { if (field.isAnnotationPresent(annotation)) result.add(field); } fillFieldsAnnotatedWith(result, theClass.getSuperclass(), annotation); } /** * Returns the collection of methods with the given annotation * * @param theClass Class object to be examined * @param annotation Annotation type to be search for * @return a Collection of Method, never null, might be empty. * @since 4.0.1 */ public static Collection<Method> getMethodsAnnotatedWith(Class theClass, Class<? extends Annotation> annotation) { Collection<Method> result = new ArrayList<Method>(); fillMethodsAnnotatedWith(result, theClass, annotation); return result; } private static void fillMethodsAnnotatedWith(Collection<Method> result, Class theClass, Class<? extends Annotation> annotation) { if (Object.class.equals(theClass)) return; for (Method method: theClass.getDeclaredMethods()) { if (method.isAnnotationPresent(annotation)) result.add(method); } fillMethodsAnnotatedWith(result, theClass.getSuperclass(), annotation); } }
Yeolar/flattype
flattype/bucket/Bucket.cpp
<filename>flattype/bucket/Bucket.cpp<gh_stars>0 /* * Copyright 2018 Yeolar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "accelerator/Conv.h" #include "accelerator/String.h" #include "flattype/matrix/ColumnarMatrix.h" #include "flattype/matrix/Matrix.h" #include "flattype/bucket/Bucket.h" namespace ftt { std::string Bucket::toDebugString() const { std::string out; if (!get()) { return "{}"; } acc::toAppend("{ name:", getName(), ", bid:", getBID(), ", fields:", acc::join(',', getFields()), ", matrix:", isColumnar() ? ColumnarMatrix(getMatrix()).toDebugString() : Matrix(getMatrix()).toDebugString(), " }", &out); return out; } uint16_t Bucket::getBID() const { return ptr_ ? ptr_->bid() : 0; } std::string Bucket::getName() const { return ptr_ ? ptr_->name()->str() : ""; } std::vector<std::string> Bucket::getFields() const { std::vector<std::string> fields; if (ptr_ && ptr_->fields()) { for (auto i : *ptr_->fields()) { fields.push_back(i->str()); } } return fields; } const fbs::Matrix* Bucket::getMatrix() const { return ptr_ ? ptr_->matrix() : nullptr; } bool Bucket::isColumnar() const { return ptr_ ? ptr_->columnar() : false; } } // namespace ftt
julianpeeters/avro-scala-macro-annotations
tests/src/test/scala/AvroRecordTests/AvroRecordDefaultValueTest.scala
<gh_stars>10-100 package test import org.specs2.mutable.Specification import com.julianpeeters.avro.annotations._ import java.io.File import org.apache.avro.generic.GenericData.Record import org.apache.avro.generic._ import org.apache.avro.specific._ import org.apache.avro.Schema import org.apache.avro.Schema.{Type => AvroType} import org.apache.avro.file._ @AvroRecord case class AvroRecordTestDefaultValue00(var x: Int = 0) @AvroRecord case class AvroRecordTestDefaultValue01(var x: Float = 1.0F) @AvroRecord case class AvroRecordTestDefaultValue02(var x: Long = 2L) @AvroRecord case class AvroRecordTestDefaultValue03(var x: Double = 2.0D) @AvroRecord case class AvroRecordTestDefaultValue04(var x: Boolean = false) @AvroRecord case class AvroRecordTestDefaultValue05(var x: String = "") @AvroRecord case class AvroRecordTestDefaultValue06(var x: Null = null) @AvroRecord case class AvroRecordTestDefaultValue07(var x: Option[String] = None) @AvroRecord case class AvroRecordTestDefaultValue08(var x: Option[Int] = Some(1)) @AvroRecord case class AvroRecordTestDefaultValue10(var x: List[String] = List("Greta", "Lauren")) @AvroRecord case class AvroRecordTestDefaultValue11(var x: List[Int] = List(1,2)) @AvroRecord case class AvroRecordTestDefaultValue12(var x: Map[String, Int] = Map("Loiusa"->2), var y: Map[String, String] = Map("criss"->"cross")) @AvroRecord case class AvroRecordTestDefaultValue13(var x: Map[String, Option[AvroRecordTest00]] = Map("Bull"->Some(AvroRecordTest00(6)), "Snake"->None)) @AvroRecord case class AvroRecordTestDefaultValue14(var x: AvroRecordTest00 = AvroRecordTest00(4)) @AvroRecord case class AvroRecordTestDefaultValue15(var x: AvroRecordTestDefaultValue00 = AvroRecordTestDefaultValue00(4)) @AvroRecord case class AvroRecordTestDefaultValue16(var x: AvroRecordTestDefaultValue14 = AvroRecordTestDefaultValue14(AvroRecordTest00(5))) @AvroRecord case class AvroRecordTestDefaultValue17(var x: List[Option[AvroRecordTestDefaultValue00]] = List(None, Some(AvroRecordTestDefaultValue00(8)))) @AvroRecord case class AvroRecordTestDefaultValue18(var x: AvroRecordTest00 = AvroRecordTest00(4), var y: AvroRecordTest01 = AvroRecordTest01(3F)) class AvroRecordDefaultValueTest extends Specification { "A case class with an Int field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue00().toString val recordSchema = AvroRecordTestDefaultValue00.SCHEMA$.toString datumSchema must ===("""{"x": 0}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue00","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field","default":0}]}""") } } "A case class with a Float field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue01().toString val recordSchema = AvroRecordTestDefaultValue01.SCHEMA$.toString datumSchema must ===("""{"x": 1.0}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue01","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"float","doc":"Auto-Generated Field","default":1.0}]}""") } } "A case class with a Long field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue02().toString val recordSchema = AvroRecordTestDefaultValue02.SCHEMA$.toString datumSchema must ===("""{"x": 2}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue02","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"long","doc":"Auto-Generated Field","default":2}]}""") } } "A case class with a Double field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue03().toString val recordSchema = AvroRecordTestDefaultValue03.SCHEMA$.toString datumSchema must ===("""{"x": 2.0}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue03","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"double","doc":"Auto-Generated Field","default":2.0}]}""") } } "A case class with a Boolean field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue04().toString val recordSchema = AvroRecordTestDefaultValue04.SCHEMA$.toString datumSchema must ===("""{"x": false}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue04","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"boolean","doc":"Auto-Generated Field","default":false}]}""") } } "A case class with a String field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue05().toString val recordSchema = AvroRecordTestDefaultValue05.SCHEMA$.toString datumSchema must ===("""{"x": ""}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue05","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"string","doc":"Auto-Generated Field","default":""}]}""") } } "A case class with a Null field" should { "have a schema that reflects the default value" in { val datumSchema = AvroRecordTestDefaultValue06().toString val recordSchema = AvroRecordTestDefaultValue06.SCHEMA$.toString datumSchema must ===("""{"x": null}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue06","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"null","doc":"Auto-Generated Field","default":null}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value of Some[String]" in { val datumSchema = AvroRecordTestDefaultValue07().toString val recordSchema = AvroRecordTestDefaultValue07.SCHEMA$.toString datumSchema must ===("""{"x": null}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue07","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":["null","string"],"doc":"Auto-Generated Field","default":null}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value Some()" in { val datumSchema = AvroRecordTestDefaultValue08().toString val recordSchema = AvroRecordTestDefaultValue08.SCHEMA$.toString datumSchema must ===("""{"x": 1}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue08","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":["null","int"],"doc":"Auto-Generated Field","default":1}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value of List[String]" in { val datumSchema = AvroRecordTestDefaultValue10().toString val recordSchema = AvroRecordTestDefaultValue10.SCHEMA$.toString datumSchema must ===("""{"x": ["Greta", "Lauren"]}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue10","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"array","items":"string"},"doc":"Auto-Generated Field","default":["Greta","Lauren"]}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value List[Int]" in { val datumSchema = AvroRecordTestDefaultValue11().toString val recordSchema = AvroRecordTestDefaultValue11.SCHEMA$.toString datumSchema must ===("""{"x": [1, 2]}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue11","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"array","items":"int"},"doc":"Auto-Generated Field","default":[1,2]}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value List[Int]" in { val datumSchema = AvroRecordTestDefaultValue12().toString val recordSchema = AvroRecordTestDefaultValue12.SCHEMA$.toString println(recordSchema) datumSchema must ===("""{"x": {"Loiusa": 2}, "y": {"criss": "cross"}}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue12","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"map","values":"int"},"doc":"Auto-Generated Field","default":{"Loiusa":2}},{"name":"y","type":{"type":"map","values":"string"},"doc":"Auto-Generated Field","default":{"criss":"cross"}}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value List[Option[AvroRecordTest00]]" in { val datumSchema = AvroRecordTestDefaultValue13().toString val recordSchema = AvroRecordTestDefaultValue13.SCHEMA$.toString datumSchema must ===("""{"x": {"Snake": null, "Bull": {"x": 6}}}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue13","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"map","values":["null",{"type":"record","name":"AvroRecordTest00","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field"}]}]},"doc":"Auto-Generated Field","default":{"Bull":{"x":6},"Snake":null}}]}""") } } "A case class with a field that is a nested case class" should { "have a schema that reflects the nested datum as default value, and the nested datum has no default" in { val datumSchema = AvroRecordTestDefaultValue14().toString val recordSchema = AvroRecordTestDefaultValue14.SCHEMA$.toString datumSchema must ===("""{"x": {"x": 4}}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue14","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"record","name":"AvroRecordTest00","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field"}]},"doc":"Auto-Generated Field","default":{"x":4}}]}""") } } "A case class with a field that is a nested case class" should { "have a schema that reflects the nested datum as default value, and the nested datum also has a default" in { val datumSchema = AvroRecordTestDefaultValue15().toString val recordSchema = AvroRecordTestDefaultValue15.SCHEMA$.toString datumSchema must ===("""{"x": {"x": 4}}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue15","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"record","name":"AvroRecordTestDefaultValue00","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field","default":0}]},"doc":"Auto-Generated Field","default":{"x":4}}]}""") } } "A case class with a field that has a doubly nested case class" should { "have a schema that reflects the nested records and their defaults" in { val datumSchema = AvroRecordTestDefaultValue16().toString val recordSchema = AvroRecordTestDefaultValue16.SCHEMA$.toString datumSchema must ===("""{"x": {"x": {"x": 5}}}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue16","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"record","name":"AvroRecordTestDefaultValue14","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"record","name":"AvroRecordTest00","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field"}]},"doc":"Auto-Generated Field","default":{"x":4}}]},"doc":"Auto-Generated Field","default":{"x":{"x":5}}}]}""") } } "A case class with an Option field" should { "have a schema that reflects the default value List[Option[MyRecord]]]" in { val datumSchema = AvroRecordTestDefaultValue17().toString val recordSchema = AvroRecordTestDefaultValue17.SCHEMA$.toString datumSchema must ===("""{"x": [null, {"x": 8}]}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue17","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"array","items":["null",{"type":"record","name":"AvroRecordTestDefaultValue00","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field","default":0}]}]},"doc":"Auto-Generated Field","default":[null,{"x":8}]}]}""") } } "A case class with a field that is a different nested case class in each of two fields" should { "have a schema that reflects the nested datum as default value, and the nested datum has no default" in { val datumSchema = AvroRecordTestDefaultValue18().toString val recordSchema = AvroRecordTestDefaultValue18.SCHEMA$.toString datumSchema must ===("""{"x": {"x": 4}, "y": {"x": 3.0}}""") recordSchema must ===("""{"type":"record","name":"AvroRecordTestDefaultValue18","namespace":"test","doc":"Auto-Generated Schema","fields":[{"name":"x","type":{"type":"record","name":"AvroRecordTest00","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"int","doc":"Auto-Generated Field"}]},"doc":"Auto-Generated Field","default":{"x":4}},{"name":"y","type":{"type":"record","name":"AvroRecordTest01","doc":"Auto-Generated Schema","fields":[{"name":"x","type":"float","doc":"Auto-Generated Field"}]},"doc":"Auto-Generated Field","default":{"x":3.0}}]}""") } } }
imdairies/imd-farm-solutions
src/test/java/com/imd/performance/FirstLactationPeakMilestoneEvaluatorTest.java
<filename>src/test/java/com/imd/performance/FirstLactationPeakMilestoneEvaluatorTest.java package com.imd.performance; import static org.junit.jupiter.api.Assertions.*; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.imd.dto.Animal; import com.imd.dto.MilkingDetail; import com.imd.dto.PerformanceMilestone; import com.imd.loader.AnimalLoader; import com.imd.loader.LifeCycleEventsLoader; import com.imd.loader.MilkingDetailLoader; import com.imd.loader.PerformanceMilestoneLoader; import com.imd.util.IMDLogger; import com.imd.util.IMDProperties; import com.imd.util.TestDataCreationUtil; import com.imd.util.Util; class FirstLactationPeakMilestoneEvaluatorTest { @BeforeAll static void setUpBeforeClass() throws Exception { } @AfterAll static void tearDownAfterClass() throws Exception { } @BeforeEach void setUp() throws Exception { } @AfterEach void tearDown() throws Exception { } @Test void testNotEligible() { String orgId = "IMD"; String maleTag = "-997"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal male = TestDataCreationUtil.createTestAnimal(orgId, maleTag, now.minusDays(1000), false); assertTrue(anmlLdr.deleteAnimal(male) >= 0); assertEquals(1, anmlLdr.insertAnimal(male)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, male.getOrgId(), male.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); assertEquals(1, anmlLdr.deleteAnimal(male)); } catch (Exception e) { fail("Exception : " + e.getMessage()); e.printStackTrace(); } } @Test void testZeroRating() { String orgId = "IMD"; String zeroStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal zeroStarFemale = TestDataCreationUtil.createTestAnimal(orgId, zeroStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(zeroStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(zeroStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); float oneStarValue = milestone.getOneStarThreshold(); TestDataCreationUtil.insertEvent(zeroStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, zeroStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(zeroStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, zeroStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(zeroStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, zeroStarFemale.getDateOfBirth().plusDays((14*30)+275)); LocalDate milkDate = new LocalDate(zeroStarFemale.getDateOfBirth().plusDays(14*30+275+10),IMDProperties.getServerTimeZone()); float oneTimeMilk = Float.parseFloat(Util.formatToSpecifiedDecimalPlaces((oneStarValue-1)/3,1)); MilkingDetail rec1_1 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate,1, oneTimeMilk); MilkingDetail rec1_2 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate,2, oneTimeMilk); MilkingDetail rec1_3 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate,3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec1_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_3 )); MilkingDetail rec2_1 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(1),1, oneTimeMilk); MilkingDetail rec2_2 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(1),2, oneTimeMilk); MilkingDetail rec2_3 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(1),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec2_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.NO_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); TestDataCreationUtil.insertEvent(zeroStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, zeroStarFemale.getDateOfBirth().plusDays((14*30)+275+90)); TestDataCreationUtil.insertEvent(zeroStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, zeroStarFemale.getDateOfBirth().plusDays((14*30)+275+91)); TestDataCreationUtil.insertEvent(zeroStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, zeroStarFemale.getDateOfBirth().plusDays((14*30)+275+90+275)); MilkingDetail rec3_1 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(2),1, oneTimeMilk); MilkingDetail rec3_2 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(2),2, oneTimeMilk); MilkingDetail rec3_3 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(2),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec3_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_3 )); MilkingDetail rec4_1 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(100+275),1, oneStarValue); MilkingDetail rec4_2 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(100+275),2, oneStarValue); MilkingDetail rec4_3 = TestDataCreationUtil.createMilkingRecord(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(),milkDate.plusDays(100+275+275),3, oneStarValue); assertEquals(1,milkLdr.insertMilkRecord(rec4_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.NO_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); assertEquals(6,evtLdr.deleteAnimalLifecycleEvents(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag())); assertEquals(12,milkLdr.deleteAllMilkingRecordOfanAnimal(zeroStarFemale.getOrgId(), zeroStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(zeroStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } @Test void testOneRating() { String orgId = "IMD"; String oneStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal oneStarFemale = TestDataCreationUtil.createTestAnimal(orgId, oneStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(oneStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(oneStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); float oneStarValue = milestone.getTwoStarThreshold(); TestDataCreationUtil.insertEvent(oneStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, oneStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(oneStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, oneStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(oneStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, oneStarFemale.getDateOfBirth().plusDays((14*30)+275)); LocalDate milkDate = new LocalDate(oneStarFemale.getDateOfBirth().plusDays(14*30+275+10),IMDProperties.getServerTimeZone()); float oneTimeMilk = Float.parseFloat(Util.formatToSpecifiedDecimalPlaces((oneStarValue-0.5)/3,1)); MilkingDetail rec1_1 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate,1, oneTimeMilk); MilkingDetail rec1_2 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate,2, oneTimeMilk); MilkingDetail rec1_3 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate,3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec1_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_3 )); MilkingDetail rec2_1 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(1),1, oneTimeMilk); MilkingDetail rec2_2 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(1),2, oneTimeMilk); MilkingDetail rec2_3 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(1),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec2_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ONE_STAR, outcome.getStarRating(),outcome.getEvaluationResultMessage()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); TestDataCreationUtil.insertEvent(oneStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, oneStarFemale.getDateOfBirth().plusDays((14*30)+275+90)); TestDataCreationUtil.insertEvent(oneStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, oneStarFemale.getDateOfBirth().plusDays((14*30)+275+91)); TestDataCreationUtil.insertEvent(oneStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, oneStarFemale.getDateOfBirth().plusDays((14*30)+275+90+275)); MilkingDetail rec3_1 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(2),1, oneTimeMilk); MilkingDetail rec3_2 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(2),2, oneTimeMilk); MilkingDetail rec3_3 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(2),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec3_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_3 )); MilkingDetail rec4_1 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(100+275),1, oneStarValue); MilkingDetail rec4_2 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(100+275),2, oneStarValue); MilkingDetail rec4_3 = TestDataCreationUtil.createMilkingRecord(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(),milkDate.plusDays(100+275+275),3, oneStarValue); assertEquals(1,milkLdr.insertMilkRecord(rec4_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ONE_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); assertEquals(6,evtLdr.deleteAnimalLifecycleEvents(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag())); assertEquals(12,milkLdr.deleteAllMilkingRecordOfanAnimal(oneStarFemale.getOrgId(), oneStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(oneStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } @Test void testTwoRating() { String orgId = "IMD"; String twoStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal twoStarFemale = TestDataCreationUtil.createTestAnimal(orgId, twoStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(twoStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(twoStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); float threeStarValue = milestone.getThreeStarThreshold(); TestDataCreationUtil.insertEvent(twoStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, twoStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(twoStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, twoStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(twoStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, twoStarFemale.getDateOfBirth().plusDays((14*30)+275)); LocalDate milkDate = new LocalDate(twoStarFemale.getDateOfBirth().plusDays(14*30+275+10),IMDProperties.getServerTimeZone()); float oneTimeMilk = Float.parseFloat(Util.formatToSpecifiedDecimalPlaces((threeStarValue-1)/3,1)); MilkingDetail rec1_1 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate,1, oneTimeMilk); MilkingDetail rec1_2 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate,2, oneTimeMilk); MilkingDetail rec1_3 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate,3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec1_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_3 )); MilkingDetail rec2_1 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(1),1, oneTimeMilk); MilkingDetail rec2_2 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(1),2, oneTimeMilk); MilkingDetail rec2_3 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(1),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec2_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.TWO_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); TestDataCreationUtil.insertEvent(twoStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, twoStarFemale.getDateOfBirth().plusDays((14*30)+275+90)); TestDataCreationUtil.insertEvent(twoStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, twoStarFemale.getDateOfBirth().plusDays((14*30)+275+91)); TestDataCreationUtil.insertEvent(twoStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, twoStarFemale.getDateOfBirth().plusDays((14*30)+275+90+275)); MilkingDetail rec3_1 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(2),1, oneTimeMilk); MilkingDetail rec3_2 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(2),2, oneTimeMilk); MilkingDetail rec3_3 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(2),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec3_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_3 )); MilkingDetail rec4_1 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(100+275),1, threeStarValue); MilkingDetail rec4_2 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(100+275),2, threeStarValue); MilkingDetail rec4_3 = TestDataCreationUtil.createMilkingRecord(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(),milkDate.plusDays(100+275+275),3, threeStarValue); assertEquals(1,milkLdr.insertMilkRecord(rec4_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.TWO_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); assertEquals(6,evtLdr.deleteAnimalLifecycleEvents(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag())); assertEquals(12,milkLdr.deleteAllMilkingRecordOfanAnimal(twoStarFemale.getOrgId(), twoStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(twoStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } @Test void testThreeRating() { String orgId = "IMD"; String threeStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal threeStarFemale = TestDataCreationUtil.createTestAnimal(orgId, threeStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(threeStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(threeStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); float fourStarValue = milestone.getFourStarThreshold(); TestDataCreationUtil.insertEvent(threeStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, threeStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(threeStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, threeStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(threeStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, threeStarFemale.getDateOfBirth().plusDays((14*30)+275)); LocalDate milkDate = new LocalDate(threeStarFemale.getDateOfBirth().plusDays(14*30+275+10),IMDProperties.getServerTimeZone()); float oneTimeMilk = Float.parseFloat(Util.formatToSpecifiedDecimalPlaces((fourStarValue-1)/3,1)); MilkingDetail rec1_1 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate,1, oneTimeMilk); MilkingDetail rec1_2 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate,2, oneTimeMilk); MilkingDetail rec1_3 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate,3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec1_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_3 )); MilkingDetail rec2_1 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(1),1, oneTimeMilk); MilkingDetail rec2_2 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(1),2, oneTimeMilk); MilkingDetail rec2_3 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(1),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec2_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.THREE_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); TestDataCreationUtil.insertEvent(threeStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, threeStarFemale.getDateOfBirth().plusDays((14*30)+275+90)); TestDataCreationUtil.insertEvent(threeStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, threeStarFemale.getDateOfBirth().plusDays((14*30)+275+91)); TestDataCreationUtil.insertEvent(threeStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, threeStarFemale.getDateOfBirth().plusDays((14*30)+275+90+275)); MilkingDetail rec3_1 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(2),1, oneTimeMilk); MilkingDetail rec3_2 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(2),2, oneTimeMilk); MilkingDetail rec3_3 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(2),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec3_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_3 )); MilkingDetail rec4_1 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(100+275),1, fourStarValue); MilkingDetail rec4_2 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(100+275),2, fourStarValue); MilkingDetail rec4_3 = TestDataCreationUtil.createMilkingRecord(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(),milkDate.plusDays(100+275+275),3, fourStarValue); assertEquals(1,milkLdr.insertMilkRecord(rec4_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.THREE_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); assertEquals(6,evtLdr.deleteAnimalLifecycleEvents(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag())); assertEquals(12,milkLdr.deleteAllMilkingRecordOfanAnimal(threeStarFemale.getOrgId(), threeStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(threeStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } @Test void testFourRating() { String orgId = "IMD"; String fourStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal fourStarFemale = TestDataCreationUtil.createTestAnimal(orgId, fourStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(fourStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(fourStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); float fourStarValue = milestone.getFiveStarThreshold(); TestDataCreationUtil.insertEvent(fourStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, fourStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(fourStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, fourStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(fourStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, fourStarFemale.getDateOfBirth().plusDays((14*30)+275)); LocalDate milkDate = new LocalDate(fourStarFemale.getDateOfBirth().plusDays(14*30+275+10),IMDProperties.getServerTimeZone()); float oneTimeMilk = Float.parseFloat(Util.formatToSpecifiedDecimalPlaces((fourStarValue-0.5)/3,1)); MilkingDetail rec1_1 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate,1, oneTimeMilk); MilkingDetail rec1_2 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate,2, oneTimeMilk); MilkingDetail rec1_3 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate,3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec1_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_3 )); MilkingDetail rec2_1 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(1),1, oneTimeMilk); MilkingDetail rec2_2 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(1),2, oneTimeMilk); MilkingDetail rec2_3 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(1),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec2_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.FOUR_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); TestDataCreationUtil.insertEvent(fourStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, fourStarFemale.getDateOfBirth().plusDays((14*30)+275+90)); TestDataCreationUtil.insertEvent(fourStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, fourStarFemale.getDateOfBirth().plusDays((14*30)+275+91)); TestDataCreationUtil.insertEvent(fourStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, fourStarFemale.getDateOfBirth().plusDays((14*30)+275+90+275)); MilkingDetail rec3_1 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(2),1, oneTimeMilk); MilkingDetail rec3_2 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(2),2, oneTimeMilk); MilkingDetail rec3_3 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(2),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec3_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_3 )); MilkingDetail rec4_1 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(100+275),1, fourStarValue); MilkingDetail rec4_2 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(100+275),2, fourStarValue); MilkingDetail rec4_3 = TestDataCreationUtil.createMilkingRecord(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(),milkDate.plusDays(100+275+275),3, fourStarValue); assertEquals(1,milkLdr.insertMilkRecord(rec4_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.FOUR_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); assertEquals(6,evtLdr.deleteAnimalLifecycleEvents(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag())); assertEquals(12,milkLdr.deleteAllMilkingRecordOfanAnimal(fourStarFemale.getOrgId(), fourStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(fourStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } @Test void testFiveRating() { String orgId = "IMD"; String fiveStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal fiveStarFemale = TestDataCreationUtil.createTestAnimal(orgId, fiveStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(fiveStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(fiveStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); float fiveStarValue = milestone.getFiveStarThreshold() + 1; TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, fiveStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, fiveStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, fiveStarFemale.getDateOfBirth().plusDays((14*30)+275)); LocalDate milkDate = new LocalDate(fiveStarFemale.getDateOfBirth().plusDays(14*30+275+10),IMDProperties.getServerTimeZone()); float oneTimeMilk = Float.parseFloat(Util.formatToSpecifiedDecimalPlaces((fiveStarValue)/3,1)); MilkingDetail rec1_1 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate,1, oneTimeMilk); MilkingDetail rec1_2 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate,2, oneTimeMilk); MilkingDetail rec1_3 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate,3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec1_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec1_3 )); MilkingDetail rec2_1 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(1),1, oneTimeMilk); MilkingDetail rec2_2 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(1),2, oneTimeMilk); MilkingDetail rec2_3 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(1),3, oneTimeMilk); assertEquals(1,milkLdr.insertMilkRecord(rec2_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec2_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.FIVE_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(oneTimeMilk*3,1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, fiveStarFemale.getDateOfBirth().plusDays((14*30)+275+90)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, fiveStarFemale.getDateOfBirth().plusDays((14*30)+275+91)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, fiveStarFemale.getDateOfBirth().plusDays((14*30)+275+90+275)); MilkingDetail rec3_1 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(2),1, oneTimeMilk*2); MilkingDetail rec3_2 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(2),2, oneTimeMilk*2); MilkingDetail rec3_3 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(2),3, oneTimeMilk*2); assertEquals(1,milkLdr.insertMilkRecord(rec3_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec3_3 )); MilkingDetail rec4_1 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(100+275),1, fiveStarValue); MilkingDetail rec4_2 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(100+275),2, fiveStarValue); MilkingDetail rec4_3 = TestDataCreationUtil.createMilkingRecord(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(),milkDate.plusDays(100+275+275),3, fiveStarValue); assertEquals(1,milkLdr.insertMilkRecord(rec4_1 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_2 )); assertEquals(1,milkLdr.insertMilkRecord(rec4_3 )); outcome = evl.evaluatePerformanceMilestone(milestone, fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.FIVE_STAR, outcome.getStarRating()); assertEquals(Util.formatToSpecifiedDecimalPlaces(((oneTimeMilk*12)/3),1), Util.formatToSpecifiedDecimalPlaces(Float.parseFloat(outcome.getEvaluationValue()),1)); assertEquals(6,evtLdr.deleteAnimalLifecycleEvents(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag())); assertEquals(12,milkLdr.deleteAllMilkingRecordOfanAnimal(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(fiveStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } @Test void testCouldNotComputeRating() { String orgId = "IMD"; String fiveStarFemaleTag = "-999"; DateTime now = DateTime.now(IMDProperties.getServerTimeZone()); IMDLogger.loggingMode = Util.INFO; try { PerformanceMilestoneLoader perfLdr = new PerformanceMilestoneLoader(); AnimalLoader anmlLdr = new AnimalLoader(); LifeCycleEventsLoader evtLdr = new LifeCycleEventsLoader(); MilkingDetailLoader milkLdr = new MilkingDetailLoader(); PerformanceMilestone milestone = perfLdr.retrieveSpecificPerformanceMilestone(orgId, Util.PerformanceMilestone.FIRSTLACTATIONPEAK).get(0); SpecifiedLactationPeakMilestoneEvaluator evl = new SpecifiedLactationPeakMilestoneEvaluator(Util.PerformanceMilestone.FIRSTLACTATIONPEAK,1); Animal fiveStarFemale = TestDataCreationUtil.createTestAnimal(orgId, fiveStarFemaleTag, now.minusDays(1000), true); assertTrue(anmlLdr.deleteAnimal(fiveStarFemale) >= 0); assertTrue(evtLdr.deleteAnimalLifecycleEvents(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag())>= 0); assertTrue(milkLdr.deleteAllMilkingRecordOfanAnimal(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag()) >= 0); assertEquals(1, anmlLdr.insertAnimal(fiveStarFemale)); PerformanceMilestone outcome = evl.evaluatePerformanceMilestone(milestone, fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.ANIMAL_NOT_ELIGIBLE, outcome.getStarRating()); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Came in heat : To be deleted", Util.LifeCycleEvents.HEAT, fiveStarFemale.getDateOfBirth().plusDays(14*30)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Inseminated : To be deleted", Util.LifeCycleEvents.INSEMINATE, fiveStarFemale.getDateOfBirth().plusDays((14*30) + 1)); TestDataCreationUtil.insertEvent(fiveStarFemale.getAnimalTag(), "Calved : To be deleted", Util.LifeCycleEvents.PARTURATE, fiveStarFemale.getDateOfBirth().plusDays((14*30)+275)); outcome = evl.evaluatePerformanceMilestone(milestone, fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag(), Util.LanguageCode.ENG); assertEquals(Util.StarRating.COULD_NOT_COMPUTE_RATING, outcome.getStarRating()); assertEquals(3,evtLdr.deleteAnimalLifecycleEvents(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag())); assertEquals(0,milkLdr.deleteAllMilkingRecordOfanAnimal(fiveStarFemale.getOrgId(), fiveStarFemale.getAnimalTag())); assertEquals(1,anmlLdr.deleteAnimal(fiveStarFemale)); } catch (Exception e) { e.printStackTrace(); fail("Exception : " + e.getMessage()); } } }
livejack/server
lib/favicons.js
<reponame>livejack/server const got = require('got'); module.exports = async (req, res, next) => { if (!req.accepts('image/*')) { res.sendStatus(400); return; } try { const url = Buffer.from(req.params.base64url, 'base64').toString(); const gs = got(url, { headers: { accept: req.get('accept') }, retry: false, responseType: 'buffer' }); const response = await gs; res.set('Content-Type', response.headers['content-type']); res.send(await gs.buffer()); } catch (err) { console.error(err.message); res.sendStatus(404); } };
oss-mirror/isc-kea
src/lib/http/tests/tls_client_unittests.cc
// Copyright (C) 2017-2021 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <asiolink/asio_wrapper.h> #include <asiolink/interval_timer.h> #include <asiolink/tls_acceptor.h> #include <asiolink/testutils/test_tls.h> #include <cc/data.h> #include <http/client.h> #include <http/http_types.h> #include <http/listener.h> #include <http/listener_impl.h> #include <http/post_request_json.h> #include <http/response_creator.h> #include <http/response_creator_factory.h> #include <http/response_json.h> #include <http/tests/response_test.h> #include <http/url.h> #include <util/multi_threading_mgr.h> #include <boost/asio/buffer.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/pointer_cast.hpp> #include <gtest/gtest.h> #include <functional> #include <list> #include <sstream> #include <string> #ifdef WITH_BOTAN #define DISABLE_SOME_TESTS #endif #ifdef WITH_OPENSSL #if !defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER < 0x10100000L) #define DISABLE_SOME_TESTS #endif #endif using namespace boost::asio; using namespace boost::asio::ip; using namespace isc::asiolink; using namespace isc::asiolink::test; using namespace isc::data; using namespace isc::http; using namespace isc::http::test; using namespace isc::util; namespace ph = std::placeholders; /// @todo: put the common part of client and server tests in its own file(s). namespace { /// @brief IP address to which HTTP service is bound. const std::string SERVER_ADDRESS = "127.0.0.1"; /// @brief IPv6 address to whch HTTP service is bound. const std::string IPV6_SERVER_ADDRESS = "::1"; /// @brief Port number to which HTTP service is bound. const unsigned short SERVER_PORT = 18123; /// @brief Request Timeout used in most of the tests (ms). const long REQUEST_TIMEOUT = 10000; /// @brief Persistent connection idle timeout used in most of the tests (ms). const long IDLE_TIMEOUT = 10000; /// @brief Persistent connection idle timeout used in tests where idle connections /// are tested (ms). const long SHORT_IDLE_TIMEOUT = 200; /// @brief Test timeout (ms). const long TEST_TIMEOUT = 10000; /// @brief Test HTTP response. typedef TestHttpResponseBase<HttpResponseJson> Response; /// @brief Pointer to test HTTP response. typedef boost::shared_ptr<Response> ResponsePtr; /// @brief Generic test HTTP response. typedef TestHttpResponseBase<HttpResponse> GenericResponse; /// @brief Pointer to generic test HTTP response. typedef boost::shared_ptr<GenericResponse> GenericResponsePtr; /// @brief Implementation of the @ref HttpResponseCreator. class TestHttpResponseCreator : public HttpResponseCreator { public: /// @brief Create a new request. /// /// @return Pointer to the new instance of the @ref HttpRequest. virtual HttpRequestPtr createNewHttpRequest() const { return (HttpRequestPtr(new PostHttpRequestJson())); } private: /// @brief Creates HTTP response. /// /// @param request Pointer to the HTTP request. /// @return Pointer to the generated HTTP response. virtual HttpResponsePtr createStockHttpResponse(const HttpRequestPtr& request, const HttpStatusCode& status_code) const { // The request hasn't been finalized so the request object // doesn't contain any information about the HTTP version number // used. But, the context should have this data (assuming the // HTTP version is parsed ok). HttpVersion http_version(request->context()->http_version_major_, request->context()->http_version_minor_); // This will generate the response holding JSON content. ResponsePtr response(new Response(http_version, status_code)); response->finalize(); return (response); } /// @brief Creates HTTP response. /// /// This method generates 3 types of responses: /// - response with a requested content type, /// - partial response with incomplete JSON body, /// - response with JSON body copied from the request. /// /// The first one is useful to test situations when received response can't /// be parsed because of the content type mismatch. The second one is useful /// to test request timeouts. The third type is used by most of the unit tests /// to test successful transactions. /// /// @param request Pointer to the HTTP request. /// @return Pointer to the generated HTTP OK response with no content. virtual HttpResponsePtr createDynamicHttpResponse(HttpRequestPtr request) { // Request must always be JSON. PostHttpRequestJsonPtr request_json = boost::dynamic_pointer_cast<PostHttpRequestJson>(request); ConstElementPtr body; if (request_json) { body = request_json->getBodyAsJson(); if (body) { // Check if the client requested one of the two first response // types. GenericResponsePtr response; ConstElementPtr content_type = body->get("requested-content-type"); ConstElementPtr partial_response = body->get("partial-response"); if (content_type || partial_response) { // The first two response types can only be generated using the // generic response as we have to explicitly modify some of the // values. response.reset(new GenericResponse(request->getHttpVersion(), HttpStatusCode::OK)); HttpResponseContextPtr ctx = response->context(); if (content_type) { // Provide requested content type. ctx->headers_.push_back(HttpHeaderContext("Content-Type", content_type->stringValue())); // It doesn't matter what body is there. ctx->body_ = "abcd"; response->finalize(); } else { // Generate JSON response. ctx->headers_.push_back(HttpHeaderContext("Content-Type", "application/json")); // The body lacks '}' so the client will be waiting for it and // eventually should time out. ctx->body_ = "{"; response->finalize(); // The auto generated Content-Length header would be based on the // body size (so set to 1 byte). We have to override it to // account for the missing '}' character. response->setContentLength(2); } return (response); } } } // Third type of response is requested. ResponsePtr response(new Response(request->getHttpVersion(), HttpStatusCode::OK)); // If body was included in the request. Let's copy it. if (body) { response->setBodyAsJson(body); } response->finalize(); return (response); } }; /// @brief Implementation of the test @ref HttpResponseCreatorFactory. /// /// This factory class creates @ref TestHttpResponseCreator instances. class TestHttpResponseCreatorFactory : public HttpResponseCreatorFactory { public: /// @brief Creates @ref TestHttpResponseCreator instance. virtual HttpResponseCreatorPtr create() const { HttpResponseCreatorPtr response_creator(new TestHttpResponseCreator()); return (response_creator); } }; /// @brief Test fixture class for @ref HttpListener. class HttpListenerTest : public ::testing::Test { public: /// @brief Constructor. /// /// Starts test timer which detects timeouts. HttpListenerTest() : io_service_(), factory_(new TestHttpResponseCreatorFactory()), test_timer_(io_service_), run_io_service_timer_(io_service_) { test_timer_.setup(std::bind(&HttpListenerTest::timeoutHandler, this, true), TEST_TIMEOUT, IntervalTimer::ONE_SHOT); } /// @brief Callback function invoke upon test timeout. /// /// It stops the IO service and reports test timeout. /// /// @param fail_on_timeout Specifies if test failure should be reported. void timeoutHandler(const bool fail_on_timeout) { if (fail_on_timeout) { ADD_FAILURE() << "Timeout occurred while running the test!"; } io_service_.stop(); } /// @brief Runs IO service with optional timeout. /// /// @param timeout Optional value specifying for how long the io service /// should be ran (ms). void runIOService(long timeout = 0) { io_service_.get_io_service().reset(); if (timeout > 0) { run_io_service_timer_.setup(std::bind(&HttpListenerTest::timeoutHandler, this, false), timeout, IntervalTimer::ONE_SHOT); } io_service_.run(); io_service_.get_io_service().reset(); io_service_.poll(); } /// @brief IO service used in the tests. IOService io_service_; /// @brief Pointer to the response creator factory. HttpResponseCreatorFactoryPtr factory_; /// @brief Asynchronous timer service to detect timeouts. IntervalTimer test_timer_; /// @brief Asynchronous timer for running IO service for a specified amount /// of time. IntervalTimer run_io_service_timer_; }; /// @brief Test fixture class for testing HTTP client. class HttpsClientTest : public HttpListenerTest { public: /// @brief Constructor. HttpsClientTest() : HttpListenerTest(), listener_(), listener2_(), listener3_(), server_context_(), client_context_() { configServer(server_context_); configClient(client_context_); listener_.reset(new HttpListener(io_service_, IOAddress(SERVER_ADDRESS), SERVER_PORT, server_context_, factory_, HttpListener::RequestTimeout(REQUEST_TIMEOUT), HttpListener::IdleTimeout(IDLE_TIMEOUT))); listener2_.reset(new HttpListener(io_service_, IOAddress(IPV6_SERVER_ADDRESS), SERVER_PORT + 1, server_context_, factory_, HttpListener::RequestTimeout(REQUEST_TIMEOUT), HttpListener::IdleTimeout(IDLE_TIMEOUT))); listener3_.reset(new HttpListener(io_service_, IOAddress(SERVER_ADDRESS), SERVER_PORT + 2, server_context_, factory_, HttpListener::RequestTimeout(REQUEST_TIMEOUT), HttpListener::IdleTimeout(SHORT_IDLE_TIMEOUT))); MultiThreadingMgr::instance().setMode(false); } /// @brief Destructor. ~HttpsClientTest() { listener_->stop(); listener2_->stop(); listener3_->stop(); io_service_.poll(); MultiThreadingMgr::instance().setMode(false); } /// @brief Creates HTTP request with JSON body. /// /// It includes a JSON parameter with a specified value. /// /// @param parameter_name JSON parameter to be included. /// @param value JSON parameter value. /// @param version HTTP version to be used. Default is HTTP/1.1. template<typename ValueType> PostHttpRequestJsonPtr createRequest(const std::string& parameter_name, const ValueType& value, const HttpVersion& version = HttpVersion(1, 1)) { // Create POST request with JSON body. PostHttpRequestJsonPtr request(new PostHttpRequestJson(HttpRequest::Method::HTTP_POST, "/", version)); // Body is a map with a specified parameter included. ElementPtr body = Element::createMap(); body->set(parameter_name, Element::create(value)); request->setBodyAsJson(body); try { request->finalize(); } catch (const std::exception& ex) { ADD_FAILURE() << "failed to create request: " << ex.what(); } return (request); } /// @brief Test that two consecutive requests can be sent over the same /// connection (if persistent, if not persistent two connections will /// be used). /// /// @param version HTTP version to be used. void testConsecutiveRequests(const HttpVersion& version) { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create a client and specify the URL on which the server can be reached. HttpClient client(io_service_); Url url("http://127.0.0.1:18123"); // Initiate request to the server. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1, version); HttpResponseJsonPtr response1(new HttpResponseJson()); unsigned resp_num = 0; ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Initiate another request to the destination. PostHttpRequestJsonPtr request2 = createRequest("sequence", 2, version); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request2, response2, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Actually trigger the requests. The requests should be handlded by the // server one after another. While the first request is being processed // the server should queue another one. ASSERT_NO_THROW(runIOService()); // Make sure that the received responses are different. We check that by // comparing value of the sequence parameters. ASSERT_TRUE(response1); ConstElementPtr sequence1 = response1->getJsonElement("sequence"); ASSERT_TRUE(sequence1); ASSERT_TRUE(response2); ConstElementPtr sequence2 = response2->getJsonElement("sequence"); ASSERT_TRUE(sequence2); EXPECT_NE(sequence1->intValue(), sequence2->intValue()); } /// @brief Test that the client can communicate with two different /// destinations simultaneously. void testMultipleDestinations() { // Start two servers running on different ports. ASSERT_NO_THROW(listener_->start()); ASSERT_NO_THROW(listener2_->start()); // Create the client. It will be communicating with the two servers. HttpClient client(io_service_); // Specify the URLs on which the servers are available. Url url1("http://127.0.0.1:18123"); Url url2("http://[::1]:18124"); // Create a request to the first server. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1); HttpResponseJsonPtr response1(new HttpResponseJson()); unsigned resp_num = 0; ASSERT_NO_THROW(client.asyncSendRequest(url1, client_context_, request1, response1, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Create a request to the second server. PostHttpRequestJsonPtr request2 = createRequest("sequence", 2); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url2, client_context_, request2, response2, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Actually trigger the requests. ASSERT_NO_THROW(runIOService()); // Make sure we have received two different responses. ASSERT_TRUE(response1); ConstElementPtr sequence1 = response1->getJsonElement("sequence"); ASSERT_TRUE(sequence1); ASSERT_TRUE(response2); ConstElementPtr sequence2 = response2->getJsonElement("sequence"); ASSERT_TRUE(sequence2); EXPECT_NE(sequence1->intValue(), sequence2->intValue()); } /// @brief Test that the client can communicate with the same destination /// address and port but with different TLS contexts so void testMultipleTlsContexts() { // Start only one server. ASSERT_NO_THROW(listener_->start()); // Create the client. HttpClient client(io_service_); // Create a second client context. TlsContextPtr client_context2; configClient(client_context2); // Specify the URL on which the server is available. Url url("http://127.0.0.1:18123"); // Create a request to the first server. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1); HttpResponseJsonPtr response1(new HttpResponseJson()); unsigned resp_num = 0; ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Create a request with the second TLS context. PostHttpRequestJsonPtr request2 = createRequest("sequence", 2); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context2, request2, response2, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Actually trigger the requests. ASSERT_NO_THROW(runIOService()); // Make sure we have received two different responses. ASSERT_TRUE(response1); ConstElementPtr sequence1 = response1->getJsonElement("sequence"); ASSERT_TRUE(sequence1); ASSERT_TRUE(response2); ConstElementPtr sequence2 = response2->getJsonElement("sequence"); ASSERT_TRUE(sequence2); EXPECT_NE(sequence1->intValue(), sequence2->intValue()); } /// @brief Test that idle connection can be resumed for second request. void testIdleConnection() { // Start the server that has short idle timeout. It closes the idle // connection after 200ms. ASSERT_NO_THROW(listener3_->start()); // Create the client that will communicate with this server. HttpClient client(io_service_); // Specify the URL of this server. Url url("http://127.0.0.1:18125"); // Create the first request. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1); HttpResponseJsonPtr response1(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [this](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { io_service_.stop(); if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Run the IO service until the response is received. ASSERT_NO_THROW(runIOService()); // Make sure the response has been received. ASSERT_TRUE(response1); ConstElementPtr sequence1 = response1->getJsonElement("sequence"); ASSERT_TRUE(sequence1); // Delay the generation of the second request by 2x server idle timeout. // This should be enough to cause the server to close the connection. ASSERT_NO_THROW(runIOService(SHORT_IDLE_TIMEOUT * 2)); // Create another request. PostHttpRequestJsonPtr request2 = createRequest("sequence", 2); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request2, response2, [this](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { io_service_.stop(); if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Actually trigger the second request. ASSERT_NO_THROW(runIOService()); // Make sire that the server has responded. ASSERT_TRUE(response2); ConstElementPtr sequence2 = response2->getJsonElement("sequence"); ASSERT_TRUE(sequence2); // Make sure that two different responses have been received. EXPECT_NE(sequence1->intValue(), sequence2->intValue()); } /// @brief This test verifies that the client returns IO error code when the /// server is unreachable. void testUnreachable () { // Create the client. HttpClient client(io_service_); // Specify the URL of the server. This server is down. Url url("http://127.0.0.1:18123"); // Create the request. PostHttpRequestJsonPtr request = createRequest("sequence", 1); HttpResponseJsonPtr response(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request, response, [this](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { io_service_.stop(); // The server should have returned an IO error. if (!ec) { ADD_FAILURE() << "asyncSendRequest didn't fail"; } })); // Actually trigger the request. ASSERT_NO_THROW(runIOService()); } /// @brief Test that an error is returned by the client if the server /// response is malformed. void testMalformedResponse () { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create the client. HttpClient client(io_service_); // Specify the URL of the server. Url url("http://127.0.0.1:18123"); // The response is going to be malformed in such a way that it holds // an invalid content type. We affect the content type by creating // a request that holds a JSON parameter requesting a specific // content type. PostHttpRequestJsonPtr request = createRequest("requested-content-type", "text/html"); HttpResponseJsonPtr response(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request, response, [this](const boost::system::error_code& ec, const HttpResponsePtr& response, const std::string& parsing_error) { io_service_.stop(); // There should be no IO error (answer from the server is received). if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } // The response object is NULL because it couldn't be finalized. EXPECT_FALSE(response); // The message parsing error should be returned. EXPECT_FALSE(parsing_error.empty()); })); // Actually trigger the request. ASSERT_NO_THROW(runIOService()); } /// @brief Test that client times out when it doesn't receive the entire /// response from the server within a desired time. void testClientRequestTimeout() { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create the client. HttpClient client(io_service_); // Specify the URL of the server. Url url("http://127.0.0.1:18123"); unsigned cb_num = 0; // Create the request which asks the server to generate a partial // (although well formed) response. The client will be waiting for the // rest of the response to be provided and will eventually time out. PostHttpRequestJsonPtr request1 = createRequest("partial-response", true); HttpResponseJsonPtr response1(new HttpResponseJson()); // This value will be set to true if the connection close callback is // invoked upon time out. auto connection_closed = false; ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [this, &cb_num](const boost::system::error_code& ec, const HttpResponsePtr& response, const std::string&) { if (++cb_num > 1) { io_service_.stop(); } // In this particular case we know exactly the type of the // IO error returned, because the client explicitly sets this // error code. EXPECT_TRUE(ec.value() == boost::asio::error::timed_out); // There should be no response returned. EXPECT_FALSE(response); }, HttpClient::RequestTimeout(100), HttpClient::ConnectHandler(), HttpClient::HandshakeHandler(), [&connection_closed](const int) { // This callback is called when the connection gets closed // by the client. connection_closed = true; }) ); // Create another request after the timeout. It should be handled ok. PostHttpRequestJsonPtr request2 = createRequest("sequence", 1); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request2, response2, [this, &cb_num](const boost::system::error_code& /*ec*/, const HttpResponsePtr&, const std::string&) { if (++cb_num > 1) { io_service_.stop(); } })); // Actually trigger the requests. ASSERT_NO_THROW(runIOService()); // Make sure that the client has closed the connection upon timeout. EXPECT_TRUE(connection_closed); } /// @brief Test that client times out when connection takes too long. void testClientConnectTimeout() { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create the client. HttpClient client(io_service_); // Specify the URL of the server. Url url("http://127.0.0.1:18123"); unsigned cb_num = 0; PostHttpRequestJsonPtr request = createRequest("sequence", 1); HttpResponseJsonPtr response(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request, response, [this, &cb_num](const boost::system::error_code& ec, const HttpResponsePtr& response, const std::string&) { if (++cb_num > 1) { io_service_.stop(); } // In this particular case we know exactly the type of the // IO error returned, because the client explicitly sets this // error code. EXPECT_TRUE(ec.value() == boost::asio::error::timed_out); // There should be no response returned. EXPECT_FALSE(response); }, HttpClient::RequestTimeout(100), // This callback is invoked upon an attempt to connect to the // server. The false value indicates to the HttpClient to not // try to send a request to the server. This simulates the // case of connect() taking very long and should eventually // cause the transaction to time out. [](const boost::system::error_code& /*ec*/, int) { return (false); })); // Create another request after the timeout. It should be handled ok. ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request, response, [this, &cb_num](const boost::system::error_code& /*ec*/, const HttpResponsePtr&, const std::string&) { if (++cb_num > 1) { io_service_.stop(); } })); // Actually trigger the requests. ASSERT_NO_THROW(runIOService()); } /// @brief Tests the behavior of the HTTP client when the premature /// timeout occurs. /// /// The premature timeout may occur when the system clock is moved /// during the transaction. This test simulates this behavior by /// starting new transaction and waiting for the timeout to occur /// before the IO service is ran. The timeout handler is invoked /// first and it resets the transaction state. This test verifies /// that the started transaction tears down gracefully after the /// transaction state is reset. /// /// There are two variants of this test. The first variant schedules /// one transaction before running the IO service. The second variant /// schedules two transactions prior to running the IO service. The /// second transaction is queued, so it is expected that it doesn't /// time out and it runs successfully. /// /// @param queue_two_requests Boolean value indicating if a single /// transaction should be queued (false), or two (true). void testClientRequestLateStart(const bool queue_two_requests) { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create the client. HttpClient client(io_service_); // Specify the URL of the server. Url url("http://127.0.0.1:18123"); // Generate first request. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1); HttpResponseJsonPtr response1(new HttpResponseJson()); // Use very short timeout to make sure that it occurs before we actually // run the transaction. ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [](const boost::system::error_code& ec, const HttpResponsePtr& response, const std::string&) { // In this particular case we know exactly the type of the // IO error returned, because the client explicitly sets this // error code. EXPECT_TRUE(ec.value() == boost::asio::error::timed_out); // There should be no response returned. EXPECT_FALSE(response); }, HttpClient::RequestTimeout(1))); if (queue_two_requests) { PostHttpRequestJsonPtr request2 = createRequest("sequence", 2); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request2, response2, [](const boost::system::error_code& ec, const HttpResponsePtr& response, const std::string&) { // This second request should be successful. if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } EXPECT_TRUE(response); })); } // This waits for 3ms to make sure that the timeout occurs before we // run the transaction. This leads to an unusual situation that the // transaction state is reset as a result of the timeout but the // transaction is alive. We want to make sure that the client can // gracefully deal with this situation. usleep(3000); // Run the transaction and hope it will gracefully tear down. ASSERT_NO_THROW(runIOService(100)); // Now try to send another request to make sure that the client // is healthy. PostHttpRequestJsonPtr request3 = createRequest("sequence", 3); HttpResponseJsonPtr response3(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request3, response3, [this](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { io_service_.stop(); // Everything should be ok. if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } })); // Actually trigger the requests. ASSERT_NO_THROW(runIOService()); } /// @brief Tests that underlying TCP socket can be registered and /// unregistered via connection and close callbacks. /// /// It conducts to consecutive requests over the same client. /// /// @param version HTTP version to be used. void testConnectCloseCallbacks(const HttpVersion& version) { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create a client and specify the URL on which the server can be reached. HttpClient client(io_service_); Url url("http://127.0.0.1:18123"); // Initiate request to the server. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1, version); HttpResponseJsonPtr response1(new HttpResponseJson()); unsigned resp_num = 0; ExternalMonitor monitor; ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } }, HttpClient::RequestTimeout(10000), std::bind(&ExternalMonitor::connectHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::handshakeHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::closeHandler, &monitor, ph::_1) )); // Initiate another request to the destination. PostHttpRequestJsonPtr request2 = createRequest("sequence", 2, version); HttpResponseJsonPtr response2(new HttpResponseJson()); ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request2, response2, [this, &resp_num](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num > 1) { io_service_.stop(); } if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } }, HttpClient::RequestTimeout(10000), std::bind(&ExternalMonitor::connectHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::handshakeHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::closeHandler, &monitor, ph::_1) )); // Actually trigger the requests. The requests should be handlded by the // server one after another. While the first request is being processed // the server should queue another one. ASSERT_NO_THROW(runIOService()); // We should have had 2 connect invocations, no closes // and a valid registered fd EXPECT_EQ(2, monitor.connect_cnt_); EXPECT_EQ(0, monitor.close_cnt_); EXPECT_GT(monitor.registered_fd_, -1); // Make sure that the received responses are different. We check that by // comparing value of the sequence parameters. ASSERT_TRUE(response1); ConstElementPtr sequence1 = response1->getJsonElement("sequence"); ASSERT_TRUE(sequence1); ASSERT_TRUE(response2); ConstElementPtr sequence2 = response2->getJsonElement("sequence"); ASSERT_TRUE(sequence2); EXPECT_NE(sequence1->intValue(), sequence2->intValue()); // Stopping the client the close the connection. client.stop(); // We should have had 2 connect invocations, 1 closes // and an invalid registered fd EXPECT_EQ(2, monitor.connect_cnt_); EXPECT_EQ(1, monitor.close_cnt_); EXPECT_EQ(-1, monitor.registered_fd_); } /// @brief Tests detection and handling out-of-band socket events /// /// It initiates a transaction and verifies that a mid-transaction call /// to HttpClient::closeIfOutOfBand() has no affect on the connection. /// After successful completion of the transaction, a second call to /// HttpClient::closeIfOutOfBand() is made. This should result in the /// connection being closed. /// This step is repeated to verify that after an OOB closure, transactions /// to the same destination can be processed. /// /// Lastly, we verify that HttpClient::stop() closes the connection correctly. /// /// @param version HTTP version to be used. void testCloseIfOutOfBand(const HttpVersion& version) { // Start the server. ASSERT_NO_THROW(listener_->start()); // Create a client and specify the URL on which the server can be reached. HttpClient client(io_service_); Url url("http://127.0.0.1:18123"); // Initiate request to the server. PostHttpRequestJsonPtr request1 = createRequest("sequence", 1, version); HttpResponseJsonPtr response1(new HttpResponseJson()); unsigned resp_num = 0; ExternalMonitor monitor; ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request1, response1, [this, &client, &resp_num, &monitor](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num == 1) { io_service_.stop(); } // We should have 1 connect. EXPECT_EQ(1, monitor.connect_cnt_); // We should have 1 handshake. EXPECT_EQ(1, monitor.handshake_cnt_); // We should have 0 closes EXPECT_EQ(0, monitor.close_cnt_); // We should have a valid fd. ASSERT_GT(monitor.registered_fd_, -1); int orig_fd = monitor.registered_fd_; // Test our socket for OOBness. client.closeIfOutOfBand(monitor.registered_fd_); // Since we're in a transaction, we should have no closes and // the same valid fd. EXPECT_EQ(0, monitor.close_cnt_); ASSERT_EQ(monitor.registered_fd_, orig_fd); if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } }, HttpClient::RequestTimeout(10000), std::bind(&ExternalMonitor::connectHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::handshakeHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::closeHandler, &monitor, ph::_1) )); // Actually trigger the requests. The requests should be handlded by the // server one after another. While the first request is being processed // the server should queue another one. ASSERT_NO_THROW(runIOService()); // Make sure that we received a response. ASSERT_TRUE(response1); ConstElementPtr sequence1 = response1->getJsonElement("sequence"); ASSERT_TRUE(sequence1); EXPECT_EQ(1, sequence1->intValue()); // We should have had 1 connect invocations, no closes // and a valid registered fd EXPECT_EQ(1, monitor.connect_cnt_); EXPECT_EQ(0, monitor.close_cnt_); EXPECT_GT(monitor.registered_fd_, -1); // Test our socket for OOBness. client.closeIfOutOfBand(monitor.registered_fd_); // Since we're in a transaction, we should have no closes and // the same valid fd. EXPECT_EQ(1, monitor.close_cnt_); EXPECT_EQ(-1, monitor.registered_fd_); // Now let's do another request to the destination to verify that // we'll reopen the connection without issue. PostHttpRequestJsonPtr request2 = createRequest("sequence", 2, version); HttpResponseJsonPtr response2(new HttpResponseJson()); resp_num = 0; ASSERT_NO_THROW(client.asyncSendRequest(url, client_context_, request2, response2, [this, &client, &resp_num, &monitor](const boost::system::error_code& ec, const HttpResponsePtr&, const std::string&) { if (++resp_num == 1) { io_service_.stop(); } // We should have 1 connect. EXPECT_EQ(2, monitor.connect_cnt_); // We should have 2 handshake. EXPECT_EQ(2, monitor.handshake_cnt_); // We should have 0 closes EXPECT_EQ(1, monitor.close_cnt_); // We should have a valid fd. ASSERT_GT(monitor.registered_fd_, -1); int orig_fd = monitor.registered_fd_; // Test our socket for OOBness. client.closeIfOutOfBand(monitor.registered_fd_); // Since we're in a transaction, we should have no closes and // the same valid fd. EXPECT_EQ(1, monitor.close_cnt_); ASSERT_EQ(monitor.registered_fd_, orig_fd); if (ec) { ADD_FAILURE() << "asyncSendRequest failed: " << ec.message(); } }, HttpClient::RequestTimeout(10000), std::bind(&ExternalMonitor::connectHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::handshakeHandler, &monitor, ph::_1, ph::_2), std::bind(&ExternalMonitor::closeHandler, &monitor, ph::_1) )); // Actually trigger the requests. The requests should be handlded by the // server one after another. While the first request is being processed // the server should queue another one. ASSERT_NO_THROW(runIOService()); // Make sure that we received the second response. ASSERT_TRUE(response2); ConstElementPtr sequence2 = response2->getJsonElement("sequence"); ASSERT_TRUE(sequence2); EXPECT_EQ(2, sequence2->intValue()); // Stopping the client the close the connection. client.stop(); // We should have had 2 connect invocations, 2 closes // and an invalid registered fd EXPECT_EQ(2, monitor.connect_cnt_); EXPECT_EQ(2, monitor.close_cnt_); EXPECT_EQ(-1, monitor.registered_fd_); } /// @brief Simulates external registry of Connection TCP sockets /// /// Provides methods compatible with Connection callbacks for connnect /// and close operations. class ExternalMonitor { public: /// @brief Constructor ExternalMonitor() : registered_fd_(-1), connect_cnt_(0), handshake_cnt_(0), close_cnt_(0) { } /// @brief Connect callback handler /// @param ec Error status of the ASIO connect /// @param tcp_native_fd socket descriptor to register bool connectHandler(const boost::system::error_code& ec, int tcp_native_fd) { ++connect_cnt_; if ((!ec || (ec.value() == boost::asio::error::in_progress)) && (tcp_native_fd >= 0)) { registered_fd_ = tcp_native_fd; return (true); } else if ((ec.value() == boost::asio::error::already_connected) && (registered_fd_ != tcp_native_fd)) { return (false); } // ec indicates an error, return true, so that error can be handled // by Connection logic. return (true); } /// @brief Handshake callback handler /// @param ec Error status of the ASIO connect bool handshakeHandler(const boost::system::error_code&, int) { ++handshake_cnt_; // ec indicates an error, return true, so that error can be handled // by Connection logic. return (true); } /// @brief Close callback handler /// /// @param tcp_native_fd socket descriptor to register void closeHandler(int tcp_native_fd) { ++close_cnt_; EXPECT_EQ(tcp_native_fd, registered_fd_) << "closeHandler fd mismatch"; if (tcp_native_fd >= 0) { registered_fd_ = -1; } } /// @brief Keeps track of socket currently "registered" for external monitoring. int registered_fd_; /// @brief Tracks how many times the connect callback is invoked. int connect_cnt_; /// @brief Tracks how many times the handshake callback is invoked. int handshake_cnt_; /// @brief Tracks how many times the close callback is invoked. int close_cnt_; }; /// @brief Instance of the listener used in the tests. std::unique_ptr<HttpListener> listener_; /// @brief Instance of the second listener used in the tests. std::unique_ptr<HttpListener> listener2_; /// @brief Instance of the third listener used in the tests (with short idle /// timeout). std::unique_ptr<HttpListener> listener3_; /// @brief Server TLS context. TlsContextPtr server_context_; /// @brief Client TLS context. TlsContextPtr client_context_; }; #ifndef DISABLE_SOME_TESTS // Test that two consecutive requests can be sent over the same (persistent) // connection. TEST_F(HttpsClientTest, consecutiveRequests) { ASSERT_NO_FATAL_FAILURE(testConsecutiveRequests(HttpVersion(1, 1))); } // Test that two consecutive requests can be sent over the same (persistent) // connection. TEST_F(HttpsClientTest, consecutiveRequestsMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testConsecutiveRequests(HttpVersion(1, 1))); } #endif // Test that two consecutive requests can be sent over non-persistent connection. // This is achieved by sending HTTP/1.0 requests, which are non-persistent by // default. The client should close the connection right after receiving a response // from the server. TEST_F(HttpsClientTest, closeBetweenRequests) { ASSERT_NO_FATAL_FAILURE(testConsecutiveRequests(HttpVersion(1, 0))); } // Test that two consecutive requests can be sent over non-persistent connection. // This is achieved by sending HTTP/1.0 requests, which are non-persistent by // default. The client should close the connection right after receiving a response // from the server. TEST_F(HttpsClientTest, closeBetweenRequestsMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testConsecutiveRequests(HttpVersion(1, 0))); } // Test that the client can communicate with two different destinations // simultaneously. TEST_F(HttpsClientTest, multipleDestinations) { ASSERT_NO_FATAL_FAILURE(testMultipleDestinations()); } // Test that the client can communicate with two different destinations // simultaneously. TEST_F(HttpsClientTest, multipleDestinationsMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testMultipleDestinations()); } // Test that the client can use two different TLS contexts to the same // destination address and port simultaneously. TEST_F(HttpsClientTest, multipleTlsContexts) { ASSERT_NO_FATAL_FAILURE(testMultipleTlsContexts()); } // Test that the client can use two different TLS contexts to the same // destination address and port simultaneously. TEST_F(HttpsClientTest, multipleTlsContextsMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testMultipleTlsContexts()); } // Test that idle connection can be resumed for second request. TEST_F(HttpsClientTest, idleConnection) { ASSERT_NO_FATAL_FAILURE(testIdleConnection()); } // Test that idle connection can be resumed for second request. TEST_F(HttpsClientTest, idleConnectionMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testIdleConnection()); } // This test verifies that the client returns IO error code when the // server is unreachable. TEST_F(HttpsClientTest, unreachable) { ASSERT_NO_FATAL_FAILURE(testUnreachable()); } // This test verifies that the client returns IO error code when the // server is unreachable. TEST_F(HttpsClientTest, unreachableMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testUnreachable()); } // Test that an error is returned by the client if the server response is // malformed. TEST_F(HttpsClientTest, malformedResponse) { ASSERT_NO_FATAL_FAILURE(testMalformedResponse()); } // Test that an error is returned by the client if the server response is // malformed. TEST_F(HttpsClientTest, malformedResponseMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testMalformedResponse()); } // Test that client times out when it doesn't receive the entire response // from the server within a desired time. TEST_F(HttpsClientTest, clientRequestTimeout) { ASSERT_NO_FATAL_FAILURE(testClientRequestTimeout()); } // Test that client times out when it doesn't receive the entire response // from the server within a desired time. TEST_F(HttpsClientTest, clientRequestTimeoutMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testClientRequestTimeout()); } // This test verifies the behavior of the HTTP client when the premature // (and unexpected) timeout occurs. The premature timeout may be caused // by the system clock move. TEST_F(HttpsClientTest, DISABLED_clientRequestLateStartNoQueue) { testClientRequestLateStart(false); } // This test verifies the behavior of the HTTP client when the premature // (and unexpected) timeout occurs. The premature timeout may be caused // by the system clock move. TEST_F(HttpsClientTest, DISABLED_clientRequestLateStartNoQueueMultiThreading) { MultiThreadingMgr::instance().setMode(true); testClientRequestLateStart(false); } #ifndef DISABLE_SOME_TESTS // This test verifies the behavior of the HTTP client when the premature // timeout occurs and there are requests queued after the request which // times out. TEST_F(HttpsClientTest, clientRequestLateStartQueue) { testClientRequestLateStart(true); } // This test verifies the behavior of the HTTP client when the premature // timeout occurs and there are requests queued after the request which // times out. TEST_F(HttpsClientTest, clientRequestLateStartQueueMultiThreading) { MultiThreadingMgr::instance().setMode(true); testClientRequestLateStart(true); } #endif // Test that client times out when connection takes too long. TEST_F(HttpsClientTest, clientConnectTimeout) { ASSERT_NO_FATAL_FAILURE(testClientConnectTimeout()); } // Test that client times out when connection takes too long. TEST_F(HttpsClientTest, clientConnectTimeoutMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testClientConnectTimeout()); } #ifndef DISABLE_SOME_TESTS /// Tests that connect and close callbacks work correctly. TEST_F(HttpsClientTest, connectCloseCallbacks) { ASSERT_NO_FATAL_FAILURE(testConnectCloseCallbacks(HttpVersion(1, 1))); } /// Tests that connect and close callbacks work correctly. TEST_F(HttpsClientTest, connectCloseCallbacksMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testConnectCloseCallbacks(HttpVersion(1, 1))); } #endif /// Tests that HttpClient::closeIfOutOfBand works correctly. TEST_F(HttpsClientTest, closeIfOutOfBand) { ASSERT_NO_FATAL_FAILURE(testCloseIfOutOfBand(HttpVersion(1, 1))); } /// Tests that HttpClient::closeIfOutOfBand works correctly. TEST_F(HttpsClientTest, closeIfOutOfBandMultiThreading) { MultiThreadingMgr::instance().setMode(true); ASSERT_NO_FATAL_FAILURE(testCloseIfOutOfBand(HttpVersion(1, 1))); } }
PaulSprayCQUNI/tutorialsP
corejava11/v1ch12/blockingQueue/BlockingQueueTest.java
<filename>corejava11/v1ch12/blockingQueue/BlockingQueueTest.java package blockingQueue; import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import java.util.stream.*; /** * @version 1.03 2018-03-17 * @author <NAME> */ public class BlockingQueueTest { private static final int FILE_QUEUE_SIZE = 10; private static final int SEARCH_THREADS = 100; private static final Path DUMMY = Path.of(""); private static BlockingQueue<Path> queue = new ArrayBlockingQueue<>(FILE_QUEUE_SIZE); public static void main(String[] args) { try (var in = new Scanner(System.in)) { System.out.print("Enter base directory (e.g. /opt/jdk-9-src): "); String directory = in.nextLine(); System.out.print("Enter keyword (e.g. volatile): "); String keyword = in.nextLine(); Runnable enumerator = () -> { try { enumerate(Path.of(directory)); queue.put(DUMMY); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { } }; new Thread(enumerator).start(); for (int i = 1; i <= SEARCH_THREADS; i++) { Runnable searcher = () -> { try { var done = false; while (!done) { Path file = queue.take(); if (file == DUMMY) { queue.put(file); done = true; } else search(file, keyword); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { } }; new Thread(searcher).start(); } } } /** * Recursively enumerates all files in a given directory and its subdirectories. * See Chapters 1 and 2 of Volume II for the stream and file operations. * @param directory the directory in which to start */ public static void enumerate(Path directory) throws IOException, InterruptedException { try (Stream<Path> children = Files.list(directory)) { for (Path child : children.collect(Collectors.toList())) { if (Files.isDirectory(child)) enumerate(child); else queue.put(child); } } } /** * Searches a file for a given keyword and prints all matching lines. * @param file the file to search * @param keyword the keyword to search for */ public static void search(Path file, String keyword) throws IOException { try (var in = new Scanner(file, StandardCharsets.UTF_8)) { int lineNumber = 0; while (in.hasNextLine()) { lineNumber++; String line = in.nextLine(); if (line.contains(keyword)) System.out.printf("%s:%d:%s%n", file, lineNumber, line); } } } }
johnnyrubin/admission-post-licence
Commun/src/AdmissionPostLicence/candidatureHelper.java
<gh_stars>0 package AdmissionPostLicence; /** * Helper class for : candidature * * @author OpenORB Compiler */ public class candidatureHelper { private static final boolean HAS_OPENORB; static { boolean hasOpenORB = false; try { Thread.currentThread().getContextClassLoader().loadClass("org.openorb.CORBA.Any"); hasOpenORB = true; } catch(ClassNotFoundException ex) { } HAS_OPENORB = hasOpenORB; } /** * Insert candidature into an any * @param a an any * @param t candidature value */ public static void insert(org.omg.CORBA.Any a, AdmissionPostLicence.candidature t) { a.insert_Streamable(new AdmissionPostLicence.candidatureHolder(t)); } /** * Extract candidature from an any * @param a an any * @return the extracted candidature value */ public static AdmissionPostLicence.candidature extract(org.omg.CORBA.Any a) { if (!a.type().equal(type())) throw new org.omg.CORBA.MARSHAL(); if (HAS_OPENORB && a instanceof org.openorb.CORBA.Any) { // streamable extraction. The jdk stubs incorrectly define the Any stub org.openorb.CORBA.Any any = (org.openorb.CORBA.Any)a; try { org.omg.CORBA.portable.Streamable s = any.extract_Streamable(); if(s instanceof AdmissionPostLicence.candidatureHolder) return ((AdmissionPostLicence.candidatureHolder)s).value; } catch (org.omg.CORBA.BAD_INV_ORDER ex) { } AdmissionPostLicence.candidatureHolder h = new AdmissionPostLicence.candidatureHolder(read(a.create_input_stream())); a.insert_Streamable(h); return h.value; } return read(a.create_input_stream()); } // // Internal TypeCode value // private static org.omg.CORBA.TypeCode _tc = null; private static boolean _working = false; /** * Return the candidature TypeCode * @return a TypeCode */ public static org.omg.CORBA.TypeCode type() { if (_tc == null) { synchronized(org.omg.CORBA.TypeCode.class) { if (_tc != null) return _tc; if (_working) return org.omg.CORBA.ORB.init().create_recursive_tc(id()); _working = true; org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(); org.omg.CORBA.StructMember []_members = new org.omg.CORBA.StructMember[7]; _members[0] = new org.omg.CORBA.StructMember(); _members[0].name = "etudiant"; _members[0].type = AdmissionPostLicence.identiteHelper.type(); _members[1] = new org.omg.CORBA.StructMember(); _members[1].name = "master"; _members[1].type = orb.get_primitive_tc(org.omg.CORBA.TCKind.tk_string); _members[2] = new org.omg.CORBA.StructMember(); _members[2].name = "universite"; _members[2].type = orb.get_primitive_tc(org.omg.CORBA.TCKind.tk_string); _members[3] = new org.omg.CORBA.StructMember(); _members[3].name = "ordre"; _members[3].type = orb.get_primitive_tc(org.omg.CORBA.TCKind.tk_short); _members[4] = new org.omg.CORBA.StructMember(); _members[4].name = "etat"; _members[4].type = AdmissionPostLicence.etatCandidatureHelper.type(); _members[5] = new org.omg.CORBA.StructMember(); _members[5].name = "decisionC"; _members[5].type = AdmissionPostLicence.decisionCandidatHelper.type(); _members[6] = new org.omg.CORBA.StructMember(); _members[6].name = "decisionM"; _members[6].type = AdmissionPostLicence.decisionMasterHelper.type(); _tc = orb.create_struct_tc(id(),"candidature",_members); _working = false; } } return _tc; } /** * Return the candidature IDL ID * @return an ID */ public static String id() { return _id; } private final static String _id = "IDL:AdmissionPostLicence/candidature:1.0"; /** * Read candidature from a marshalled stream * @param istream the input stream * @return the readed candidature value */ public static AdmissionPostLicence.candidature read(org.omg.CORBA.portable.InputStream istream) { AdmissionPostLicence.candidature new_one = new AdmissionPostLicence.candidature(); new_one.etudiant = AdmissionPostLicence.identiteHelper.read(istream); new_one.master = istream.read_string(); new_one.universite = istream.read_string(); new_one.ordre = istream.read_short(); new_one.etat = AdmissionPostLicence.etatCandidatureHelper.read(istream); new_one.decisionC = AdmissionPostLicence.decisionCandidatHelper.read(istream); new_one.decisionM = AdmissionPostLicence.decisionMasterHelper.read(istream); return new_one; } /** * Write candidature into a marshalled stream * @param ostream the output stream * @param value candidature value */ public static void write(org.omg.CORBA.portable.OutputStream ostream, AdmissionPostLicence.candidature value) { AdmissionPostLicence.identiteHelper.write(ostream,value.etudiant); ostream.write_string(value.master); ostream.write_string(value.universite); ostream.write_short(value.ordre); AdmissionPostLicence.etatCandidatureHelper.write(ostream,value.etat); AdmissionPostLicence.decisionCandidatHelper.write(ostream,value.decisionC); AdmissionPostLicence.decisionMasterHelper.write(ostream,value.decisionM); } }
ReZeroS/LeetCode
589.N-ary Tree Preorder Traversal/test.cpp
<filename>589.N-ary Tree Preorder Traversal/test.cpp /* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ static auto __ = [] () { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }(); class Solution { public: vector<int> vec; vector<int> preorder(Node* root) { dlr(root); return vec; } void dlr(Node* root){ if(!root){ return ; } int len = root->children.size(); vec.emplace_back(root->val); for(int i = 0; i < len; ++i){ dlr(root->children[i]); } } };
fractalPlatform/Fractal.js
examples/playground/imageSet.js
import R from 'ramda' import h from 'snabbdom/h' import F from '../../lib' const fetchTask = F.tasks.fetch.types.fetch // TODO: hacer que este modulo sea una matriz de 4x4 imagenes, evaluar si agregar un metodo de ayuda para esta tarea al core export default F.def({ // state stuff init: ({key}) => ({ key, lorempixel: 'fetching', loremsrc: {}, }), inputs: { fetchImage: (ctx, Action, _) => [ Action.Reload(), [ 'fetch', fetchTask({ url: 'https://unsplash.it/40/40?random', options: { method: 'get', }, response: res => res.blob(), success: blob => ctx.action$(Action.Lorempixel(URL.createObjectURL(blob))), denied: () => ctx.action$(Action.LorempixelFail()), error: () => ctx.action$(Action.LorempixelFail()), netError: () => ctx.action$(Action.LorempixelFail()), }) ] ], }, actions: { Reload: [[], R.evolve({lorempixel: R.always('fetching')})], Lorempixel: [[String], (objURL, model) => R.evolve({ lorempixel: R.always('success'), loremsrc: R.always(objURL) }, model)], LorempixelFail: [[], R.evolve({lorempixel: R.always('error')})], }, // side connections interfaces: { view: (ctx, i, m) => h('div', {key: m.key, style: styles.base, hook: {insert: i.fetchImage }}, [ (() => { if (m.lorempixel == 'fetching') return h('span', {style: styles.image}, 'fetching...') if (m.lorempixel == 'success') return h('img', {style: styles.image, attrs: {src: m.loremsrc}}) if (m.lorempixel == 'error') return h('span', {style: styles.image}, 'error') })(), h('button', {style: styles.button, on: {click: i.fetchImage}}, 'Reload'), ]), } }) let styles = { base: { margin: '5px', width: '70px', height: '70px', padding: '2px', color: 'white', backgroundColor: 'rgb(80, 150, 190)', border: '1px solid blue', }, count: { fontSize: '16px', textAlign: 'center', }, button: {}, image: {}, }
lyphui/Just-Code
src/0050.powx-n/powx-n.py
class Solution: def myPow(self, x: float, n: int) -> float: p, r = abs(n), 1 while p: if p & 1: r *= x x *= x p >>= 1 return r if n >= 0 else 1/r
2bite/ARK-SDK
SDK/ARKSurvivalEvolved_EngramEntry_HideBoots_parameters.hpp
<reponame>2bite/ARK-SDK<filename>SDK/ARKSurvivalEvolved_EngramEntry_HideBoots_parameters.hpp #pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_EngramEntry_HideBoots_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function EngramEntry_HideBoots.EngramEntry_HideBoots_C.ExecuteUbergraph_EngramEntry_HideBoots struct UEngramEntry_HideBoots_C_ExecuteUbergraph_EngramEntry_HideBoots_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
yasserglez/pytiger2c
packages/pytiger2c/ast/oroperatornode.py
# -*- coding: utf-8 -*- """ Clase C{OrOperatorNode} del árbol de sintáxis abstracta. """ from pytiger2c.ast.binarylogicaloperatornode import BinaryLogicalOperatorNode from pytiger2c.types.integertype import IntegerType class OrOperatorNode(BinaryLogicalOperatorNode): """ Clase C{OrOperatorNode} del árbol de sintáxis abstracta. Representa la operación lógica C{OR}, representada con el operador C{|} en Tiger, entre dos números enteros. Este operador retornará 1 en caso de que el resultado de evaluar la expresión sea verdadero, 0 en otro caso. """ def __init__(self, left, right): """ Inicializa la clase C{OrOperatorNode}. Para obtener información acerca de los parámetros recibidos por este método consulte la documentación del método C{__init__} en la clase C{BinaryOperatorNode}. """ super(OrOperatorNode, self).__init__(left, right) def generate_code(self, generator): """ Genera el código C correspondiente a la estructura del lenguaje Tiger representada por el nodo. @type generator: C{CodeGenerator} @param generator: Clase auxiliar utilizada en la generación del código C correspondiente a un programa Tiger. @raise CodeGenerationError: Esta excepción se lanzará cuando se produzca algún error durante la generación del código correspondiente al nodo. La excepción contendrá información acerca del error. """ self.scope.generate_code(generator) result_var = generator.define_local(IntegerType().code_type) self.left.generate_code(generator) generator.add_statement('if ({left}) {{'.format(left=self.left.code_name)) generator.add_statement('{result} = 1; }}'.format(result=result_var)) generator.add_statement('else {') self.right.generate_code(generator) generator.add_statement('if ({right}) {{'.format(right=self.right.code_name)) generator.add_statement('{result} = 1; }}'.format(result=result_var)) generator.add_statement('else {') generator.add_statement('{result} = 0; }}'.format(result=result_var)) generator.add_statement('}') self._code_name = result_var
thiagogarbazza/project-manager
src/api-test/domain/iteration/iteration-validate-spec.js
'use strict'; const IterationValidate = require('../../../api/domain/iteration/iteration-validate'); const DATA_2010_01_01 = new Date('2010/01/01'); const DATA_2013_06_03 = new Date('2013/06/03'); const DATA_2013_06_07 = new Date('2013/06/07'); describe('api domain iteration validate', () => { const APP = {}; let ITERATION; let iterationValidate; beforeEach(() => { dottie.set(APP, 'domain.iteration.IterationModel', {}); ITERATION = { end: DATA_2013_06_07, id: '<PASSWORD>', name: 'Sprint 01', projectId: '43cf39a6-f1a8-48fe-a76b-ee042cb2ea9a', start: DATA_2013_06_03, text: 'There was no problem during the Sprint' }; iterationValidate = new IterationValidate(APP); }); it('should be defined', () => { expect(iterationValidate).to.not.be.undefined; }); it('end should be required', done => { delete ITERATION.end; iterationValidate.endIsRequired(ITERATION) .then(result => { expect(result.code).to.equal('iteration.end.required'); expect(result.message).to.equal('End date is required'); return done(); }) .catch(done); }); it('end must be greater than a start.', done => { ITERATION.start = DATA_2013_06_03; ITERATION.end = DATA_2010_01_01; iterationValidate.endMustBeGreaterThanAStart(ITERATION) .then(result => { expect(result.code).to.equal('iteration.end.must-be-greater-than-a-start'); expect(result.message).to.equal('End date must be greater than a start date'); return done(); }) .catch(done); }); it('name should be required', done => { delete ITERATION.name; iterationValidate.nameIsRequired(ITERATION) .then(result => { expect(result.code).to.equal('iteration.name.required'); expect(result.message).to.equal('Name is required'); return done(); }) .catch(done); }); it('name should be unique, Sending a new name', done => { const anotherDocument = clone(ITERATION); anotherDocument.name = 'Internal'; APP.domain.iteration.IterationModel.findOne = simpleMock.stub().resolveWith(); iterationValidate.nameMustBeUnique(anotherDocument) .then(() => { expect(APP.domain.iteration.IterationModel.findOne.callCount).to.equal(1); return done(); }) .catch(done); }); it('name should be unique, Sending same name with equal ID', done => { const anotherDocument = clone(ITERATION); APP.domain.iteration.IterationModel.findOne = simpleMock.stub().resolveWith(ITERATION); iterationValidate.nameMustBeUnique(anotherDocument) .then(() => { expect(APP.domain.iteration.IterationModel.findOne.callCount).to.equal(1); return done(); }) .catch(done); }); it('name should be unique, Sending same name with different ID´s', done => { const anotherDocument = clone(ITERATION); anotherDocument.id = '2103c936-6613-4479-975c-cd1a87fe1e41'; APP.domain.iteration.IterationModel.findOne = simpleMock.stub().resolveWith(ITERATION); iterationValidate.nameMustBeUnique(anotherDocument) .then(result => { expect(APP.domain.iteration.IterationModel.findOne.callCount).to.equal(1); expect(result.code).to.equal('iteration.name.unique'); expect(result.message).to.equal('Name must be unique'); return done(); }) .catch(done); }); it('name should be maximum 100 characters', done => { ITERATION.name = properties.BIG_TEXT; iterationValidate.nameMustHaveMaximum100Characters(ITERATION) .then(result => { expect(result.code).to.equal('iteration.name.maxlength'); expect(result.message).to.equal('Name must have a maximum of 100 characters'); return done(); }) .catch(done); }); it('project should be required', done => { delete ITERATION.projectId; iterationValidate.projectIsRequired(ITERATION) .then(result => { expect(result.code).to.equal('iteration.project.required'); expect(result.message).to.equal('Project is required'); return done(); }) .catch(done); }); it('start should be required', done => { delete ITERATION.start; iterationValidate.startIsRequired(ITERATION) .then(result => { expect(result.code).to.equal('iteration.start.required'); expect(result.message).to.equal('Start date is required'); return done(); }) .catch(done); }); describe('# onCreate', () => { beforeEach(() => { delete ITERATION.id; APP.domain.iteration.IterationModel.findOne = simpleMock.stub().resolveWith(); }); it('create a new valid iteration', done => { iterationValidate.onCreate(ITERATION) .then(() => done()) .catch(done); }); it('create a new invalid iteration', done => { const expected2Erros = 2; delete ITERATION.name; delete ITERATION.projectId; iterationValidate.onCreate(ITERATION) .then(() => done('should be error')) .catch(error => { expect(error.name).to.equal('BusinessError'); expect(error.errors.length).to.equal(expected2Erros); expect(error.errors[0].code).to.equal('iteration.name.required'); expect(error.errors[1].code).to.equal('iteration.project.required'); return done(); }); }); }); describe('# onUpdate', () => { beforeEach(() => { APP.domain.iteration.IterationModel.findOne = simpleMock.stub().resolveWith(); }); it('update a valid iteration', done => { iterationValidate.onUpdate(ITERATION) .then(() => done()) .catch(error => done(error)); }); it('update a invalid iteration', done => { const expected2Erros = 2; delete ITERATION.name; delete ITERATION.projectId; iterationValidate.onUpdate(ITERATION) .then(() => done()) .catch(error => { expect(error.name).to.equal('BusinessError'); expect(error.errors.length).to.equal(expected2Erros); expect(error.errors[0].code).to.equal('iteration.name.required'); expect(error.errors[1].code).to.equal('iteration.project.required'); return done(); }); }); }); });
MrSlovo/IT-Coding-Exercises
Gr 10/TextBook Activity/pg45Activity4/src/Main.java
public class Main { public static void main(String[] args) { String s1 = "polo"; String s2 = "call"; System.out.print(s2.charAt(0)); System.out.print(s1.charAt(3)); System.out.print(s1.charAt(1)); System.out.print(s2.charAt(2)); System.out.println("!"); } }
HernandezM22/DatlasHackMTY
real-data/node_modules/@deck.gl/json/dist/esm/syntactic-sugar.js
<filename>real-data/node_modules/@deck.gl/json/dist/esm/syntactic-sugar.js var FUNCTION_IDENTIFIER = '@@='; var CONSTANT_IDENTIFIER = '@@#'; var TYPE_KEY = '@@type'; export { FUNCTION_IDENTIFIER, CONSTANT_IDENTIFIER, TYPE_KEY }; //# sourceMappingURL=syntactic-sugar.js.map
hscspring/TheAlgorithms-Python
LeetCode/8-String-to-Integer (atoi)/String-to-Integer.py
<filename>LeetCode/8-String-to-Integer (atoi)/String-to-Integer.py class Solution: def remove_frontspace(self, s): i = 0 while i < len(s) and s[i] == " ": i = i + 1 return s[i:] def s2num(self, s): news = self.remove_frontspace(s) if news == "": return 0 begin = news[0] if begin == "-" or begin == "+": res = begin else: try: int(begin) res = begin except ValueError as e: return 0 for i in news[1:]: try: int(i) except ValueError as e: break res += i if res == "" or res == "-" or res == "+": num = 0 else: num = int(res) return num def myAtoi(self, s: str) -> int: num = self.s2num(s) minn = -(2**31) maxn = 2**31-1 if num < minn: num = minn elif num > maxn: num = maxn return num if __name__ == '__main__': solution = Solution() assert solution.myAtoi(" +0 123") == 0 assert solution.myAtoi("+") == 0 assert solution.myAtoi("-") == 0 assert solution.myAtoi("-120") == -120 assert solution.myAtoi("-1+0") == -1 assert solution.myAtoi("1-+0") == 1 assert solution.myAtoi("0+1") == 0 assert solution.myAtoi("1+0") == 1 assert solution.myAtoi("1-0") == 1 assert solution.myAtoi("0-1") == 0 assert solution.myAtoi("4a2") == 4 assert solution.myAtoi("words and 987") == 0 assert solution.myAtoi("4193 with words") == 4193 assert solution.myAtoi(" -42") == -42 assert solution.myAtoi("42") == 42 assert solution.myAtoi("") == 0 assert solution.myAtoi(" ") == 0
JUD210/Study-Note
__Training__/Python - HackerRank/4. Sets/Set .add().py
<reponame>JUD210/Study-Note # https://www.hackerrank.com/challenges/py-set-add/problem n = int(input()) # 7 # len(set) s = set() for _ in range(n): s.add(input()) # UK # China # USA # France # New Zealand # UK # France print(len(s)) # 5
phodal/twu-biblioteca-phodal
src/com/twu/biblioteca/artistic/book/Book.java
<filename>src/com/twu/biblioteca/artistic/book/Book.java package com.twu.biblioteca.artistic.book; import com.twu.biblioteca.artistic.Artistic; /** * Created by fdhuang on 9/9/14. */ public class Book extends Artistic { private final String type; private String author; public Book(String name, String author, int publishDate) { super(name, publishDate); this.author = author; this.type = "book"; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getType() { return type; } }
oluigipo/untitled
src/main.c
// Includes #include "headers/all.h" struct GameGlobalState game = { 0 }; internal void parse_args(struct GameArgs* restrict args, uint argc, const char* restrict* restrict argv) { // Default values args->mem = megabytes(8); args->width = 0; args->height = 0; args->fullscreen = -1; args->novsync = 0; args->locale = -1; // debug_log("%llu\n", hash_of_cstr("locale")); // Parse arguments for (uint i = 1; i < argc; ++i) { const char* restrict arg = argv[i]; // Argument shall begin with a - if (arg[0] != '-') { continue; } u64 hash = hash_of_cstr(arg + 1); // ignore first character #define __write_field(field, format) \ do { if (!argv[i+1]) { debug_error("Missing value for argument '%s'. Default to %u.\n", argv[i], args->field); break; } ++i; arg = argv[i]; sscanf(arg, (format), &args->field); } while (0) #define __write_flag(field, value) do { args->field = (value); } while (0) switch (hash) { case 3298519710295134399ull: __write_field(width, "%u"); break; case 14734894603901239938ull: __write_field(height, "%u"); break; case 2222796463784432279ull: __write_field(locale, "%u"); break; case 3748217411440170462ull: // fs case 17893791189687017496ull: __write_flag(fullscreen, true); break; case 16136394061700334151ull: __write_flag(novsync, true); break; // mem case 15779855643795709214ull: { ++i; arg = argv[i]; if (!arg) { debug_error("Missing value for argument '-mem'. Default to %llu.\n", args->mem); break; } usize s; sscanf(arg, "%zu", &s); if (s < args->mem) { debug_error("Argument for '-mem' shall be greater than %llu. Ignoring flag.\n", megabytes(1)); break; } args->mem = s; } break; // error case 14697351840100226696ull: { ++i; arg = argv[i]; if (!arg) { debug_error("WTF????"); exit(1); } os_message_box("Assertion Failure", arg); exit(0); } break; // Unknown default: { debug_error("Ignoring argument '%s'\n", arg); } break; } #undef __write_field #undef __write_flag } } //~ Main Function int main(int argc, char* argv[]) { struct GameArgs args; uint result; // Initialize game. parse_args(&args, (uint)argc, (void*)argv); result = engine_init(&args); if (result != 0) return result; game.currentScene = FIRST_SCENE; do { result = game.currentScene(); } while (game.currentScene && result == 0 && !glfwWindowShouldClose(game.apiWindow)); engine_deinit(); return result; }
81CuongVn/hikaki
hikari/traits.py
# -*- coding: utf-8 -*- # cython: language_level=3 # Copyright (c) 2020 Nekokatt # Copyright (c) 2021-present davfsa # # 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. """Core app interface for application implementations.""" from __future__ import annotations __all__: typing.List[str] = [ "CacheAware", "EventManagerAware", "EntityFactoryAware", "EventFactoryAware", "ExecutorAware", "GatewayBotAware", "IntentsAware", "NetworkSettingsAware", "RESTAware", "RESTBotAware", "Runnable", "InteractionServerAware", "ShardAware", "VoiceAware", ] import typing from hikari import presences from hikari import undefined from hikari.internal import fast_protocol if typing.TYPE_CHECKING: import datetime from concurrent import futures from hikari import channels from hikari import config from hikari import guilds from hikari import intents as intents_ from hikari import snowflakes from hikari import users as users_ from hikari.api import cache as cache_ from hikari.api import entity_factory as entity_factory_ from hikari.api import event_factory as event_factory_ from hikari.api import event_manager as event_manager_ from hikari.api import interaction_server as interaction_server_ from hikari.api import rest as rest_ from hikari.api import shard as gateway_shard from hikari.api import voice as voice_ @typing.runtime_checkable class NetworkSettingsAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for any component aware of network settings.""" __slots__: typing.Sequence[str] = () @property def http_settings(self) -> config.HTTPSettings: """Return the HTTP settings in use by this component. Returns ------- hikari.config.HTTPSettings The HTTP settings in use. """ raise NotImplementedError @property def proxy_settings(self) -> config.ProxySettings: """Return the proxy settings in use by this component. Returns ------- hikari.config.ProxySettings The proxy settings in use. """ raise NotImplementedError @typing.runtime_checkable class EventManagerAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for a event manager-aware object. event manager-aware components are able to manage event listeners and waiters. """ __slots__: typing.Sequence[str] = () @property def event_manager(self) -> event_manager_.EventManager: """Return the event manager for this object. Returns ------- hikari.api.event_manager.EventManager The event manager component. """ raise NotImplementedError @typing.runtime_checkable class EntityFactoryAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for an entity factory-aware object. These components will be able to construct library entities. """ __slots__: typing.Sequence[str] = () @property def entity_factory(self) -> entity_factory_.EntityFactory: """Return the entity factory implementation for this object. Returns ------- hikari.api.entity_factory.EntityFactory The entity factory component. """ raise NotImplementedError @typing.runtime_checkable class ExecutorAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for an executor-aware object. These components will contain an `executor` attribute that may return a `concurrent.futures.Executor` or `builtins.None` if the default `asyncio` thread pool for the event loop is used. """ __slots__: typing.Sequence[str] = () @property def executor(self) -> typing.Optional[futures.Executor]: """Return the executor to use for blocking operations. This may return `builtins.None` if the default `asyncio` thread pool should be used instead. Returns ------- typing.Optional[concurrent.futures.Executor] The executor to use, or `builtins.None` to use the `asyncio` default instead. """ raise NotImplementedError @typing.runtime_checkable class EventFactoryAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for an event factory-aware object. These components are able to construct library events. """ __slots__: typing.Sequence[str] = () @property def event_factory(self) -> event_factory_.EventFactory: """Return the event factory component. Returns ------- hikari.api.event_factory.EventFactory The event factory component. """ raise NotImplementedError @typing.runtime_checkable class IntentsAware(fast_protocol.FastProtocolChecking, typing.Protocol): """A component that is aware of the application intents.""" __slots__: typing.Sequence[str] = () @property def intents(self) -> intents_.Intents: """Return the intents registered for the application. Returns ------- hikari.intents.Intents The intents registered on this application. """ raise NotImplementedError @typing.runtime_checkable class RESTAware( EntityFactoryAware, NetworkSettingsAware, ExecutorAware, fast_protocol.FastProtocolChecking, typing.Protocol ): """Structural supertype for a REST-aware object. These are able to perform REST API calls. """ __slots__: typing.Sequence[str] = () @property def rest(self) -> rest_.RESTClient: """Return the REST client to use for HTTP requests. Returns ------- hikari.api.rest.RESTClient The REST client to use. """ raise NotImplementedError @typing.runtime_checkable class VoiceAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for a voice-aware object. This is an object that provides a `voice` property to allow the creation of custom voice client instances. """ __slots__: typing.Sequence[str] = () @property def voice(self) -> voice_.VoiceComponent: """Return the voice connection manager component for this application. Returns ------- hikari.api.voice.VoiceComponent The voice component for the application. """ raise NotImplementedError @typing.runtime_checkable class ShardAware( IntentsAware, NetworkSettingsAware, ExecutorAware, VoiceAware, fast_protocol.FastProtocolChecking, typing.Protocol, ): """Structural supertype for a shard-aware object. These will expose a mapping of shards, the intents in use and the bot user object. """ __slots__: typing.Sequence[str] = () @property def heartbeat_latencies(self) -> typing.Mapping[int, float]: """Return a mapping of shard ID to heartbeat latency. Any shards that are not yet started will be `float('nan')`. Returns ------- typing.Mapping[builtins.int, builtins.float] Each shard ID mapped to the corresponding heartbeat latency. Each latency is measured in seconds. """ raise NotImplementedError @property def heartbeat_latency(self) -> float: """Return the average heartbeat latency of all started shards. If no shards are started, this will return `float('nan')`. Returns ------- builtins.float The average heartbeat latency of all started shards, or `float('nan')` if no shards are started. This is measured in seconds. """ raise NotImplementedError @property def shards(self) -> typing.Mapping[int, gateway_shard.GatewayShard]: """Return a mapping of shards in this application instance. Each shard ID is mapped to the corresponding shard instance. If the application has not started, it is acceptable to assume the result of this call will be an empty mapping. Returns ------- typing.Mapping[int, hikari.api.shard.GatewayShard] The shard mapping. """ raise NotImplementedError @property def shard_count(self) -> int: """Return the number of shards in the total application. This may not be the same as the size of `shards`. If the application is auto-sharded, this may be `0` until the shards are started. Returns ------- builtins.int The number of shards in the total application. """ raise NotImplementedError def get_me(self) -> typing.Optional[users_.OwnUser]: """Return the bot user, if known. This should be available as soon as the bot has fired the `hikari.events.lifetime_events.StartingEvent`. Until then, this may or may not be `builtins.None`. Returns ------- typing.Optional[hikari.users.OwnUser] The bot user, if known, otherwise `builtins.None`. """ raise NotImplementedError async def update_presence( self, *, status: undefined.UndefinedOr[presences.Status] = undefined.UNDEFINED, idle_since: undefined.UndefinedNoneOr[datetime.datetime] = undefined.UNDEFINED, activity: undefined.UndefinedNoneOr[presences.Activity] = undefined.UNDEFINED, afk: undefined.UndefinedOr[bool] = undefined.UNDEFINED, ) -> None: """Update the presence on all shards. This call will patch the presence on each shard. This means that unless you explicitly specify a parameter, the previous value will be retained. This means you do not have to track the global presence in your code. Other Parameters ---------------- idle_since : hikari.undefined.UndefinedNoneOr[datetime.datetime] The datetime that the user started being idle. If undefined, this will not be changed. afk : hikari.undefined.UndefinedOr[builtins.bool] If `builtins.True`, the user is marked as AFK. If `builtins.False`, the user is marked as being active. If undefined, this will not be changed. activity : hikari.undefined.UndefinedNoneOr[hikari.presences.Activity] The activity to appear to be playing. If undefined, this will not be changed. status : hikari.undefined.UndefinedOr[hikari.presences.Status] The web status to show. If undefined, this will not be changed. !!! note This will only send the update payloads to shards that are alive. Any shards that are not alive will cache the new presence for when they do start. !!! note If you want to set presences per shard, access the shard you wish to update (e.g. by using `GatewayBot.shards`), and call `hikari.api.shard.GatewayShard.update_presence` on that shard. This method is simply a facade to make performing this in bulk simpler. """ raise NotImplementedError async def update_voice_state( self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild], channel: typing.Optional[snowflakes.SnowflakeishOr[channels.GuildVoiceChannel]], *, self_mute: undefined.UndefinedOr[bool] = undefined.UNDEFINED, self_deaf: undefined.UndefinedOr[bool] = undefined.UNDEFINED, ) -> None: """Update the voice state for this bot in a given guild. Parameters ---------- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild] The guild or guild ID to update the voice state for. channel : typing.Optional[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]] The channel or channel ID to update the voice state for. If `builtins.None` then the bot will leave the voice channel that it is in for the given guild. self_mute : builtins.bool If specified and `builtins.True`, the bot will mute itself in that voice channel. If `builtins.False`, then it will unmute itself. self_deaf : builtins.bool If specified and `builtins.True`, the bot will deafen itself in that voice channel. If `builtins.False`, then it will undeafen itself. Raises ------ builtins.RuntimeError If the guild passed isn't covered by any of the shards in this sharded client. """ async def request_guild_members( self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild], *, include_presences: undefined.UndefinedOr[bool] = undefined.UNDEFINED, query: str = "", limit: int = 0, users: undefined.UndefinedOr[snowflakes.SnowflakeishSequence[users_.User]] = undefined.UNDEFINED, nonce: undefined.UndefinedOr[str] = undefined.UNDEFINED, ) -> None: """Request for a guild chunk. Parameters ---------- guild: hikari.guilds.Guild The guild to request chunk for. Other Parameters ---------------- include_presences: hikari.undefined.UndefinedOr[builtins.bool] If provided, whether to request presences. query: builtins.str If not `""`, request the members which username starts with the string. limit: builtins.int Maximum number of members to send matching the query. users: hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishSequence[hikari.users.User]] If provided, the users to request for. nonce: hikari.undefined.UndefinedOr[builtins.str] If provided, the nonce to be sent with guild chunks. !!! note To request the full list of members, set `query` to `""` (empty string) and `limit` to `0`. Raises ------ ValueError When trying to specify `users` with `query`/`limit`, if `limit` is not between 0 and 100, both inclusive or if `users` length is over 100. hikari.errors.MissingIntentError When trying to request presences without the `GUILD_MEMBERS` or when trying to request the full list of members without `GUILD_PRESENCES`. builtins.RuntimeError If the guild passed isn't covered by any of the shards in this sharded client. """ @typing.runtime_checkable class InteractionServerAware(RESTAware, EntityFactoryAware, fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for a interaction REST server-aware object.""" __slots__: typing.Sequence[str] = () @property def interaction_server(self) -> interaction_server_.InteractionServer: """Interaction server this app is bound to. Returns ------- hikari.api.interaction_server.InteractionServer The interaction server this app is bound to. """ raise NotImplementedError @typing.runtime_checkable class CacheAware(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for a cache-aware object. Any cache-aware objects are able to access the Discord application cache. """ __slots__: typing.Sequence[str] = () @property def cache(self) -> cache_.Cache: """Return the immutable cache implementation for this object. Returns ------- hikari.api.cache.Cache The cache component for this object. """ raise NotImplementedError @typing.runtime_checkable class Runnable(fast_protocol.FastProtocolChecking, typing.Protocol): """Structural super-type for an application which can be run independently.""" __slots__: typing.Sequence[str] = () @property def is_alive(self) -> bool: """Check whether the application is running or not. This is useful as some functions might raise `hikari.errors.ComponentStateConflictError` if this is `builtins.False`. Returns ------- builtins.bool Whether the bot is running or not. """ raise NotImplementedError async def close(self) -> None: """Kill the application by shutting all components down.""" async def join(self) -> None: """Wait indefinitely until the application closes. This can be placed in a task and cancelled without affecting the application runtime itself. Any exceptions raised by shards will be propagated to here. """ raise NotImplementedError def run(self) -> None: """Start the application and block until it's finished running.""" raise NotImplementedError async def start(self) -> None: """Start the application and then return.""" raise NotImplementedError @typing.runtime_checkable class GatewayBotAware( RESTAware, Runnable, ShardAware, EventFactoryAware, EventManagerAware, CacheAware, fast_protocol.FastProtocolChecking, typing.Protocol, ): """Structural supertype for a component that has all the gateway components.""" __slots__: typing.Sequence[str] = () async def join(self, until_close: bool = True) -> None: """Wait indefinitely until the application closes. This can be placed in a task and cancelled without affecting the application runtime itself. Any exceptions raised by shards will be propagated to here. Other Parameters ---------------- until_close : builtins.bool Defaults to `builtins.True`. If set, the waiter will stop as soon as a request for shut down is processed. This can allow you to break and begin closing your own resources. If `builtins.False`, then this will wait until all shards' tasks have died. """ raise NotImplementedError def run( self, *, activity: typing.Optional[presences.Activity] = None, afk: bool = False, close_passed_executor: bool = False, idle_since: typing.Optional[datetime.datetime] = None, ignore_session_start_limit: bool = False, large_threshold: int = 250, status: presences.Status = presences.Status.ONLINE, shard_ids: typing.Optional[typing.AbstractSet[int]] = None, shard_count: typing.Optional[int] = None, ) -> None: """Start the bot and block until it's finished running. Other Parameters ---------------- activity : typing.Optional[hikari.presences.Activity] The initial activity to display in the bot user presence, or `builtins.None` (default) to not show any. afk : builtins.bool The initial AFK state to display in the bot user presence, or `builtins.False` (default) to not show any. close_executor : builtins.bool Defaults to `builtins.False`. If `builtins.True`, any custom `concurrent.futures.Executor` passed to the constructor will be shut down when the application terminates. This does not affect the default executor associated with the event loop, and will not do anything if you do not provide a custom executor to the constructor. idle_since : typing.Optional[datetime.datetime] The `datetime.datetime` the user should be marked as being idle since, or `builtins.None` (default) to not show this. ignore_session_start_limit : builtins.bool Defaults to `builtins.False`. If `builtins.False`, then attempting to start more sessions than you are allowed in a 24 hour window will throw a `hikari.errors.GatewayError` rather than going ahead and hitting the IDENTIFY limit, which may result in your token being reset. Setting to `builtins.True` disables this behavior. large_threshold : builtins.int Threshold for members in a guild before it is treated as being "large" and no longer sending member details in the `GUILD CREATE` event. Defaults to `250`. shard_ids : typing.Optional[typing.AbstractSet[builtins.int]] The shard IDs to create shards for. If not `builtins.None`, then a non-`None` `shard_count` must ALSO be provided. Defaults to `builtins.None`, which means the Discord-recommended count is used for your application instead. shard_count : typing.Optional[builtins.int] The number of shards to use in the entire distributed application. Defaults to `builtins.None` which results in the count being determined dynamically on startup. status : hikari.presences.Status The initial status to show for the user presence on startup. Defaults to `hikari.presences.Status.ONLINE`. """ raise NotImplementedError async def start( self, *, activity: typing.Optional[presences.Activity] = None, afk: bool = False, idle_since: typing.Optional[datetime.datetime] = None, ignore_session_start_limit: bool = False, large_threshold: int = 250, shard_ids: typing.Optional[typing.AbstractSet[int]] = None, shard_count: typing.Optional[int] = None, status: presences.Status = presences.Status.ONLINE, ) -> None: """Start the bot, wait for all shards to become ready, and then return. Other Parameters ---------------- activity : typing.Optional[hikari.presences.Activity] The initial activity to display in the bot user presence, or `builtins.None` (default) to not show any. afk : builtins.bool The initial AFK state to display in the bot user presence, or `builtins.False` (default) to not show any. idle_since : typing.Optional[datetime.datetime] The `datetime.datetime` the user should be marked as being idle since, or `builtins.None` (default) to not show this. ignore_session_start_limit : builtins.bool Defaults to `builtins.False`. If `builtins.False`, then attempting to start more sessions than you are allowed in a 24 hour window will throw a `hikari.errors.GatewayError` rather than going ahead and hitting the IDENTIFY limit, which may result in your token being reset. Setting to `builtins.True` disables this behavior. large_threshold : builtins.int Threshold for members in a guild before it is treated as being "large" and no longer sending member details in the `GUILD CREATE` event. Defaults to `250`. shard_ids : typing.Optional[typing.AbstractSet[builtins.int]] The shard IDs to create shards for. If not `builtins.None`, then a non-`None` `shard_count` must ALSO be provided. Defaults to `builtins.None`, which means the Discord-recommended count is used for your application instead. shard_count : typing.Optional[builtins.int] The number of shards to use in the entire distributed application. Defaults to `builtins.None` which results in the count being determined dynamically on startup. status : hikari.presences.Status The initial status to show for the user presence on startup. Defaults to `hikari.presences.Status.ONLINE`. """ raise NotImplementedError @typing.runtime_checkable class RESTBotAware(InteractionServerAware, Runnable, fast_protocol.FastProtocolChecking, typing.Protocol): """Structural supertype for a component that has all the RESTful components.""" __slots__: typing.Sequence[str] = ()
Grimgrents2/WarsmashModEngine
core/src/com/etheller/warsmash/viewer5/handlers/mdx/Layer.java
<gh_stars>10-100 package com.etheller.warsmash.viewer5.handlers.mdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.hiveworkshop.rms.parsers.mdlx.AnimationMap; import com.hiveworkshop.rms.parsers.mdlx.MdlxLayer; /** * An MDX layer. */ public class Layer extends AnimatedObject { public int index; public int priorityPlane; public int filterMode; public int textureId; public int coordId; public float alpha; public int unshaded; public int sphereEnvironmentMap; public int twoSided; public int unfogged; public int noDepthTest; public int noDepthSet; public boolean depthMaskValue; public int blendSrc; public int blendDst; public boolean blended; public TextureAnimation textureAnimation; public Layer(final MdxModel model, final MdlxLayer layer, final int layerId, final int priorityPlane) { super(model, layer); final MdlxLayer.FilterMode filterMode = layer.getFilterMode(); final int textureAnimationId = layer.getTextureAnimationId(); final GL20 gl = model.viewer.gl; this.index = layerId; this.priorityPlane = priorityPlane; this.filterMode = filterMode.ordinal(); this.textureId = layer.getTextureId(); this.coordId = (int) layer.getCoordId(); this.alpha = layer.getAlpha(); final int flags = layer.getFlags(); this.unshaded = flags & 0x1; this.sphereEnvironmentMap = flags & 0x2; this.twoSided = flags & 0x10; this.unfogged = flags & 0x20; this.noDepthTest = flags & 0x40; this.noDepthSet = flags & 0x80; this.depthMaskValue = ((filterMode == MdlxLayer.FilterMode.NONE) || (filterMode == MdlxLayer.FilterMode.TRANSPARENT)); this.blendSrc = 0; this.blendDst = 0; this.blended = (filterMode.ordinal() > 1); if (this.blended) { final int[] result = FilterMode.layerFilterMode(filterMode); this.blendSrc = result[0]; this.blendDst = result[1]; } if (textureAnimationId != -1) { final TextureAnimation textureAnimation = model.getTextureAnimations().get(textureAnimationId); if (textureAnimation != null) { this.textureAnimation = textureAnimation; } } this.addVariants(AnimationMap.KMTA.getWar3id(), "alpha"); this.addVariants(AnimationMap.KMTF.getWar3id(), "textureId"); } public void bind(final ShaderProgram shader) { final GL20 gl = this.model.viewer.gl; // gl.uniform1f(shader.uniforms.u_unshaded, this.unshaded); shader.setUniformf("u_filterMode", this.filterMode); if (this.blended) { gl.glEnable(GL20.GL_BLEND); gl.glBlendFunc(this.blendSrc, this.blendDst); } else { gl.glDisable(GL20.GL_BLEND); } if (this.twoSided != 0) { gl.glDisable(GL20.GL_CULL_FACE); } else { gl.glEnable(GL20.GL_CULL_FACE); } if (this.noDepthTest != 0) { gl.glDisable(GL20.GL_DEPTH_TEST); } else { gl.glEnable(GL20.GL_DEPTH_TEST); } if (this.noDepthSet != 0) { gl.glDepthMask(false); } else { gl.glDepthMask(this.depthMaskValue); } } public void bindBlended(final ShaderProgram shader) { final GL20 gl = this.model.viewer.gl; // gl.uniform1f(shader.uniforms.u_unshaded, this.unshaded); shader.setUniformf("u_filterMode", this.filterMode); gl.glEnable(GL20.GL_BLEND); if ((this.blendSrc == 0) && (this.blendDst == 0)) { gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); } else { gl.glBlendFunc(this.blendSrc, this.blendDst); } if (this.twoSided != 0) { gl.glDisable(GL20.GL_CULL_FACE); } else { gl.glEnable(GL20.GL_CULL_FACE); } if (this.noDepthTest != 0) { gl.glDisable(GL20.GL_DEPTH_TEST); } else { gl.glEnable(GL20.GL_DEPTH_TEST); } if (this.noDepthSet != 0) { gl.glDepthMask(false); } else { gl.glDepthMask(this.depthMaskValue); } } public int getAlpha(final float[] out, final int sequence, final int frame, final int counter) { return this.getScalarValue(out, AnimationMap.KMTA.getWar3id(), sequence, frame, counter, this.alpha); } public int getTextureId(final long[] out, final int sequence, final int frame, final int counter) { return this.getScalarValue(out, AnimationMap.KMTF.getWar3id(), sequence, frame, counter, this.textureId); } }
jdiaz/snorkel
snorkel/components/query_details/query_details.js
<gh_stars>0 "use strict"; module.exports = { tagName: "div", className: "", client: function(options) { var created_str = new Date(options.created).toISOString(); var helpers = bootloader.require("app/client/views/helpers"); var that = this; var view = options.query.parsed.baseview || options.query.parsed.view; var count = 0; var w_count = 0; var results = options.query.results; if (view == "samples") { count = results.length; } if (view == "table" || view == "time" || view == "dist") { _.each(results, function(row) { count += row.count; w_count += row.weight; }); } if (!_.isNaN(count)) { that.$el.find(".count").text("Sample Count: " + helpers.count_format(count)); } if (!_.isNaN(w_count)) { that.$el.find(".weight").text("Weighted Samples: " + helpers.count_format(w_count)); } $C("timeago", {time: created_str }, function(cmp) { that.$el.find(".timestamp").append(cmp.$el); }); } };
bq/corbel-js2
src/build/with-polyfills.js
(function(root, factory) { 'use strict'; /* jshint unused: false */ if (typeof define === 'function' && define.amd) { define(['es6-promise'], function(promise) { promise.polyfill(); return factory(root); }); } else if (typeof module !== 'undefined' && module.exports) { var Promise = require('es6-promise').polyfill(); module.exports = factory.call(root); } else if (window !== undefined) { if (root.ES6Promise !== undefined && typeof root.ES6Promise.polyfill === 'function') { root.ES6Promise.polyfill(); } root.corbel = factory(root); } })(this, function(root) { 'use strict'; /* jshint unused: false */ // @include ../../bower_components/es6-promise/promise.js /** * corbel namespace * @exports corbel * @namespace */ var corbel = {}; //-----------Utils and libraries (exports into corbel namespace)--------------------------- // @include ../corbel.js // @include ../utils.js // @include ../validate.js // @include ../object.js // @include ../cryptography.js // @include ../jwt.js // @include ../request.js // @include ../services.js //----------corbel modules---------------- // @include ../config.js // @include ../iam/iam.js // @include ../iam/clientBuilder.js // @include ../iam/domainBuilder.js // @include ../iam/scopeBuilder.js // @include ../iam/tokenBuilder.js // @include ../iam/usernameBuilder.js // @include ../iam/usersBuilder.js // @include ../iam/groupsBuilder.js // @include ../iam/emailBuilder.js // @include ../assets/assets.js // @include ../assets/assets-builder.js // @include ../scheduler/scheduler.js // @include ../scheduler/schedulerBuilder.js // @include ../request-params/aggregation-builder.js // @include ../request-params/query-builder.js // @include ../request-params/page-builder.js // @include ../request-params/sort-builder.js // @include ../request-params/request-params-builder.js // @include ../resources/resources.js // @include ../resources/base-resource.js // @include ../resources/relation.js // @include ../resources/collection.js // @include ../resources/resource.js // @include ../oauth/oauth.js // @include ../oauth/authorizationBuilder.js // @include ../oauth/tokenBuilder.js // @include ../oauth/userBuilder.js // @include ../notifications/notifications.js // @include ../notifications/base-notifications.js // @include ../notifications/notificationsBuilder.js // @include ../notifications/notificationsDomainBuilder.js // @include ../notifications/notificationsTemplateBuilder.js // @include ../ec/ec.js // @include ../ec/orderBuilder.js // @include ../ec/productBuilder.js // @include ../evci/evci.js // @include ../evci/eventBuilder.js // @include ../borrow/borrow.js // @include ../borrow/borrowBuilder.js // @include ../borrow/userBuilder.js // @include ../borrow/lenderBuilder.js // @include ../composr/composr.js // @include ../composr/phraseBuilder.js // @include ../composr/requestBuilder.js // @include ../webfs/webfs.js // @include ../webfs/webfsBuilder.js // @include ../domain/domain.js return corbel; });
ishiura-compiler/CF3
testsuite/EXP_5/test1739.c
<reponame>ishiura-compiler/CF3 /* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" volatile int8_t x4 = 0; uint32_t x7 = 1122487749U; int16_t x9 = INT16_MIN; int32_t t3 = -415032444; int8_t x28 = 1; int16_t x32 = INT16_MIN; int64_t x35 = -1LL; volatile int32_t t8 = 519672751; uint64_t x46 = UINT64_MAX; uint64_t x47 = 113759LLU; uint64_t x48 = UINT64_MAX; static volatile uint32_t t10 = 193U; int8_t x63 = INT8_MIN; uint64_t x64 = 437223054300LLU; int8_t x72 = -1; volatile int32_t t14 = -234; int8_t x77 = INT8_MIN; volatile uint64_t t16 = 7648514LLU; volatile int32_t t17 = -1; static volatile uint64_t x97 = UINT64_MAX; volatile int16_t x100 = -1; int32_t x104 = INT32_MIN; static int8_t x114 = INT8_MIN; int8_t x127 = -1; volatile int32_t t22 = -670123; uint32_t x131 = 1293380637U; uint32_t x132 = UINT32_MAX; int64_t x136 = -1LL; volatile int32_t t25 = 1; int32_t x157 = 3143; int16_t x169 = INT16_MAX; uint8_t x171 = 40U; volatile int32_t x178 = INT32_MAX; static uint16_t x179 = UINT16_MAX; static volatile int32_t x198 = -1; int32_t x204 = -1; volatile int32_t t36 = 38; volatile uint32_t x205 = 28053U; volatile int64_t x211 = INT64_MIN; volatile int8_t x213 = 16; static volatile int8_t x215 = -1; int32_t t39 = 50348; volatile int32_t t40 = -56900; static int8_t x221 = 4; int32_t t41 = 0; int64_t x225 = 595212604LL; static int32_t x232 = INT32_MAX; static int64_t x238 = 18123099LL; int16_t x240 = INT16_MIN; int16_t x245 = 750; int8_t x249 = -1; int8_t x261 = INT8_MIN; static uint16_t x269 = 47U; static int32_t t51 = -243995774; static volatile uint64_t x276 = 2LLU; int16_t x280 = INT16_MIN; uint64_t x286 = 698368660777129LLU; static int32_t x290 = INT32_MAX; volatile int8_t x291 = 33; uint32_t x292 = 50U; int64_t x294 = 366399LL; int64_t x302 = -71683257523LL; static volatile int16_t x310 = INT16_MAX; volatile int32_t x319 = INT32_MAX; int8_t x320 = 1; static uint32_t x340 = 4991U; volatile uint64_t t67 = 62197277LLU; volatile int8_t x353 = 2; volatile int32_t x365 = INT32_MAX; uint32_t x366 = 398796U; int64_t x368 = -1LL; int64_t t70 = 649LL; uint32_t x385 = 25U; uint32_t x386 = UINT32_MAX; uint32_t t73 = 93U; int16_t x392 = -1; static volatile int32_t t74 = 1257; int8_t x414 = 0; volatile int32_t x419 = -128734; int16_t x424 = INT16_MIN; uint16_t x426 = 33U; int32_t t82 = 700900678; uint32_t x434 = 192099449U; static int16_t x436 = INT16_MIN; volatile int32_t x437 = INT32_MAX; int32_t x438 = -1; int32_t x440 = -1; volatile int64_t t87 = -249276553630LL; uint32_t t88 = 129091U; int64_t x459 = INT64_MIN; volatile uint32_t t92 = 1U; uint8_t x486 = 19U; int16_t x487 = -1; int8_t x488 = 24; uint32_t t94 = 8369480U; int16_t x494 = -2; volatile uint64_t t95 = 247029665364LLU; int32_t x497 = -1219; int16_t x509 = INT16_MIN; static volatile int16_t x513 = 1; uint32_t x515 = 103U; volatile int8_t x516 = -1; static uint16_t x520 = UINT16_MAX; volatile int64_t t100 = -12757LL; int32_t x529 = -1; volatile int32_t x538 = INT32_MIN; volatile uint32_t x544 = 14U; uint8_t x548 = 110U; volatile uint64_t x554 = 24889464388169395LLU; static volatile int8_t x555 = INT8_MIN; int16_t x559 = INT16_MAX; volatile uint64_t t106 = 1444LLU; int64_t x563 = INT64_MIN; static int64_t x564 = 527784805171806230LL; static int32_t x571 = 212615453; int32_t x576 = -18; volatile uint32_t t110 = 225U; volatile int32_t x577 = INT32_MAX; volatile int64_t t111 = 3793352667LL; int8_t x588 = -11; volatile uint64_t t114 = 56LLU; uint32_t t115 = 1U; static int32_t x602 = INT32_MAX; volatile uint64_t x608 = 14087572755776526LLU; int8_t x609 = -15; int16_t x612 = -1; int16_t x616 = -1; volatile int32_t t119 = 101; int32_t x622 = INT32_MIN; static int64_t t121 = -23257937160761948LL; int32_t x628 = INT32_MIN; int8_t x638 = INT8_MAX; int64_t x639 = INT64_MIN; static volatile int64_t x640 = INT64_MAX; static volatile uint32_t x641 = 222604U; int32_t x646 = -1; volatile uint64_t x650 = UINT64_MAX; uint32_t x659 = 14U; int64_t x668 = INT64_MIN; static int16_t x677 = -1; uint32_t x684 = UINT32_MAX; int16_t x685 = INT16_MIN; static uint8_t x697 = 2U; int32_t x704 = -1491103; int8_t x709 = INT8_MIN; uint16_t x714 = 1946U; int8_t x723 = 20; int8_t x733 = INT8_MAX; static uint64_t x739 = UINT64_MAX; static int64_t t147 = 1132776843LL; uint16_t x741 = UINT16_MAX; int64_t x766 = -1LL; int8_t x767 = -1; volatile int32_t t151 = 114; static int8_t x777 = INT8_MAX; int32_t t152 = 141830771; static uint8_t x789 = 1U; int32_t x817 = 55957118; volatile int32_t t160 = 1882249; static uint64_t x834 = UINT64_MAX; uint8_t x841 = UINT8_MAX; int64_t x843 = INT64_MAX; int32_t x846 = INT32_MAX; int8_t x847 = INT8_MAX; uint64_t x855 = 156221163LLU; int16_t x856 = INT16_MIN; int32_t x865 = 1; static volatile int32_t t170 = -135; int32_t x881 = -1500354; volatile uint64_t t173 = 1817LLU; uint16_t x894 = 30769U; uint8_t x895 = 0U; uint64_t x896 = 43407170LLU; volatile int32_t x899 = INT32_MIN; volatile int8_t x902 = -1; uint64_t x903 = 258522172273501LLU; int64_t t176 = INT64_MAX; int8_t x905 = 0; uint16_t x907 = 10U; int16_t x911 = -1; uint64_t x913 = UINT64_MAX; int16_t x915 = INT16_MAX; volatile int32_t x921 = -1; int16_t x924 = -1; int32_t t181 = 0; static uint32_t x933 = 25U; int16_t x935 = INT16_MIN; volatile int32_t x949 = -19365; static int64_t x952 = 56960LL; int16_t x955 = -1; volatile uint32_t t186 = 42078U; uint16_t x965 = UINT16_MAX; static uint32_t x966 = 4743865U; int32_t x967 = INT32_MIN; volatile int16_t x980 = INT16_MAX; int8_t x992 = -2; static int16_t x997 = -4072; static int32_t x999 = -1; volatile int16_t x1000 = -2; static volatile int32_t t198 = -22874302; void f0(void) { int32_t x1 = INT32_MAX; static volatile int32_t x2 = INT32_MIN; int32_t x3 = INT32_MIN; volatile int32_t t0 = 0; t0 = (x1*((x2>x3)|x4)); if (t0 != 0) { NG(); } else { ; } } void f1(void) { int64_t x5 = 1220615192LL; int64_t x6 = -37172360957LL; int16_t x8 = INT16_MIN; volatile int64_t t1 = 192524068LL; t1 = (x5*((x6>x7)|x8)); if (t1 != -39997118611456LL) { NG(); } else { ; } } void f2(void) { int8_t x10 = 9; int32_t x11 = INT32_MIN; int8_t x12 = INT8_MIN; int32_t t2 = -14427; t2 = (x9*((x10>x11)|x12)); if (t2 != 4161536) { NG(); } else { ; } } void f3(void) { int32_t x13 = 2; int8_t x14 = INT8_MIN; uint32_t x15 = 25994U; int16_t x16 = -1; t3 = (x13*((x14>x15)|x16)); if (t3 != -2) { NG(); } else { ; } } void f4(void) { volatile int8_t x21 = INT8_MIN; static volatile int8_t x22 = INT8_MIN; static int32_t x23 = INT32_MIN; uint16_t x24 = 2U; volatile int32_t t4 = -557322043; t4 = (x21*((x22>x23)|x24)); if (t4 != -384) { NG(); } else { ; } } void f5(void) { volatile int16_t x25 = INT16_MIN; uint16_t x26 = UINT16_MAX; int8_t x27 = -1; int32_t t5 = -1; t5 = (x25*((x26>x27)|x28)); if (t5 != -32768) { NG(); } else { ; } } void f6(void) { uint32_t x29 = 648626U; static int16_t x30 = INT16_MIN; int64_t x31 = -91840147773378LL; volatile uint32_t t6 = 11165995U; t6 = (x29*((x30>x31)|x32)); if (t6 != 221308338U) { NG(); } else { ; } } void f7(void) { uint16_t x33 = 32U; int64_t x34 = 65589140172LL; volatile uint64_t x36 = UINT64_MAX; uint64_t t7 = 240082797431064LLU; t7 = (x33*((x34>x35)|x36)); if (t7 != 18446744073709551584LLU) { NG(); } else { ; } } void f8(void) { uint8_t x37 = 92U; int16_t x38 = 451; volatile uint8_t x39 = 0U; volatile uint8_t x40 = 27U; t8 = (x37*((x38>x39)|x40)); if (t8 != 2484) { NG(); } else { ; } } void f9(void) { int16_t x45 = -4; uint64_t t9 = 285694433057100759LLU; t9 = (x45*((x46>x47)|x48)); if (t9 != 4LLU) { NG(); } else { ; } } void f10(void) { uint32_t x49 = 3191637U; volatile int32_t x50 = INT32_MAX; volatile uint64_t x51 = UINT64_MAX; int16_t x52 = INT16_MIN; t10 = (x49*((x50>x51)|x52)); if (t10 != 2790621184U) { NG(); } else { ; } } void f11(void) { int16_t x53 = INT16_MIN; int16_t x54 = INT16_MAX; int32_t x55 = INT32_MAX; uint32_t x56 = UINT32_MAX; volatile uint32_t t11 = 1026U; t11 = (x53*((x54>x55)|x56)); if (t11 != 32768U) { NG(); } else { ; } } void f12(void) { int8_t x61 = INT8_MIN; volatile uint64_t x62 = 20778171001950364LLU; volatile uint64_t t12 = 110925LLU; t12 = (x61*((x62>x63)|x64)); if (t12 != 18446688109158601216LLU) { NG(); } else { ; } } void f13(void) { uint64_t x69 = 815581092703LLU; int8_t x70 = INT8_MIN; volatile uint32_t x71 = UINT32_MAX; uint64_t t13 = 758586463194LLU; t13 = (x69*((x70>x71)|x72)); if (t13 != 18446743258128458913LLU) { NG(); } else { ; } } void f14(void) { static uint8_t x73 = 1U; static int8_t x74 = -1; static volatile uint32_t x75 = 954U; volatile uint16_t x76 = 5U; t14 = (x73*((x74>x75)|x76)); if (t14 != 5) { NG(); } else { ; } } void f15(void) { static uint64_t x78 = 6577998669338596LLU; volatile uint32_t x79 = 5724914U; int64_t x80 = -3940LL; int64_t t15 = -233912848261420052LL; t15 = (x77*((x78>x79)|x80)); if (t15 != 504192LL) { NG(); } else { ; } } void f16(void) { uint16_t x85 = 1U; int32_t x86 = -1; volatile int32_t x87 = INT32_MIN; volatile uint64_t x88 = 11923158LLU; t16 = (x85*((x86>x87)|x88)); if (t16 != 11923159LLU) { NG(); } else { ; } } void f17(void) { static int16_t x93 = -1299; static int16_t x94 = INT16_MAX; volatile int64_t x95 = -1LL; static uint16_t x96 = 9567U; t17 = (x93*((x94>x95)|x96)); if (t17 != -12427533) { NG(); } else { ; } } void f18(void) { static int8_t x98 = -1; volatile int16_t x99 = INT16_MIN; uint64_t t18 = 243849445910620LLU; t18 = (x97*((x98>x99)|x100)); if (t18 != 1LLU) { NG(); } else { ; } } void f19(void) { static uint64_t x101 = 41LLU; uint64_t x102 = UINT64_MAX; int16_t x103 = 96; uint64_t t19 = 136267831084165LLU; t19 = (x101*((x102>x103)|x104)); if (t19 != 18446743985662722089LLU) { NG(); } else { ; } } void f20(void) { int8_t x109 = -1; static volatile int8_t x110 = -1; static int64_t x111 = -1LL; int16_t x112 = 0; volatile int32_t t20 = 205; t20 = (x109*((x110>x111)|x112)); if (t20 != 0) { NG(); } else { ; } } void f21(void) { static uint32_t x113 = 210169U; uint8_t x115 = 26U; int32_t x116 = INT32_MAX; uint32_t t21 = 5U; t21 = (x113*((x114>x115)|x116)); if (t21 != 2147273479U) { NG(); } else { ; } } void f22(void) { static int16_t x125 = -1; int8_t x126 = INT8_MIN; int8_t x128 = 0; t22 = (x125*((x126>x127)|x128)); if (t22 != 0) { NG(); } else { ; } } void f23(void) { int64_t x129 = -1LL; uint64_t x130 = 44150374492LLU; int64_t t23 = 13356136LL; t23 = (x129*((x130>x131)|x132)); if (t23 != -4294967295LL) { NG(); } else { ; } } void f24(void) { int8_t x133 = -1; int8_t x134 = INT8_MIN; int16_t x135 = -1; int64_t t24 = 66815361645LL; t24 = (x133*((x134>x135)|x136)); if (t24 != 1LL) { NG(); } else { ; } } void f25(void) { uint16_t x137 = 14258U; int16_t x138 = 5284; uint8_t x139 = 27U; volatile int16_t x140 = -1; t25 = (x137*((x138>x139)|x140)); if (t25 != -14258) { NG(); } else { ; } } void f26(void) { int16_t x153 = -45; int64_t x154 = -1LL; int32_t x155 = -1; int32_t x156 = -5; int32_t t26 = -482315088; t26 = (x153*((x154>x155)|x156)); if (t26 != 225) { NG(); } else { ; } } void f27(void) { volatile uint64_t x158 = 110240485178883097LLU; uint8_t x159 = UINT8_MAX; int32_t x160 = -3; volatile int32_t t27 = -1; t27 = (x157*((x158>x159)|x160)); if (t27 != -9429) { NG(); } else { ; } } void f28(void) { int8_t x161 = INT8_MAX; int16_t x162 = INT16_MIN; uint16_t x163 = UINT16_MAX; volatile uint32_t x164 = 10593U; uint32_t t28 = 51U; t28 = (x161*((x162>x163)|x164)); if (t28 != 1345311U) { NG(); } else { ; } } void f29(void) { int64_t x165 = -48559LL; int16_t x166 = INT16_MIN; uint32_t x167 = 4808U; static volatile uint32_t x168 = 21818U; static int64_t t29 = 25520LL; t29 = (x165*((x166>x167)|x168)); if (t29 != -1059508821LL) { NG(); } else { ; } } void f30(void) { static volatile int32_t x170 = -1; uint8_t x172 = 82U; volatile int32_t t30 = 298734; t30 = (x169*((x170>x171)|x172)); if (t30 != 2686894) { NG(); } else { ; } } void f31(void) { uint64_t x177 = 247945LLU; int32_t x180 = INT32_MAX; volatile uint64_t t31 = 2126646540122895962LLU; t31 = (x177*((x178>x179)|x180)); if (t31 != 532457832855415LLU) { NG(); } else { ; } } void f32(void) { static uint64_t x181 = 8310298552294098805LLU; int8_t x182 = -1; int8_t x183 = INT8_MIN; volatile uint32_t x184 = 166704U; volatile uint64_t t32 = 1757192685393180LLU; t32 = (x181*((x182>x183)|x184)); if (t32 != 17840224600414925925LLU) { NG(); } else { ; } } void f33(void) { int8_t x185 = INT8_MIN; static volatile int32_t x186 = INT32_MAX; int64_t x187 = INT64_MIN; int64_t x188 = -224526793LL; static int64_t t33 = -17122505555LL; t33 = (x185*((x186>x187)|x188)); if (t33 != 28739429504LL) { NG(); } else { ; } } void f34(void) { static uint8_t x193 = UINT8_MAX; static int16_t x194 = -1; uint16_t x195 = 2346U; volatile uint64_t x196 = UINT64_MAX; uint64_t t34 = 1276207LLU; t34 = (x193*((x194>x195)|x196)); if (t34 != 18446744073709551361LLU) { NG(); } else { ; } } void f35(void) { int32_t x197 = -1; int64_t x199 = -8125902992621LL; int16_t x200 = -1; static int32_t t35 = -231772; t35 = (x197*((x198>x199)|x200)); if (t35 != 1) { NG(); } else { ; } } void f36(void) { int8_t x201 = INT8_MAX; int64_t x202 = -7LL; uint8_t x203 = 70U; t36 = (x201*((x202>x203)|x204)); if (t36 != -127) { NG(); } else { ; } } void f37(void) { uint16_t x206 = 142U; volatile int32_t x207 = INT32_MAX; uint64_t x208 = UINT64_MAX; volatile uint64_t t37 = 537893604LLU; t37 = (x205*((x206>x207)|x208)); if (t37 != 18446744073709523563LLU) { NG(); } else { ; } } void f38(void) { volatile int16_t x209 = -1; uint16_t x210 = 2U; static int64_t x212 = INT64_MIN; volatile int64_t t38 = INT64_MAX; t38 = (x209*((x210>x211)|x212)); if (t38 != INT64_MAX) { NG(); } else { ; } } void f39(void) { int8_t x214 = INT8_MAX; static int8_t x216 = INT8_MAX; t39 = (x213*((x214>x215)|x216)); if (t39 != 2032) { NG(); } else { ; } } void f40(void) { uint8_t x217 = 19U; int32_t x218 = INT32_MIN; int32_t x219 = INT32_MAX; uint16_t x220 = UINT16_MAX; t40 = (x217*((x218>x219)|x220)); if (t40 != 1245165) { NG(); } else { ; } } void f41(void) { static int64_t x222 = INT64_MIN; static volatile uint32_t x223 = 4470688U; static int8_t x224 = -1; t41 = (x221*((x222>x223)|x224)); if (t41 != -4) { NG(); } else { ; } } void f42(void) { uint32_t x226 = 1441344U; int64_t x227 = INT64_MIN; volatile uint16_t x228 = UINT16_MAX; int64_t t42 = -13377LL; t42 = (x225*((x226>x227)|x228)); if (t42 != 39007258003140LL) { NG(); } else { ; } } void f43(void) { uint32_t x229 = UINT32_MAX; uint64_t x230 = 1165576424328634LLU; int32_t x231 = 11378966; volatile uint32_t t43 = 3125U; t43 = (x229*((x230>x231)|x232)); if (t43 != 2147483649U) { NG(); } else { ; } } void f44(void) { int8_t x233 = INT8_MIN; int8_t x234 = -17; static int16_t x235 = INT16_MIN; uint32_t x236 = UINT32_MAX; uint32_t t44 = 5922U; t44 = (x233*((x234>x235)|x236)); if (t44 != 128U) { NG(); } else { ; } } void f45(void) { volatile int8_t x237 = INT8_MAX; int16_t x239 = INT16_MAX; int32_t t45 = 338397; t45 = (x237*((x238>x239)|x240)); if (t45 != -4161409) { NG(); } else { ; } } void f46(void) { static int8_t x246 = 10; static volatile int32_t x247 = INT32_MIN; static uint32_t x248 = 173U; volatile uint32_t t46 = 110142U; t46 = (x245*((x246>x247)|x248)); if (t46 != 129750U) { NG(); } else { ; } } void f47(void) { int8_t x250 = INT8_MAX; static volatile int64_t x251 = 105LL; static int32_t x252 = -6476; int32_t t47 = 508644; t47 = (x249*((x250>x251)|x252)); if (t47 != 6475) { NG(); } else { ; } } void f48(void) { volatile int32_t x257 = INT32_MAX; static uint16_t x258 = 4U; uint64_t x259 = 913134256263LLU; int64_t x260 = -1LL; int64_t t48 = -1LL; t48 = (x257*((x258>x259)|x260)); if (t48 != -2147483647LL) { NG(); } else { ; } } void f49(void) { volatile uint32_t x262 = 2930U; int8_t x263 = 1; static uint32_t x264 = 12U; static volatile uint32_t t49 = 864678026U; t49 = (x261*((x262>x263)|x264)); if (t49 != 4294965632U) { NG(); } else { ; } } void f50(void) { int16_t x265 = INT16_MAX; int32_t x266 = -1; int16_t x267 = -1; int64_t x268 = -538454754LL; int64_t t50 = 2162401067484687LL; t50 = (x265*((x266>x267)|x268)); if (t50 != -17643546924318LL) { NG(); } else { ; } } void f51(void) { uint32_t x270 = UINT32_MAX; volatile uint32_t x271 = UINT32_MAX; int8_t x272 = INT8_MIN; t51 = (x269*((x270>x271)|x272)); if (t51 != -6016) { NG(); } else { ; } } void f52(void) { int8_t x273 = -1; int64_t x274 = INT64_MIN; int16_t x275 = -7142; static volatile uint64_t t52 = 143158828LLU; t52 = (x273*((x274>x275)|x276)); if (t52 != 18446744073709551614LLU) { NG(); } else { ; } } void f53(void) { volatile int16_t x277 = INT16_MIN; static uint8_t x278 = 2U; volatile int16_t x279 = 61; volatile int32_t t53 = 101959233; t53 = (x277*((x278>x279)|x280)); if (t53 != 1073741824) { NG(); } else { ; } } void f54(void) { uint8_t x281 = UINT8_MAX; int32_t x282 = -1; volatile int32_t x283 = INT32_MAX; volatile int32_t x284 = -678; static int32_t t54 = -12; t54 = (x281*((x282>x283)|x284)); if (t54 != -172890) { NG(); } else { ; } } void f55(void) { uint8_t x285 = 28U; uint32_t x287 = 3009173U; uint8_t x288 = 21U; int32_t t55 = 78; t55 = (x285*((x286>x287)|x288)); if (t55 != 588) { NG(); } else { ; } } void f56(void) { int32_t x289 = 20; uint32_t t56 = 20390U; t56 = (x289*((x290>x291)|x292)); if (t56 != 1020U) { NG(); } else { ; } } void f57(void) { int16_t x293 = INT16_MIN; volatile int32_t x295 = INT32_MAX; int16_t x296 = INT16_MAX; int32_t t57 = -5; t57 = (x293*((x294>x295)|x296)); if (t57 != -1073709056) { NG(); } else { ; } } void f58(void) { int32_t x301 = -1; int32_t x303 = INT32_MIN; int32_t x304 = 3939199; static int32_t t58 = 118264621; t58 = (x301*((x302>x303)|x304)); if (t58 != -3939199) { NG(); } else { ; } } void f59(void) { static uint16_t x305 = 2403U; int8_t x306 = INT8_MIN; int32_t x307 = -1; static volatile int32_t x308 = -295082; static int32_t t59 = 179; t59 = (x305*((x306>x307)|x308)); if (t59 != -709082046) { NG(); } else { ; } } void f60(void) { int16_t x309 = INT16_MAX; int64_t x311 = INT64_MIN; int16_t x312 = INT16_MIN; int32_t t60 = -1506828; t60 = (x309*((x310>x311)|x312)); if (t60 != -1073676289) { NG(); } else { ; } } void f61(void) { int8_t x313 = -1; int32_t x314 = -13913; volatile uint64_t x315 = UINT64_MAX; int8_t x316 = INT8_MIN; volatile int32_t t61 = -680612390; t61 = (x313*((x314>x315)|x316)); if (t61 != 128) { NG(); } else { ; } } void f62(void) { int8_t x317 = -1; int8_t x318 = -1; static int32_t t62 = 243803; t62 = (x317*((x318>x319)|x320)); if (t62 != -1) { NG(); } else { ; } } void f63(void) { int16_t x321 = -1; static uint8_t x322 = 3U; uint64_t x323 = UINT64_MAX; int16_t x324 = 372; static int32_t t63 = 4711; t63 = (x321*((x322>x323)|x324)); if (t63 != -372) { NG(); } else { ; } } void f64(void) { int8_t x325 = -1; static int32_t x326 = INT32_MAX; int32_t x327 = INT32_MIN; int8_t x328 = -14; static int32_t t64 = 3711011; t64 = (x325*((x326>x327)|x328)); if (t64 != 13) { NG(); } else { ; } } void f65(void) { volatile uint32_t x329 = 771720625U; static int16_t x330 = INT16_MIN; int32_t x331 = INT32_MAX; int8_t x332 = INT8_MIN; uint32_t t65 = 1133240607U; t65 = (x329*((x330>x331)|x332)); if (t65 != 4007808U) { NG(); } else { ; } } void f66(void) { int32_t x337 = INT32_MAX; volatile int8_t x338 = -1; int64_t x339 = INT64_MAX; volatile uint32_t t66 = 299048352U; t66 = (x337*((x338>x339)|x340)); if (t66 != 2147478657U) { NG(); } else { ; } } void f67(void) { int16_t x341 = INT16_MIN; static int16_t x342 = INT16_MIN; uint8_t x343 = 78U; uint64_t x344 = UINT64_MAX; t67 = (x341*((x342>x343)|x344)); if (t67 != 32768LLU) { NG(); } else { ; } } void f68(void) { int64_t x354 = INT64_MIN; int64_t x355 = -13251199982615414LL; int8_t x356 = -19; volatile int32_t t68 = -23865; t68 = (x353*((x354>x355)|x356)); if (t68 != -38) { NG(); } else { ; } } void f69(void) { uint32_t x361 = 1U; volatile uint16_t x362 = 381U; static uint64_t x363 = 575LLU; uint8_t x364 = 4U; static uint32_t t69 = 22032540U; t69 = (x361*((x362>x363)|x364)); if (t69 != 4U) { NG(); } else { ; } } void f70(void) { volatile int32_t x367 = INT32_MIN; t70 = (x365*((x366>x367)|x368)); if (t70 != -2147483647LL) { NG(); } else { ; } } void f71(void) { static volatile uint8_t x369 = 107U; int8_t x370 = INT8_MIN; uint16_t x371 = 6U; int64_t x372 = -1LL; int64_t t71 = -885598122031977218LL; t71 = (x369*((x370>x371)|x372)); if (t71 != -107LL) { NG(); } else { ; } } void f72(void) { uint32_t x381 = 3U; static int8_t x382 = INT8_MIN; int32_t x383 = INT32_MIN; int32_t x384 = -1927; static volatile uint32_t t72 = 112U; t72 = (x381*((x382>x383)|x384)); if (t72 != 4294961515U) { NG(); } else { ; } } void f73(void) { int64_t x387 = 387329LL; uint32_t x388 = 49U; t73 = (x385*((x386>x387)|x388)); if (t73 != 1225U) { NG(); } else { ; } } void f74(void) { int32_t x389 = INT32_MAX; static int64_t x390 = 14070LL; volatile int32_t x391 = INT32_MIN; t74 = (x389*((x390>x391)|x392)); if (t74 != -2147483647) { NG(); } else { ; } } void f75(void) { static int8_t x393 = INT8_MAX; int16_t x394 = INT16_MIN; static int8_t x395 = INT8_MIN; uint16_t x396 = 3296U; int32_t t75 = -46; t75 = (x393*((x394>x395)|x396)); if (t75 != 418592) { NG(); } else { ; } } void f76(void) { uint16_t x401 = 108U; volatile int16_t x402 = INT16_MAX; uint16_t x403 = 45U; int8_t x404 = INT8_MIN; int32_t t76 = -93946; t76 = (x401*((x402>x403)|x404)); if (t76 != -13716) { NG(); } else { ; } } void f77(void) { int16_t x405 = -1; static uint32_t x406 = 284103797U; static uint16_t x407 = 1U; volatile int8_t x408 = INT8_MIN; int32_t t77 = 2310916; t77 = (x405*((x406>x407)|x408)); if (t77 != 127) { NG(); } else { ; } } void f78(void) { int8_t x413 = 57; int32_t x415 = -41136; static uint64_t x416 = 438762LLU; volatile uint64_t t78 = 1064641LLU; t78 = (x413*((x414>x415)|x416)); if (t78 != 25009491LLU) { NG(); } else { ; } } void f79(void) { int32_t x417 = -1; int16_t x418 = 838; uint8_t x420 = 100U; volatile int32_t t79 = 15838043; t79 = (x417*((x418>x419)|x420)); if (t79 != -101) { NG(); } else { ; } } void f80(void) { uint16_t x421 = 1426U; int16_t x422 = INT16_MIN; volatile uint64_t x423 = 322698913473565LLU; int32_t t80 = -205658840; t80 = (x421*((x422>x423)|x424)); if (t80 != -46725742) { NG(); } else { ; } } void f81(void) { int64_t x425 = -334953559LL; uint64_t x427 = UINT64_MAX; uint8_t x428 = 1U; volatile int64_t t81 = -7222209446LL; t81 = (x425*((x426>x427)|x428)); if (t81 != -334953559LL) { NG(); } else { ; } } void f82(void) { int32_t x429 = -232; static uint32_t x430 = 1591961874U; int16_t x431 = -1; volatile uint8_t x432 = 33U; t82 = (x429*((x430>x431)|x432)); if (t82 != -7656) { NG(); } else { ; } } void f83(void) { int16_t x433 = INT16_MIN; int8_t x435 = -1; static int32_t t83 = -115324536; t83 = (x433*((x434>x435)|x436)); if (t83 != 1073741824) { NG(); } else { ; } } void f84(void) { static uint16_t x439 = UINT16_MAX; static volatile int32_t t84 = -73631; t84 = (x437*((x438>x439)|x440)); if (t84 != -2147483647) { NG(); } else { ; } } void f85(void) { uint16_t x441 = 0U; volatile int32_t x442 = -1; int16_t x443 = -7989; volatile int16_t x444 = -1; volatile int32_t t85 = -569462; t85 = (x441*((x442>x443)|x444)); if (t85 != 0) { NG(); } else { ; } } void f86(void) { int8_t x445 = INT8_MIN; uint32_t x446 = 32U; int8_t x447 = INT8_MIN; uint8_t x448 = 2U; int32_t t86 = 901; t86 = (x445*((x446>x447)|x448)); if (t86 != -256) { NG(); } else { ; } } void f87(void) { int64_t x449 = 5120360818LL; static int8_t x450 = -1; static int8_t x451 = -1; uint16_t x452 = 6328U; t87 = (x449*((x450>x451)|x452)); if (t87 != 32401643256304LL) { NG(); } else { ; } } void f88(void) { volatile uint32_t x453 = UINT32_MAX; volatile int16_t x454 = INT16_MIN; uint8_t x455 = 43U; uint16_t x456 = UINT16_MAX; t88 = (x453*((x454>x455)|x456)); if (t88 != 4294901761U) { NG(); } else { ; } } void f89(void) { uint16_t x457 = 23U; volatile uint16_t x458 = 18885U; uint8_t x460 = 4U; volatile int32_t t89 = 1829; t89 = (x457*((x458>x459)|x460)); if (t89 != 115) { NG(); } else { ; } } void f90(void) { int64_t x465 = -1LL; int32_t x466 = -10845; static volatile int16_t x467 = INT16_MAX; int16_t x468 = -34; static int64_t t90 = -2613400LL; t90 = (x465*((x466>x467)|x468)); if (t90 != 34LL) { NG(); } else { ; } } void f91(void) { int64_t x469 = INT64_MAX; static int16_t x470 = 8161; uint8_t x471 = UINT8_MAX; volatile int32_t x472 = -1; int64_t t91 = -104241441425LL; t91 = (x469*((x470>x471)|x472)); if (t91 != -9223372036854775807LL) { NG(); } else { ; } } void f92(void) { uint16_t x473 = UINT16_MAX; uint16_t x474 = 8134U; int16_t x475 = INT16_MIN; uint32_t x476 = 1290298U; t92 = (x473*((x474>x475)|x476)); if (t92 != 2955366341U) { NG(); } else { ; } } void f93(void) { volatile int64_t x477 = 6881319614LL; static uint8_t x478 = UINT8_MAX; static volatile int16_t x479 = -1; static volatile uint32_t x480 = 6U; static volatile int64_t t93 = -24439020941149LL; t93 = (x477*((x478>x479)|x480)); if (t93 != 48169237298LL) { NG(); } else { ; } } void f94(void) { uint32_t x485 = 561U; t94 = (x485*((x486>x487)|x488)); if (t94 != 14025U) { NG(); } else { ; } } void f95(void) { volatile int16_t x493 = INT16_MIN; int32_t x495 = INT32_MAX; static volatile uint64_t x496 = UINT64_MAX; t95 = (x493*((x494>x495)|x496)); if (t95 != 32768LLU) { NG(); } else { ; } } void f96(void) { int32_t x498 = INT32_MIN; volatile uint64_t x499 = UINT64_MAX; int32_t x500 = -548; int32_t t96 = -381968795; t96 = (x497*((x498>x499)|x500)); if (t96 != 668012) { NG(); } else { ; } } void f97(void) { static volatile int8_t x510 = INT8_MAX; int32_t x511 = -1; uint16_t x512 = UINT16_MAX; static int32_t t97 = 6102; t97 = (x509*((x510>x511)|x512)); if (t97 != -2147450880) { NG(); } else { ; } } void f98(void) { uint64_t x514 = UINT64_MAX; int32_t t98 = 5; t98 = (x513*((x514>x515)|x516)); if (t98 != -1) { NG(); } else { ; } } void f99(void) { volatile int16_t x517 = 11055; uint64_t x518 = 0LLU; volatile uint8_t x519 = UINT8_MAX; int32_t t99 = -281; t99 = (x517*((x518>x519)|x520)); if (t99 != 724489425) { NG(); } else { ; } } void f100(void) { int32_t x521 = INT32_MIN; uint32_t x522 = UINT32_MAX; uint16_t x523 = 3U; static int64_t x524 = -1LL; t100 = (x521*((x522>x523)|x524)); if (t100 != 2147483648LL) { NG(); } else { ; } } void f101(void) { uint64_t x530 = 804755260900223937LLU; uint64_t x531 = 1434LLU; int8_t x532 = -1; volatile int32_t t101 = 11711; t101 = (x529*((x530>x531)|x532)); if (t101 != 1) { NG(); } else { ; } } void f102(void) { static uint64_t x537 = 1343967812LLU; int64_t x539 = -958510528967082958LL; int16_t x540 = INT16_MAX; volatile uint64_t t102 = 14568156108101845LLU; t102 = (x537*((x538>x539)|x540)); if (t102 != 44037793295804LLU) { NG(); } else { ; } } void f103(void) { int16_t x541 = -1; int32_t x542 = INT32_MIN; volatile int64_t x543 = -1LL; static uint32_t t103 = 1836U; t103 = (x541*((x542>x543)|x544)); if (t103 != 4294967282U) { NG(); } else { ; } } void f104(void) { static volatile int64_t x545 = -1LL; uint32_t x546 = UINT32_MAX; uint8_t x547 = UINT8_MAX; int64_t t104 = 7472782LL; t104 = (x545*((x546>x547)|x548)); if (t104 != -111LL) { NG(); } else { ; } } void f105(void) { static int64_t x553 = 136394849LL; int32_t x556 = INT32_MIN; volatile int64_t t105 = 55101521314824389LL; t105 = (x553*((x554>x555)|x556)); if (t105 != -292905707898929152LL) { NG(); } else { ; } } void f106(void) { static uint64_t x557 = UINT64_MAX; int32_t x558 = -136663380; uint16_t x560 = 12U; t106 = (x557*((x558>x559)|x560)); if (t106 != 18446744073709551604LLU) { NG(); } else { ; } } void f107(void) { int32_t x561 = -1; int16_t x562 = INT16_MIN; volatile int64_t t107 = 669505013144093LL; t107 = (x561*((x562>x563)|x564)); if (t107 != -527784805171806231LL) { NG(); } else { ; } } void f108(void) { uint16_t x565 = 472U; int16_t x566 = INT16_MIN; static int8_t x567 = 6; uint8_t x568 = UINT8_MAX; volatile int32_t t108 = 1786655; t108 = (x565*((x566>x567)|x568)); if (t108 != 120360) { NG(); } else { ; } } void f109(void) { int16_t x569 = -1096; int32_t x570 = -58; uint64_t x572 = 1669237545694LLU; static volatile uint64_t t109 = 202842627909526LLU; t109 = (x569*((x570>x571)|x572)); if (t109 != 18444914589359470992LLU) { NG(); } else { ; } } void f110(void) { uint32_t x573 = UINT32_MAX; static int64_t x574 = -1LL; static int16_t x575 = -930; t110 = (x573*((x574>x575)|x576)); if (t110 != 17U) { NG(); } else { ; } } void f111(void) { int16_t x578 = -1; int16_t x579 = -35; int64_t x580 = 209643814LL; t111 = (x577*((x578>x579)|x580)); if (t111 != 450206664407193305LL) { NG(); } else { ; } } void f112(void) { static int64_t x585 = 2588875LL; int64_t x586 = -359258LL; volatile uint8_t x587 = 20U; int64_t t112 = 5431862087LL; t112 = (x585*((x586>x587)|x588)); if (t112 != -28477625LL) { NG(); } else { ; } } void f113(void) { static volatile int16_t x589 = -1; uint32_t x590 = UINT32_MAX; volatile uint16_t x591 = 4547U; int64_t x592 = 106LL; volatile int64_t t113 = 3030821LL; t113 = (x589*((x590>x591)|x592)); if (t113 != -107LL) { NG(); } else { ; } } void f114(void) { volatile int64_t x593 = INT64_MAX; int32_t x594 = 7; int32_t x595 = INT32_MAX; uint64_t x596 = 55976698LLU; t114 = (x593*((x594>x595)|x596)); if (t114 != 18446744073653574918LLU) { NG(); } else { ; } } void f115(void) { int16_t x597 = -87; uint8_t x598 = 40U; int8_t x599 = 24; uint32_t x600 = UINT32_MAX; t115 = (x597*((x598>x599)|x600)); if (t115 != 87U) { NG(); } else { ; } } void f116(void) { volatile uint16_t x601 = UINT16_MAX; int8_t x603 = -5; uint32_t x604 = 21594742U; volatile uint32_t t116 = 678U; t116 = (x601*((x602>x603)|x604)); if (t116 != 2167242121U) { NG(); } else { ; } } void f117(void) { int8_t x605 = INT8_MAX; uint64_t x606 = UINT64_MAX; int64_t x607 = -1LL; uint64_t t117 = 1539200307090722LLU; t117 = (x605*((x606>x607)|x608)); if (t117 != 1789121739983618802LLU) { NG(); } else { ; } } void f118(void) { int16_t x610 = -13; static int16_t x611 = INT16_MAX; int32_t t118 = 23241; t118 = (x609*((x610>x611)|x612)); if (t118 != 15) { NG(); } else { ; } } void f119(void) { int32_t x613 = -1; static int16_t x614 = -1; uint8_t x615 = 48U; t119 = (x613*((x614>x615)|x616)); if (t119 != 1) { NG(); } else { ; } } void f120(void) { static int8_t x617 = 42; int16_t x618 = INT16_MIN; int32_t x619 = INT32_MIN; int16_t x620 = 4658; int32_t t120 = -127446; t120 = (x617*((x618>x619)|x620)); if (t120 != 195678) { NG(); } else { ; } } void f121(void) { static volatile int16_t x621 = INT16_MIN; volatile int16_t x623 = -14; int64_t x624 = -1LL; t121 = (x621*((x622>x623)|x624)); if (t121 != 32768LL) { NG(); } else { ; } } void f122(void) { static uint8_t x625 = 0U; int32_t x626 = INT32_MAX; int16_t x627 = INT16_MIN; volatile int32_t t122 = -522179787; t122 = (x625*((x626>x627)|x628)); if (t122 != 0) { NG(); } else { ; } } void f123(void) { uint32_t x629 = UINT32_MAX; uint8_t x630 = UINT8_MAX; static int8_t x631 = -1; static volatile int32_t x632 = INT32_MIN; volatile uint32_t t123 = 1340U; t123 = (x629*((x630>x631)|x632)); if (t123 != 2147483647U) { NG(); } else { ; } } void f124(void) { volatile uint16_t x633 = 39U; volatile uint16_t x634 = UINT16_MAX; int16_t x635 = -1; static uint8_t x636 = UINT8_MAX; int32_t t124 = 203; t124 = (x633*((x634>x635)|x636)); if (t124 != 9945) { NG(); } else { ; } } void f125(void) { int64_t x637 = -1LL; int64_t t125 = -44002506887212LL; t125 = (x637*((x638>x639)|x640)); if (t125 != -9223372036854775807LL) { NG(); } else { ; } } void f126(void) { static int32_t x642 = 5156; int16_t x643 = INT16_MAX; uint16_t x644 = 15286U; uint32_t t126 = 21103U; t126 = (x641*((x642>x643)|x644)); if (t126 != 3402724744U) { NG(); } else { ; } } void f127(void) { uint8_t x645 = 0U; static uint64_t x647 = UINT64_MAX; volatile uint64_t x648 = 12104018LLU; volatile uint64_t t127 = 160LLU; t127 = (x645*((x646>x647)|x648)); if (t127 != 0LLU) { NG(); } else { ; } } void f128(void) { volatile int16_t x649 = -1; int64_t x651 = INT64_MIN; int8_t x652 = INT8_MIN; static int32_t t128 = 536795; t128 = (x649*((x650>x651)|x652)); if (t128 != 127) { NG(); } else { ; } } void f129(void) { int16_t x657 = INT16_MIN; volatile uint64_t x658 = UINT64_MAX; int8_t x660 = -1; volatile int32_t t129 = 5654; t129 = (x657*((x658>x659)|x660)); if (t129 != 32768) { NG(); } else { ; } } void f130(void) { int64_t x661 = -82LL; uint8_t x662 = 0U; static uint8_t x663 = 14U; uint16_t x664 = 723U; int64_t t130 = -6119398363LL; t130 = (x661*((x662>x663)|x664)); if (t130 != -59286LL) { NG(); } else { ; } } void f131(void) { uint64_t x665 = 3678914486559011LLU; int16_t x666 = INT16_MIN; int32_t x667 = INT32_MAX; static uint64_t t131 = 2LLU; t131 = (x665*((x666>x667)|x668)); if (t131 != 9223372036854775808LLU) { NG(); } else { ; } } void f132(void) { int16_t x673 = INT16_MIN; uint8_t x674 = 0U; volatile uint8_t x675 = UINT8_MAX; uint8_t x676 = 17U; int32_t t132 = 340591334; t132 = (x673*((x674>x675)|x676)); if (t132 != -557056) { NG(); } else { ; } } void f133(void) { static int64_t x678 = 107551061317296123LL; uint64_t x679 = 1560LLU; uint8_t x680 = 71U; int32_t t133 = -3; t133 = (x677*((x678>x679)|x680)); if (t133 != -71) { NG(); } else { ; } } void f134(void) { volatile int8_t x681 = -28; int64_t x682 = INT64_MAX; static uint16_t x683 = 6U; volatile uint32_t t134 = 62U; t134 = (x681*((x682>x683)|x684)); if (t134 != 28U) { NG(); } else { ; } } void f135(void) { static int32_t x686 = 103702357; static int16_t x687 = 2409; volatile int16_t x688 = INT16_MIN; int32_t t135 = 239504; t135 = (x685*((x686>x687)|x688)); if (t135 != 1073709056) { NG(); } else { ; } } void f136(void) { uint8_t x693 = 62U; int32_t x694 = INT32_MAX; int16_t x695 = -109; static volatile uint8_t x696 = 5U; volatile int32_t t136 = 129973140; t136 = (x693*((x694>x695)|x696)); if (t136 != 310) { NG(); } else { ; } } void f137(void) { int16_t x698 = -6860; int16_t x699 = -1; int8_t x700 = 7; volatile int32_t t137 = 51; t137 = (x697*((x698>x699)|x700)); if (t137 != 14) { NG(); } else { ; } } void f138(void) { uint16_t x701 = 102U; uint32_t x702 = UINT32_MAX; static uint32_t x703 = 4738U; static int32_t t138 = 599; t138 = (x701*((x702>x703)|x704)); if (t138 != -152092506) { NG(); } else { ; } } void f139(void) { volatile uint16_t x705 = 17U; uint32_t x706 = 987691468U; uint16_t x707 = 65U; int8_t x708 = -3; volatile int32_t t139 = -47389088; t139 = (x705*((x706>x707)|x708)); if (t139 != -51) { NG(); } else { ; } } void f140(void) { volatile uint8_t x710 = 79U; int64_t x711 = INT64_MIN; uint64_t x712 = 304571996227LLU; volatile uint64_t t140 = 86786LLU; t140 = (x709*((x710>x711)|x712)); if (t140 != 18446705088494034560LLU) { NG(); } else { ; } } void f141(void) { int16_t x713 = INT16_MIN; int8_t x715 = INT8_MIN; int16_t x716 = INT16_MIN; volatile int32_t t141 = 1656796; t141 = (x713*((x714>x715)|x716)); if (t141 != 1073709056) { NG(); } else { ; } } void f142(void) { static int8_t x717 = -1; volatile int16_t x718 = INT16_MIN; uint16_t x719 = 8116U; int16_t x720 = INT16_MAX; int32_t t142 = -110435216; t142 = (x717*((x718>x719)|x720)); if (t142 != -32767) { NG(); } else { ; } } void f143(void) { static uint32_t x721 = UINT32_MAX; int8_t x722 = 0; int8_t x724 = INT8_MAX; volatile uint32_t t143 = 9810U; t143 = (x721*((x722>x723)|x724)); if (t143 != 4294967169U) { NG(); } else { ; } } void f144(void) { uint64_t x725 = 67705536613187LLU; volatile int16_t x726 = INT16_MIN; uint16_t x727 = UINT16_MAX; static int8_t x728 = INT8_MIN; static volatile uint64_t t144 = 8LLU; t144 = (x725*((x726>x727)|x728)); if (t144 != 18438077765023063680LLU) { NG(); } else { ; } } void f145(void) { uint64_t x729 = 712225550274LLU; static int16_t x730 = -1; int16_t x731 = -1; static int64_t x732 = 1919730914615188302LL; uint64_t t145 = 29577568858084836LLU; t145 = (x729*((x730>x731)|x732)); if (t145 != 10700243097060115228LLU) { NG(); } else { ; } } void f146(void) { static int8_t x734 = INT8_MIN; int64_t x735 = INT64_MAX; int8_t x736 = INT8_MIN; volatile int32_t t146 = -64; t146 = (x733*((x734>x735)|x736)); if (t146 != -16256) { NG(); } else { ; } } void f147(void) { int64_t x737 = -1LL; volatile uint8_t x738 = UINT8_MAX; static int16_t x740 = INT16_MIN; t147 = (x737*((x738>x739)|x740)); if (t147 != 32768LL) { NG(); } else { ; } } void f148(void) { uint32_t x742 = UINT32_MAX; volatile uint8_t x743 = 0U; uint64_t x744 = 208269066566856483LLU; uint64_t t148 = 3657651258099LLU; t148 = (x741*((x742>x743)|x744)); if (t148 != 16769406987580969181LLU) { NG(); } else { ; } } void f149(void) { volatile uint64_t x749 = UINT64_MAX; uint32_t x750 = UINT32_MAX; int8_t x751 = INT8_MIN; uint8_t x752 = 0U; volatile uint64_t t149 = UINT64_MAX; t149 = (x749*((x750>x751)|x752)); if (t149 != UINT64_MAX) { NG(); } else { ; } } void f150(void) { int32_t x753 = -1; static volatile int64_t x754 = INT64_MIN; volatile int16_t x755 = INT16_MIN; int8_t x756 = -1; volatile int32_t t150 = 0; t150 = (x753*((x754>x755)|x756)); if (t150 != 1) { NG(); } else { ; } } void f151(void) { volatile uint8_t x765 = 10U; static volatile uint8_t x768 = UINT8_MAX; t151 = (x765*((x766>x767)|x768)); if (t151 != 2550) { NG(); } else { ; } } void f152(void) { volatile int64_t x778 = 8877974836705357LL; volatile uint8_t x779 = UINT8_MAX; static volatile int16_t x780 = -2361; t152 = (x777*((x778>x779)|x780)); if (t152 != -299847) { NG(); } else { ; } } void f153(void) { static int16_t x781 = -5; int64_t x782 = 634857444LL; int16_t x783 = -14426; static int16_t x784 = 17; int32_t t153 = 632; t153 = (x781*((x782>x783)|x784)); if (t153 != -85) { NG(); } else { ; } } void f154(void) { uint64_t x785 = UINT64_MAX; int64_t x786 = -1LL; int16_t x787 = INT16_MIN; int64_t x788 = -1LL; volatile uint64_t t154 = 109326LLU; t154 = (x785*((x786>x787)|x788)); if (t154 != 1LLU) { NG(); } else { ; } } void f155(void) { static int8_t x790 = INT8_MAX; int8_t x791 = INT8_MAX; int8_t x792 = INT8_MAX; static int32_t t155 = 54; t155 = (x789*((x790>x791)|x792)); if (t155 != 127) { NG(); } else { ; } } void f156(void) { volatile int16_t x793 = INT16_MIN; int8_t x794 = -1; int32_t x795 = 6395877; int16_t x796 = INT16_MAX; volatile int32_t t156 = 186; t156 = (x793*((x794>x795)|x796)); if (t156 != -1073709056) { NG(); } else { ; } } void f157(void) { volatile int8_t x797 = -11; uint32_t x798 = 4284U; uint32_t x799 = 1026922901U; volatile int32_t x800 = -2010; int32_t t157 = 4; t157 = (x797*((x798>x799)|x800)); if (t157 != 22110) { NG(); } else { ; } } void f158(void) { int32_t x809 = INT32_MIN; int32_t x810 = -1; uint32_t x811 = UINT32_MAX; uint64_t x812 = UINT64_MAX; volatile uint64_t t158 = 278222147LLU; t158 = (x809*((x810>x811)|x812)); if (t158 != 2147483648LLU) { NG(); } else { ; } } void f159(void) { uint16_t x813 = UINT16_MAX; uint32_t x814 = 43U; static int8_t x815 = 0; static uint16_t x816 = 52U; static volatile int32_t t159 = -28419; t159 = (x813*((x814>x815)|x816)); if (t159 != 3473355) { NG(); } else { ; } } void f160(void) { static int16_t x818 = -1; int32_t x819 = 115478335; int16_t x820 = -1; t160 = (x817*((x818>x819)|x820)); if (t160 != -55957118) { NG(); } else { ; } } void f161(void) { static int8_t x821 = -1; volatile int32_t x822 = INT32_MIN; uint32_t x823 = 1203U; int8_t x824 = -1; volatile int32_t t161 = -32288637; t161 = (x821*((x822>x823)|x824)); if (t161 != 1) { NG(); } else { ; } } void f162(void) { static volatile int64_t x833 = -1LL; uint64_t x835 = 4LLU; volatile int32_t x836 = -73; static int64_t t162 = -3338507586195721LL; t162 = (x833*((x834>x835)|x836)); if (t162 != 73LL) { NG(); } else { ; } } void f163(void) { int16_t x837 = -1; int32_t x838 = INT32_MIN; int8_t x839 = -1; int8_t x840 = -1; int32_t t163 = -22; t163 = (x837*((x838>x839)|x840)); if (t163 != 1) { NG(); } else { ; } } void f164(void) { static volatile int16_t x842 = INT16_MIN; int8_t x844 = -1; volatile int32_t t164 = -6810; t164 = (x841*((x842>x843)|x844)); if (t164 != -255) { NG(); } else { ; } } void f165(void) { int8_t x845 = INT8_MIN; uint64_t x848 = 135627928642LLU; uint64_t t165 = 1287001LLU; t165 = (x845*((x846>x847)|x848)); if (t165 != 18446726713334685312LLU) { NG(); } else { ; } } void f166(void) { uint64_t x849 = 679409LLU; int64_t x850 = 0LL; int16_t x851 = INT16_MAX; uint16_t x852 = UINT16_MAX; volatile uint64_t t166 = 7089709273797397LLU; t166 = (x849*((x850>x851)|x852)); if (t166 != 44525068815LLU) { NG(); } else { ; } } void f167(void) { volatile int32_t x853 = -1; uint64_t x854 = UINT64_MAX; static int32_t t167 = 287587544; t167 = (x853*((x854>x855)|x856)); if (t167 != 32767) { NG(); } else { ; } } void f168(void) { volatile int64_t x857 = -1LL; int32_t x858 = INT32_MIN; volatile int8_t x859 = -1; int8_t x860 = -7; int64_t t168 = -7401379319227LL; t168 = (x857*((x858>x859)|x860)); if (t168 != 7LL) { NG(); } else { ; } } void f169(void) { int16_t x866 = INT16_MIN; int32_t x867 = INT32_MAX; volatile uint16_t x868 = 1773U; volatile int32_t t169 = 18659; t169 = (x865*((x866>x867)|x868)); if (t169 != 1773) { NG(); } else { ; } } void f170(void) { int16_t x873 = INT16_MIN; uint64_t x874 = 136770213021457LLU; int16_t x875 = 16366; int32_t x876 = -1; t170 = (x873*((x874>x875)|x876)); if (t170 != 32768) { NG(); } else { ; } } void f171(void) { uint16_t x877 = UINT16_MAX; int16_t x878 = 26; int64_t x879 = INT64_MIN; volatile uint32_t x880 = 2176326U; volatile uint32_t t171 = 15081471U; t171 = (x877*((x878>x879)|x880)); if (t171 != 891669177U) { NG(); } else { ; } } void f172(void) { int32_t x882 = INT32_MIN; volatile int64_t x883 = INT64_MIN; static volatile uint8_t x884 = 54U; volatile int32_t t172 = -14429; t172 = (x881*((x882>x883)|x884)); if (t172 != -82519470) { NG(); } else { ; } } void f173(void) { uint64_t x885 = 1515LLU; volatile int8_t x886 = INT8_MIN; uint8_t x887 = 3U; int16_t x888 = INT16_MIN; t173 = (x885*((x886>x887)|x888)); if (t173 != 18446744073659908096LLU) { NG(); } else { ; } } void f174(void) { int32_t x893 = INT32_MAX; static uint64_t t174 = 93041451877789LLU; t174 = (x893*((x894>x895)|x896)); if (t174 != 93216189885032637LLU) { NG(); } else { ; } } void f175(void) { volatile int8_t x897 = -57; uint16_t x898 = UINT16_MAX; static int8_t x900 = -1; int32_t t175 = 32433; t175 = (x897*((x898>x899)|x900)); if (t175 != 57) { NG(); } else { ; } } void f176(void) { volatile uint8_t x901 = 1U; int64_t x904 = INT64_MAX; t176 = (x901*((x902>x903)|x904)); if (t176 != INT64_MAX) { NG(); } else { ; } } void f177(void) { static int8_t x906 = INT8_MAX; uint8_t x908 = 15U; volatile int32_t t177 = 19250; t177 = (x905*((x906>x907)|x908)); if (t177 != 0) { NG(); } else { ; } } void f178(void) { int32_t x909 = -1; volatile int8_t x910 = INT8_MAX; uint8_t x912 = UINT8_MAX; int32_t t178 = 2657; t178 = (x909*((x910>x911)|x912)); if (t178 != -255) { NG(); } else { ; } } void f179(void) { volatile uint8_t x914 = UINT8_MAX; volatile uint32_t x916 = 1666519U; uint64_t t179 = 424783578143LLU; t179 = (x913*((x914>x915)|x916)); if (t179 != 18446744073707885097LLU) { NG(); } else { ; } } void f180(void) { int32_t x917 = INT32_MIN; volatile int32_t x918 = 769484646; volatile int16_t x919 = -1; int8_t x920 = 0; int32_t t180 = INT32_MIN; t180 = (x917*((x918>x919)|x920)); if (t180 != INT32_MIN) { NG(); } else { ; } } void f181(void) { int16_t x922 = INT16_MAX; volatile int8_t x923 = INT8_MIN; t181 = (x921*((x922>x923)|x924)); if (t181 != 1) { NG(); } else { ; } } void f182(void) { uint8_t x929 = 58U; volatile int16_t x930 = -1; int32_t x931 = -1; int8_t x932 = -1; int32_t t182 = -42358; t182 = (x929*((x930>x931)|x932)); if (t182 != -58) { NG(); } else { ; } } void f183(void) { uint32_t x934 = UINT32_MAX; uint32_t x936 = UINT32_MAX; uint32_t t183 = 13856U; t183 = (x933*((x934>x935)|x936)); if (t183 != 4294967271U) { NG(); } else { ; } } void f184(void) { int8_t x941 = 9; uint16_t x942 = UINT16_MAX; uint64_t x943 = UINT64_MAX; uint64_t x944 = 2672111862122LLU; volatile uint64_t t184 = 84270302700758LLU; t184 = (x941*((x942>x943)|x944)); if (t184 != 24049006759098LLU) { NG(); } else { ; } } void f185(void) { uint32_t x950 = 1U; int32_t x951 = -996733; volatile int64_t t185 = -4782055536LL; t185 = (x949*((x950>x951)|x952)); if (t185 != -1103030400LL) { NG(); } else { ; } } void f186(void) { uint32_t x953 = UINT32_MAX; static uint16_t x954 = 8862U; static uint32_t x956 = 28767U; t186 = (x953*((x954>x955)|x956)); if (t186 != 4294938529U) { NG(); } else { ; } } void f187(void) { uint16_t x957 = 28U; static uint16_t x958 = UINT16_MAX; static int16_t x959 = -1; uint64_t x960 = UINT64_MAX; volatile uint64_t t187 = 251007581922LLU; t187 = (x957*((x958>x959)|x960)); if (t187 != 18446744073709551588LLU) { NG(); } else { ; } } void f188(void) { int8_t x968 = INT8_MIN; int32_t t188 = 16251; t188 = (x965*((x966>x967)|x968)); if (t188 != -8388480) { NG(); } else { ; } } void f189(void) { int8_t x969 = -1; static int16_t x970 = -6; int16_t x971 = -2; int32_t x972 = INT32_MAX; volatile int32_t t189 = -716247; t189 = (x969*((x970>x971)|x972)); if (t189 != -2147483647) { NG(); } else { ; } } void f190(void) { uint16_t x973 = 12428U; uint16_t x974 = UINT16_MAX; int32_t x975 = INT32_MIN; int64_t x976 = -1LL; static int64_t t190 = 83248181250LL; t190 = (x973*((x974>x975)|x976)); if (t190 != -12428LL) { NG(); } else { ; } } void f191(void) { int16_t x977 = -1; uint8_t x978 = 3U; volatile int64_t x979 = -2393775149LL; int32_t t191 = 9754297; t191 = (x977*((x978>x979)|x980)); if (t191 != -32767) { NG(); } else { ; } } void f192(void) { volatile int32_t x981 = 88; uint16_t x982 = 1303U; int8_t x983 = -30; uint16_t x984 = 6544U; int32_t t192 = 22883111; t192 = (x981*((x982>x983)|x984)); if (t192 != 575960) { NG(); } else { ; } } void f193(void) { uint64_t x989 = UINT64_MAX; uint32_t x990 = 1893240U; int8_t x991 = -1; volatile uint64_t t193 = 939851940001178LLU; t193 = (x989*((x990>x991)|x992)); if (t193 != 2LLU) { NG(); } else { ; } } void f194(void) { int8_t x993 = -1; volatile int8_t x994 = INT8_MIN; uint8_t x995 = 11U; uint8_t x996 = UINT8_MAX; volatile int32_t t194 = -9547; t194 = (x993*((x994>x995)|x996)); if (t194 != -255) { NG(); } else { ; } } void f195(void) { int64_t x998 = -23910267LL; volatile int32_t t195 = 60798627; t195 = (x997*((x998>x999)|x1000)); if (t195 != 8144) { NG(); } else { ; } } void f196(void) { int8_t x1005 = 45; int8_t x1006 = -1; uint64_t x1007 = 1468246656179084LLU; uint32_t x1008 = UINT32_MAX; uint32_t t196 = 16U; t196 = (x1005*((x1006>x1007)|x1008)); if (t196 != 4294967251U) { NG(); } else { ; } } void f197(void) { static uint16_t x1009 = 88U; static int8_t x1010 = INT8_MIN; int16_t x1011 = 0; volatile int8_t x1012 = 0; int32_t t197 = 393396; t197 = (x1009*((x1010>x1011)|x1012)); if (t197 != 0) { NG(); } else { ; } } void f198(void) { int8_t x1013 = INT8_MIN; volatile uint16_t x1014 = 57U; volatile uint8_t x1015 = UINT8_MAX; int8_t x1016 = -1; t198 = (x1013*((x1014>x1015)|x1016)); if (t198 != 128) { NG(); } else { ; } } void f199(void) { static volatile uint8_t x1017 = 26U; static int64_t x1018 = -59321046LL; int16_t x1019 = 536; static uint32_t x1020 = 29042U; static uint32_t t199 = 67903U; t199 = (x1017*((x1018>x1019)|x1020)); if (t199 != 755092U) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
MrAhmedSayedAli/TinyORM
include/orm/concerns/logsqueries.hpp
#pragma once #ifndef ORM_CONCERNS_LOGSQUERIES_HPP #define ORM_CONCERNS_LOGSQUERIES_HPP #include "orm/macros/systemheader.hpp" TINY_SYSTEM_HEADER #include <QtSql/QSqlQuery> #include <memory> #include <optional> #include "orm/macros/export.hpp" #include "orm/types/log.hpp" TINYORM_BEGIN_COMMON_NAMESPACE namespace Orm { class DatabaseConnection; namespace Concerns { /*! Logs executed queries to the console. */ class SHAREDLIB_EXPORT LogsQueries { Q_DISABLE_COPY(LogsQueries) public: /*! Default constructor. */ inline LogsQueries() = default; /*! Virtual destructor, to pass -Weffc++. */ inline virtual ~LogsQueries() = default; /*! Log a query into the connection's query log. */ inline void logQuery(const QSqlQuery &query, std::optional<qint64> elapsed) const; /*! Log a query into the connection's query log. */ inline void logQuery(const std::tuple<int, QSqlQuery> &queryResult, std::optional<qint64> elapsed) const; /*! Log a query into the connection's query log in the pretending mode. */ void logQueryForPretend(const QString &query, const QVector<QVariant> &bindings) const; /*! Log a transaction query into the connection's query log. */ void logTransactionQuery(const QString &query, std::optional<qint64> elapsed) const; /*! Log a transaction query into the connection's query log in the pretending mode. */ void logTransactionQueryForPretend(const QString &query) const; /*! Get the connection query log. */ inline std::shared_ptr<QVector<Log>> getQueryLog() const; /*! Clear the query log. */ void flushQueryLog(); /*! Enable the query log on the connection. */ void enableQueryLog(); /*! Disable the query log on the connection. */ inline void disableQueryLog(); /*! Determine whether we're logging queries. */ inline bool logging() const; /*! The current order value for a query log record. */ inline static std::size_t getQueryLogOrder(); /*! Determine whether debugging SQL queries is enabled/disabled (logging to the console using qDebug()). */ inline bool debugSql() const; /*! Disable debugging SQL queries (logging to the console using qDebug()). */ inline void disableDebugSql(); /*! Enable debugging SQL queries (logging to the console using qDebug()). */ inline void enableDebugSql(); protected: /*! Execute the given callback in "dry run" mode. */ QVector<Log> withFreshQueryLog(const std::function<QVector<Log>()> &callback); /*! Indicates if changes have been made to the database. */ bool m_recordsModified = false; /*! All of the queries run against the connection. */ std::shared_ptr<QVector<Log>> m_queryLog = nullptr; /*! ID of the query log record. */ inline static std::atomic<std::size_t> m_queryLogId = 0; #ifdef TINYORM_DEBUG_SQL /*! Indicates whether logging of sql queries is enabled. */ bool m_debugSql = true; #else /*! Indicates whether logging of sql queries is enabled. */ bool m_debugSql = false; #endif private: /*! Log a query into the connection's query log. */ void logQueryInternal(const QSqlQuery &query, std::optional<qint64> elapsed) const; /*! Convert a named bindings map to the positional bindings vector. */ QVector<QVariant> convertNamedToPositionalBindings(QVariantMap &&bindings) const; /*! Dynamic cast *this to the DatabaseConnection & derived type. */ const DatabaseConnection &databaseConnection() const; /*! Indicates whether queries are being logged (private intentionally). */ bool m_loggingQueries = false; /*! All of the queries run against the connection. */ std::shared_ptr<QVector<Log>> m_queryLogForPretend = nullptr; }; /* public */ void LogsQueries::logQuery( const QSqlQuery &queryResult, std::optional<qint64> elapsed) const { logQueryInternal(queryResult, elapsed); } void LogsQueries::logQuery( const std::tuple<int, QSqlQuery> &queryResult, std::optional<qint64> elapsed) const { logQueryInternal(std::get<1>(queryResult), elapsed); } std::shared_ptr<QVector<Log>> LogsQueries::getQueryLog() const { return m_queryLog; } void LogsQueries::disableQueryLog() { m_loggingQueries = false; } bool LogsQueries::logging() const { return m_loggingQueries; } std::size_t LogsQueries::getQueryLogOrder() { return m_queryLogId; } bool LogsQueries::debugSql() const { return m_debugSql; } void LogsQueries::disableDebugSql() { m_debugSql = false; } void LogsQueries::enableDebugSql() { m_debugSql = true; } } // namespace Concerns } // namespace Orm TINYORM_END_COMMON_NAMESPACE #endif // ORM_CONCERNS_LOGSQUERIES_HPP
ckclark/leetcode
go/valid-mountain-array.go
<gh_stars>0 package leetcode func validMountainArray(A []int) bool { n := len(A) left, right := 0, n-1 for i := 0; i < n-1 && A[i+1] > A[i]; i++ { left = i + 1 } for i := n - 1; i > 0 && A[i] < A[i-1]; i-- { right = i - 1 } return left != 0 && right != n-1 && left == right }
ScalablyTyped/SlinkyTyped
j/jsforce/src/main/scala/typingsSlinky/jsforce/queryMod.scala
<reponame>ScalablyTyped/SlinkyTyped package typingsSlinky.jsforce import typingsSlinky.jsforce.jsforceStrings.ASC import typingsSlinky.jsforce.jsforceStrings.DESC import typingsSlinky.jsforce.recordResultMod.RecordResult import typingsSlinky.node.NodeJS.WritableStream import typingsSlinky.node.anon.End import typingsSlinky.node.streamMod.Readable import typingsSlinky.node.streamMod.ReadableOptions import typingsSlinky.std.Promise import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object queryMod { @JSImport("jsforce/query", "ExplainInfo") @js.native class ExplainInfo () extends StObject @JSImport("jsforce/query", "Query") @js.native class Query[T] () extends Readable with Promise[T] { def this(opts: ReadableOptions) = this() def del(): js.Any = js.native def del(callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit]): js.Any = js.native def del( `type`: js.UndefOr[scala.Nothing], callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit] ): js.Any = js.native def del(`type`: String): js.Any = js.native def del(`type`: String, callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit]): js.Any = js.native def delete(): js.Any = js.native def delete(callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit]): js.Any = js.native def delete( `type`: js.UndefOr[scala.Nothing], callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit] ): js.Any = js.native def delete(`type`: String): js.Any = js.native def delete(`type`: String, callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit]): js.Any = js.native def destroy(callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit]): js.Promise[js.Array[RecordResult]] = js.native def destroy( `type`: js.UndefOr[scala.Nothing], callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit] ): js.Promise[js.Array[RecordResult]] = js.native def destroy(`type`: String): js.Promise[js.Array[RecordResult]] = js.native def destroy(`type`: String, callback: js.Function2[/* err */ js.Error, /* ret */ RecordResult, Unit]): js.Promise[js.Array[RecordResult]] = js.native @JSName("destroy") def destroy_Promise(): js.Promise[js.Array[RecordResult]] = js.native def end(): Query[T] = js.native def exec(): Query[T] = js.native def exec( options: js.UndefOr[scala.Nothing], callback: js.Function2[/* err */ js.Error, /* records */ js.Array[T], Unit] ): Query[T] = js.native def exec(options: ExecuteOptions): Query[T] = js.native def exec( options: ExecuteOptions, callback: js.Function2[/* err */ js.Error, /* records */ js.Array[T], Unit] ): Query[T] = js.native def execute(): Query[T] = js.native def execute( options: js.UndefOr[scala.Nothing], callback: js.Function2[/* err */ js.Error, /* records */ js.Array[T], Unit] ): Query[T] = js.native def execute(options: ExecuteOptions): Query[T] = js.native def execute( options: ExecuteOptions, callback: js.Function2[/* err */ js.Error, /* records */ js.Array[T], Unit] ): Query[T] = js.native def explain(): js.Promise[ExplainInfo] = js.native def explain(callback: js.Function2[/* err */ js.Error, /* info */ ExplainInfo, Unit]): js.Promise[ExplainInfo] = js.native def filter(filter: js.Object): Query[T] = js.native def hint(hint: js.Object): Query[T] = js.native def include(include: String): Query[T] = js.native def limit(value: Double): Query[T] = js.native def map(callback: js.Function1[/* currentValue */ js.Object, Unit]): js.Promise[_] = js.native def maxFetch(value: Double): Query[T] = js.native def offset(value: Double): Query[T] = js.native /* InferMemberOverrides */ override def pipe[T /* <: WritableStream */](destination: T): T = js.native /* InferMemberOverrides */ override def pipe[T /* <: WritableStream */](destination: T, options: End): T = js.native def run(): Query[T] = js.native def run( options: js.UndefOr[scala.Nothing], callback: js.Function2[/* err */ js.Error, /* records */ js.Array[T], Unit] ): Query[T] = js.native def run(options: ExecuteOptions): Query[T] = js.native def run( options: ExecuteOptions, callback: js.Function2[/* err */ js.Error, /* records */ js.Array[T], Unit] ): Query[T] = js.native def scanAll(value: Boolean): Query[T] = js.native def select(fields: String): Query[T] = js.native def select(fields: js.Array[String]): Query[T] = js.native def select(fields: js.Object): Query[T] = js.native def skip(value: Double): Query[T] = js.native def sort(keyOrList: String): Query[T] = js.native def sort(keyOrList: String, direction: Double): Query[T] = js.native def sort(keyOrList: js.Array[js.Object]): Query[T] = js.native def sort(keyOrList: js.Array[js.Object], direction: Double): Query[T] = js.native def sort(keyOrList: js.Object): Query[T] = js.native def sort(keyOrList: js.Object, direction: Double): Query[T] = js.native @JSName("sort") def sort_ASC(keyOrList: String, direction: ASC): Query[T] = js.native @JSName("sort") def sort_ASC(keyOrList: js.Array[js.Object], direction: ASC): Query[T] = js.native @JSName("sort") def sort_ASC(keyOrList: js.Object, direction: ASC): Query[T] = js.native @JSName("sort") def sort_DESC(keyOrList: String, direction: DESC): Query[T] = js.native @JSName("sort") def sort_DESC(keyOrList: js.Array[js.Object], direction: DESC): Query[T] = js.native @JSName("sort") def sort_DESC(keyOrList: js.Object, direction: DESC): Query[T] = js.native def thenCall(): Query[T] = js.native def thenCall(callback: js.Function2[/* err */ js.Error, /* records */ T, Unit]): Query[T] = js.native def toSOQL(callback: js.Function2[/* err */ js.Error, /* soql */ String, Unit]): js.Promise[String] = js.native @JSName(js.Symbol.toStringTag) var toStringTag_Query: typingsSlinky.jsforce.jsforceStrings.Promise = js.native def update( mapping: js.Any, callback: js.Function2[/* err */ js.Error, /* records */ js.Array[RecordResult], Unit] ): js.Promise[js.Array[RecordResult]] = js.native def update( mapping: js.Any, `type`: String, callback: js.Function2[/* err */ js.Error, /* records */ js.Array[RecordResult], Unit] ): js.Promise[js.Array[RecordResult]] = js.native def where(conditions: String): Query[T] = js.native def where(conditions: js.Object): Query[T] = js.native } @js.native trait ExecuteOptions extends StObject { var autoFetch: js.UndefOr[Boolean] = js.native var headers: js.UndefOr[js.Object] = js.native var maxFetch: js.UndefOr[Double] = js.native var scanAll: js.UndefOr[Boolean] = js.native } object ExecuteOptions { @scala.inline def apply(): ExecuteOptions = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[ExecuteOptions] } @scala.inline implicit class ExecuteOptionsMutableBuilder[Self <: ExecuteOptions] (val x: Self) extends AnyVal { @scala.inline def setAutoFetch(value: Boolean): Self = StObject.set(x, "autoFetch", value.asInstanceOf[js.Any]) @scala.inline def setAutoFetchUndefined: Self = StObject.set(x, "autoFetch", js.undefined) @scala.inline def setHeaders(value: js.Object): Self = StObject.set(x, "headers", value.asInstanceOf[js.Any]) @scala.inline def setHeadersUndefined: Self = StObject.set(x, "headers", js.undefined) @scala.inline def setMaxFetch(value: Double): Self = StObject.set(x, "maxFetch", value.asInstanceOf[js.Any]) @scala.inline def setMaxFetchUndefined: Self = StObject.set(x, "maxFetch", js.undefined) @scala.inline def setScanAll(value: Boolean): Self = StObject.set(x, "scanAll", value.asInstanceOf[js.Any]) @scala.inline def setScanAllUndefined: Self = StObject.set(x, "scanAll", js.undefined) } } @js.native trait QueryResult[T] extends StObject { var done: Boolean = js.native var nextRecordsUrl: js.UndefOr[String] = js.native var records: js.Array[T] = js.native var totalSize: Double = js.native } object QueryResult { @scala.inline def apply[T](done: Boolean, records: js.Array[T], totalSize: Double): QueryResult[T] = { val __obj = js.Dynamic.literal(done = done.asInstanceOf[js.Any], records = records.asInstanceOf[js.Any], totalSize = totalSize.asInstanceOf[js.Any]) __obj.asInstanceOf[QueryResult[T]] } @scala.inline implicit class QueryResultMutableBuilder[Self <: QueryResult[_], T] (val x: Self with QueryResult[T]) extends AnyVal { @scala.inline def setDone(value: Boolean): Self = StObject.set(x, "done", value.asInstanceOf[js.Any]) @scala.inline def setNextRecordsUrl(value: String): Self = StObject.set(x, "nextRecordsUrl", value.asInstanceOf[js.Any]) @scala.inline def setNextRecordsUrlUndefined: Self = StObject.set(x, "nextRecordsUrl", js.undefined) @scala.inline def setRecords(value: js.Array[T]): Self = StObject.set(x, "records", value.asInstanceOf[js.Any]) @scala.inline def setRecordsVarargs(value: T*): Self = StObject.set(x, "records", js.Array(value :_*)) @scala.inline def setTotalSize(value: Double): Self = StObject.set(x, "totalSize", value.asInstanceOf[js.Any]) } } }
AaronFriel/pulumi-aws-native
sdk/go/aws/elasticache/user.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package elasticache import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Resource Type definition for AWS::ElastiCache::User type User struct { pulumi.CustomResourceState // Access permissions string used for this user account. AccessString pulumi.StringPtrOutput `pulumi:"accessString"` // The Amazon Resource Name (ARN) of the user account. Arn pulumi.StringOutput `pulumi:"arn"` // Must be redis. Engine UserEngineOutput `pulumi:"engine"` // Indicates a password is not required for this user account. NoPasswordRequired pulumi.BoolPtrOutput `pulumi:"noPasswordRequired"` // Passwords used for this user account. You can create up to two passwords for each user. Passwords pulumi.StringArrayOutput `pulumi:"passwords"` // Indicates the user status. Can be "active", "modifying" or "deleting". Status pulumi.StringOutput `pulumi:"status"` // The ID of the user. UserId pulumi.StringOutput `pulumi:"userId"` // The username of the user. UserName pulumi.StringOutput `pulumi:"userName"` } // NewUser registers a new resource with the given unique name, arguments, and options. func NewUser(ctx *pulumi.Context, name string, args *UserArgs, opts ...pulumi.ResourceOption) (*User, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.Engine == nil { return nil, errors.New("invalid value for required argument 'Engine'") } if args.UserId == nil { return nil, errors.New("invalid value for required argument 'UserId'") } var resource User err := ctx.RegisterResource("aws-native:elasticache:User", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetUser gets an existing User resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetUser(ctx *pulumi.Context, name string, id pulumi.IDInput, state *UserState, opts ...pulumi.ResourceOption) (*User, error) { var resource User err := ctx.ReadResource("aws-native:elasticache:User", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering User resources. type userState struct { } type UserState struct { } func (UserState) ElementType() reflect.Type { return reflect.TypeOf((*userState)(nil)).Elem() } type userArgs struct { // Access permissions string used for this user account. AccessString *string `pulumi:"accessString"` // Must be redis. Engine UserEngine `pulumi:"engine"` // Indicates a password is not required for this user account. NoPasswordRequired *bool `pulumi:"noPasswordRequired"` // Passwords used for this user account. You can create up to two passwords for each user. Passwords []string `pulumi:"passwords"` // The ID of the user. UserId string `pulumi:"userId"` // The username of the user. UserName *string `pulumi:"userName"` } // The set of arguments for constructing a User resource. type UserArgs struct { // Access permissions string used for this user account. AccessString pulumi.StringPtrInput // Must be redis. Engine UserEngineInput // Indicates a password is not required for this user account. NoPasswordRequired pulumi.BoolPtrInput // Passwords used for this user account. You can create up to two passwords for each user. Passwords pulumi.StringArrayInput // The ID of the user. UserId pulumi.StringInput // The username of the user. UserName pulumi.StringPtrInput } func (UserArgs) ElementType() reflect.Type { return reflect.TypeOf((*userArgs)(nil)).Elem() } type UserInput interface { pulumi.Input ToUserOutput() UserOutput ToUserOutputWithContext(ctx context.Context) UserOutput } func (*User) ElementType() reflect.Type { return reflect.TypeOf((*User)(nil)) } func (i *User) ToUserOutput() UserOutput { return i.ToUserOutputWithContext(context.Background()) } func (i *User) ToUserOutputWithContext(ctx context.Context) UserOutput { return pulumi.ToOutputWithContext(ctx, i).(UserOutput) } type UserOutput struct{ *pulumi.OutputState } func (UserOutput) ElementType() reflect.Type { return reflect.TypeOf((*User)(nil)) } func (o UserOutput) ToUserOutput() UserOutput { return o } func (o UserOutput) ToUserOutputWithContext(ctx context.Context) UserOutput { return o } func init() { pulumi.RegisterInputType(reflect.TypeOf((*UserInput)(nil)).Elem(), &User{}) pulumi.RegisterOutputType(UserOutput{}) }
YuriyPobezhymov/tsunami-security-scanner-plugins
google/detectors/rce/java_jmx/src/test/java/com/google/tsunami/plugins/detectors/rce/java/JavaJmxRceDetectorTest.java
/* * Copyright 2020 Google LLC * * 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.google.tsunami.plugins.detectors.rce.java; import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat; import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.protobuf.util.Timestamps; import com.google.tsunami.common.data.NetworkEndpointUtils; import com.google.tsunami.common.time.testing.FakeUtcClock; import com.google.tsunami.common.time.testing.FakeUtcClockModule; import com.google.tsunami.proto.DetectionReport; import com.google.tsunami.proto.DetectionReportList; import com.google.tsunami.proto.DetectionStatus; import com.google.tsunami.proto.NetworkService; import com.google.tsunami.proto.Severity; import com.google.tsunami.proto.TargetInfo; import com.google.tsunami.proto.Vulnerability; import com.google.tsunami.proto.VulnerabilityId; import java.lang.management.ManagementFactory; import java.rmi.registry.LocateRegistry; import java.time.Instant; import java.util.HashMap; import javax.inject.Inject; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnectorServer; import javax.rmi.ssl.SslRMIClientSocketFactory; import javax.rmi.ssl.SslRMIServerSocketFactory; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link JavaJmxRceDetector}. */ @RunWith(JUnit4.class) public final class JavaJmxRceDetectorTest { private final FakeUtcClock fakeUtcClock = FakeUtcClock.create().setNow(Instant.parse("2020-01-01T00:00:00.00Z")); private static final int REGISTRY_PORT = 65535; private static JMXServiceURL url; private JMXConnectorServer server; @Inject private JavaJmxRceDetector detector; @BeforeClass public static void setUpClass() throws Exception { LocateRegistry.createRegistry(REGISTRY_PORT); url = new JMXServiceURL(String.format("service:jmx:rmi:///jndi/rmi://:%d/jmxrmi", REGISTRY_PORT)); } @Before public void setUp() { Guice.createInjector( new FakeUtcClockModule(fakeUtcClock), new JavaJmxRceDetectorBootstrapModule()) .injectMembers(this); } @After public void tearDown() throws Exception { server.stop(); } private void startVulnerableServer() throws Exception { server = JMXConnectorServerFactory.newJMXConnectorServer( url, null, ManagementFactory.getPlatformMBeanServer()); server.start(); } private void startSecureServer() throws Exception { HashMap<String, Object> env = new HashMap<>(); SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory(); SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(); env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf); env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf); server = JMXConnectorServerFactory.newJMXConnectorServer( url, env, ManagementFactory.getPlatformMBeanServer()); server.start(); } @Test public void detect_whenJMXServiceRunningUnprotected_returnsVulnerability() throws Exception { startVulnerableServer(); NetworkService vulnerableService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forHostnameAndPort("localhost", REGISTRY_PORT)) .build(); DetectionReportList detectionReports = detector.detect(TargetInfo.getDefaultInstance(), ImmutableList.of(vulnerableService)); assertThat(detectionReports.getDetectionReportsList()) .containsExactly( DetectionReport.newBuilder() .setTargetInfo(TargetInfo.getDefaultInstance()) .setNetworkService(vulnerableService) .setDetectionTimestamp( Timestamps.fromMillis(Instant.now(fakeUtcClock).toEpochMilli())) .setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED) .setVulnerability( Vulnerability.newBuilder() .setMainId( VulnerabilityId.newBuilder() .setPublisher("GOOGLE") .setValue("JAVA_UNPROTECTED_JMX_RMI_SERVER")) .setSeverity(Severity.CRITICAL) .setTitle("Unprotected Java JMX RMI Server") .setDescription( "Java Management Extension (JMX) allows remote monitoring and" + " diagnostics for Java applications. Running JMX with" + " unprotected RMI endpoint allows any remote users to create a" + " javax.management.loading.MLet MBean and use it to create new" + " MBeans from arbitrary URLs.")) .build()); } @Test public void detect_whenJMXServiceRunningProtected_returnsEmptyDetectionReport() throws Exception { startSecureServer(); NetworkService secureService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forHostnameAndPort("localhost", REGISTRY_PORT)) .build(); DetectionReportList detectionReports = detector.detect(TargetInfo.getDefaultInstance(), ImmutableList.of(secureService)); assertThat(detectionReports.getDetectionReportsList()).isEmpty(); } }
vipuserr/vipuserr-Geological-hazard
geo3d/include/CGAL/Arr_tags.h
<gh_stars>100-1000 // Copyright (c) 2007,2009,2010,2011 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s): <NAME> <<EMAIL>> // <NAME> <<EMAIL>> #ifndef CGAL_ARR_TAGS_H #define CGAL_ARR_TAGS_H #include <CGAL/license/Arrangement_on_surface_2.h> #include <CGAL/config.h> #include <boost/type_traits.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/logical.hpp> #include <boost/mpl/has_xxx.hpp> /*! \file * Definition of the tags for the arrangement package. */ namespace CGAL { struct Arr_boundary_side_tag {}; struct Arr_oblivious_side_tag : public virtual Arr_boundary_side_tag {}; struct Arr_open_side_tag : public virtual Arr_oblivious_side_tag {}; struct Arr_closed_side_tag : public virtual Arr_oblivious_side_tag {}; struct Arr_contracted_side_tag : public virtual Arr_oblivious_side_tag {}; struct Arr_identified_side_tag : public virtual Arr_oblivious_side_tag {}; BOOST_MPL_HAS_XXX_TRAIT_DEF(Left_side_category) BOOST_MPL_HAS_XXX_TRAIT_DEF(Bottom_side_category) BOOST_MPL_HAS_XXX_TRAIT_DEF(Top_side_category) BOOST_MPL_HAS_XXX_TRAIT_DEF(Right_side_category) namespace internal { //! type to provide left side tag (is oblivious if not existing) template < class Traits_, bool B > struct Get_left_side_category {}; template < class Traits_ > struct Get_left_side_category< Traits_, true > { typedef typename Traits_::Left_side_category Category; }; template < class Traits_ > struct Get_left_side_category< Traits_, false > { typedef Arr_oblivious_side_tag Category; }; template < class Traits_ > struct Arr_complete_left_side_category { public: typedef Traits_ Traits; typedef typename Get_left_side_category< Traits, has_Left_side_category< Traits >::value >::Category Category; }; template < class GeometryTraits_2, bool b > struct Validate_left_side_category {}; template < class GeometryTraits_2 > struct Validate_left_side_category< GeometryTraits_2, true > { template <typename T> void missing__Left_side_category() {} }; template < class GeometryTraits_2 > struct Validate_left_side_category< GeometryTraits_2, false > { template <typename T> void missing__Left_side_category() { T missing__Left_side_category__assuming__Arr_oblivious_side_tag__instead; } }; //! type to provide bottom side tag (is oblivious if not existing) template < class Traits_, bool B > struct Get_bottom_side_category { }; template < class Traits_ > struct Get_bottom_side_category< Traits_, true > { typedef typename Traits_::Bottom_side_category Category; }; template < class Traits_ > struct Get_bottom_side_category< Traits_, false > { typedef Arr_oblivious_side_tag Category; }; template < class Traits_ > struct Arr_complete_bottom_side_category { public: typedef Traits_ Traits; typedef typename Get_bottom_side_category< Traits, has_Bottom_side_category< Traits >::value >::Category Category; }; template < class GeometryTraits_2, bool b > struct Validate_bottom_side_category {}; template < class GeometryTraits_2 > struct Validate_bottom_side_category< GeometryTraits_2, true > { template <typename T> void missing__Bottom_side_category() {} }; template < class GeometryTraits_2 > struct Validate_bottom_side_category< GeometryTraits_2, false > { template <typename T> void missing__Bottom_side_category() { T missing__Bottom_side_category__assuming__Arr_oblivious_side_tag__instead; } }; //! type to provide top side tag (is oblivious if not existing) template < class Traits_, bool B > struct Get_top_side_category { }; template < class Traits_ > struct Get_top_side_category< Traits_, true > { typedef typename Traits_::Top_side_category Category; }; template < class Traits_ > struct Get_top_side_category< Traits_, false > { typedef Arr_oblivious_side_tag Category; }; template < class Traits_ > struct Arr_complete_top_side_category { public: typedef Traits_ Traits; typedef typename Get_top_side_category< Traits, has_Top_side_category< Traits >::value >::Category Category; }; template < class GeometryTraits_2, bool b > struct Validate_top_side_category {}; template < class GeometryTraits_2 > struct Validate_top_side_category< GeometryTraits_2, true > { template <typename T> void missing__Top_side_category() {} }; template < class GeometryTraits_2 > struct Validate_top_side_category< GeometryTraits_2, false > { template <typename T> void missing__Top_side_category() { T missing__Top_side_category__assuming__Arr_oblivious_side_tag__instead; } }; //! type to provide right side tag (is oblivious if not existing) template < class Traits_, bool B > struct Get_right_side_category { }; template < class Traits_ > struct Get_right_side_category< Traits_, true > { typedef typename Traits_::Right_side_category Category; }; template < class Traits_ > struct Get_right_side_category< Traits_, false > { typedef Arr_oblivious_side_tag Category; }; template < class Traits_ > struct Arr_complete_right_side_category { public: typedef Traits_ Traits; typedef typename Get_right_side_category< Traits, has_Right_side_category< Traits >::value >::Category Category; }; template < class GeometryTraits_2, bool b > struct Validate_right_side_category {}; template < class GeometryTraits_2 > struct Validate_right_side_category< GeometryTraits_2, true > { template <typename T> void missing__Right_side_category() {} }; template < class GeometryTraits_2 > struct Validate_right_side_category< GeometryTraits_2, false > { template <typename T> void missing__Right_side_category() { T missing__Right_side_category__assuming__Arr_oblivious_side_tag__instead; } }; } // namespace internal struct Arr_boundary_cond_tag{}; struct Arr_all_sides_oblivious_tag : public virtual Arr_boundary_cond_tag{}; struct Arr_not_all_sides_oblivious_tag : public virtual Arr_boundary_cond_tag{}; struct Arr_has_identified_side_tag : public virtual Arr_not_all_sides_oblivious_tag{}; struct Arr_has_contracted_side_tag : public virtual Arr_not_all_sides_oblivious_tag{}; struct Arr_has_closed_side_tag : public virtual Arr_not_all_sides_oblivious_tag{}; struct Arr_has_open_side_tag : public virtual Arr_not_all_sides_oblivious_tag{}; struct Arr_all_sides_open_tag : public virtual Arr_not_all_sides_oblivious_tag{}; struct Arr_all_sides_non_open_tag {}; struct Arr_not_all_sides_non_open_tag {}; /*!\brief Struct to determine whether all side tags are "oblivious" */ template < class ArrLeftSideCategory, class ArrBottomSideCategory, class ArrTopSideCategory, class ArrRightSideCategory > struct Arr_are_all_sides_oblivious_tag { public: //! This instance's first template parameter typedef ArrLeftSideCategory Left_side_category; //! This instance's second template parameter typedef ArrBottomSideCategory Bottom_side_category; //! This instance's third template parameter typedef ArrTopSideCategory Top_side_category; //! This instance's fourth template parameter typedef ArrRightSideCategory Right_side_category; private: typedef boost::mpl::bool_< true > true_; typedef boost::mpl::bool_< false > false_; typedef boost::mpl::if_< boost::is_same< Left_side_category, Arr_oblivious_side_tag >, true_, false_ > Left_oblivious; typedef boost::mpl::if_< boost::is_same< Bottom_side_category, Arr_oblivious_side_tag >, true_, false_ > Bottom_oblivious; typedef boost::mpl::if_< boost::is_same< Top_side_category, Arr_oblivious_side_tag >, true_, false_ > Top_oblivious; typedef boost::mpl::if_< boost::is_same< Right_side_category, Arr_oblivious_side_tag >, true_, false_ > Right_oblivious; public: /*!\brief * boolean tag that is Arr_all_sides_oblivious_tag if all sides are * oblivious, otherwise Arr_not_all_sides_oblivious_tag */ typedef typename boost::mpl::if_< boost::mpl::and_< Left_oblivious, Bottom_oblivious, Top_oblivious, Right_oblivious >, Arr_all_sides_oblivious_tag, Arr_not_all_sides_oblivious_tag >::type result; }; /*!\brief Struct to determine whether all side tags are "non-open" */ template < class ArrLeftSideCategory, class ArrBottomSideCategory, class ArrTopSideCategory, class ArrRightSideCategory > struct Arr_are_all_sides_non_open_tag { public: //! This instance's first template parameter typedef ArrLeftSideCategory Left_side_category; //! This instance's second template parameter typedef ArrBottomSideCategory Bottom_side_category; //! This instance's third template parameter typedef ArrTopSideCategory Top_side_category; //! This instance's fourth template parameter typedef ArrRightSideCategory Right_side_category; private: typedef boost::mpl::bool_< true > true_; typedef boost::mpl::bool_< false > false_; typedef boost::mpl::if_< boost::is_same< Left_side_category, Arr_open_side_tag >, true_, false_ > Left_open; typedef boost::mpl::if_< boost::is_same< Bottom_side_category, Arr_open_side_tag >, true_, false_ > Bottom_open; typedef boost::mpl::if_< boost::is_same< Top_side_category, Arr_open_side_tag >, true_, false_ > Top_open; typedef boost::mpl::if_< boost::is_same< Right_side_category, Arr_open_side_tag >, true_, false_ > Right_open; public: /*!\brief * boolean tag that is Arr_all_sides_non_open_tag if all sides are non-open, * otherwise Arr_not_all_sides_non_open_tag */ typedef typename boost::mpl::if_< boost::mpl::and_< boost::mpl::not_< Left_open >, boost::mpl::not_< Bottom_open >, boost::mpl::not_< Top_open >, boost::mpl::not_< Right_open > >, Arr_all_sides_non_open_tag, Arr_not_all_sides_non_open_tag >::type result; }; /*!\brief Struct to check consistent tagging of identifications */ template < class ArrLeftSideCategory, class ArrBottomSideCategory, class ArrTopSideCategory, class ArrRightSideCategory > struct Arr_sane_identified_tagging { public: //! This instance's first template parameter typedef ArrLeftSideCategory Left_side_category; //! This instance's second template parameter typedef ArrBottomSideCategory Bottom_side_category; //! This instance's third template parameter typedef ArrTopSideCategory Top_side_category; //! This instance's fourth template parameter typedef ArrRightSideCategory Right_side_category; private: typedef boost::mpl::bool_< true > true_; typedef boost::mpl::bool_< false > false_; typedef boost::mpl::if_< boost::is_same< Left_side_category, Arr_identified_side_tag >, true_, false_ > Left_identified; typedef boost::mpl::if_< boost::is_same< Bottom_side_category, Arr_identified_side_tag >, true_, false_ > Bottom_identified; typedef boost::mpl::if_< boost::is_same< Top_side_category, Arr_identified_side_tag >, true_, false_ > Top_identified; typedef boost::mpl::if_< boost::is_same< Right_side_category, Arr_identified_side_tag >, true_, false_ > Right_identified; typedef boost::mpl::and_< Left_identified, Right_identified > LR_identified; typedef boost::mpl::and_< Bottom_identified, Top_identified > BT_identified; typedef boost::mpl::and_< boost::mpl::not_< Left_identified>, boost::mpl::not_< Right_identified > > LR_non_identified; typedef boost::mpl::and_< boost::mpl::not_< Bottom_identified >, boost::mpl::not_< Top_identified > > BT_non_identified; typedef boost::mpl::or_< LR_identified, LR_non_identified > LR_ok; typedef boost::mpl::or_< BT_identified, BT_non_identified > BT_ok; public: /*!\brief * boolean tag that is bool_<true> if opposite sides are either * both identified or both non-identified, * otherwise bool_<false> */ typedef boost::mpl::and_< LR_ok, BT_ok > result; }; /*! Checks whether one of two boundary sides are identified * Observe that if one side is identified, the opposite side must be identified * as well. Thus: * (i) When Arr_has_identified_sides is used to check whether two opposite * sides are identified, the check for the second side is redundant. * (ii) When Arr_has_identified_sides is used to check whether two non-opposite * sides are identified, the check applies to all four sides. */ template <class ArrSideOneCategory, class ArrSideTwoCategory> struct Arr_has_identified_sides { public: //! This instance's first template parameter typedef ArrSideOneCategory Side_one_category; //! This instance's second template parameter typedef ArrSideTwoCategory Side_two_category; private: typedef boost::mpl::bool_<true> true_; typedef boost::mpl::bool_<false> false_; typedef boost::mpl::if_< boost::is_same<Side_one_category, Arr_identified_side_tag>, true_, false_> Side_one_identified; typedef boost::mpl::if_< boost::is_same<Side_two_category, Arr_identified_side_tag>, true_, false_> Side_two_identified; public: /*!\brief * boolean tag that is bool_<true> if one side is identified, * otherwise bool_<false> */ typedef boost::mpl::or_<Side_one_identified, Side_two_identified> result; }; /*! Checks whether one of two boundary sides are contracted */ template <class ArrSideOneCategory, class ArrSideTwoCategory> struct Arr_has_contracted_sides_two { public: //! This instance's first template parameter typedef ArrSideOneCategory Side_one_category; //! This instance's second template parameter typedef ArrSideTwoCategory Side_two_category; private: typedef boost::mpl::bool_<true> true_; typedef boost::mpl::bool_<false> false_; typedef boost::mpl::if_< boost::is_same<Side_one_category, Arr_contracted_side_tag>, true_, false_> Side_one_contracted; typedef boost::mpl::if_< boost::is_same<Side_two_category, Arr_contracted_side_tag>, true_, false_> Side_two_contracted; public: /*!\brief * boolean tag that is bool_<true> if one side is identified, * otherwise bool_<false> */ typedef boost::mpl::or_<Side_one_contracted, Side_two_contracted> result; }; /*! Checks whether one of two boundary sides are closed */ template <class ArrSideOneCategory, class ArrSideTwoCategory> struct Arr_has_closed_sides_two { public: //! This instance's first template parameter typedef ArrSideOneCategory Side_one_category; //! This instance's second template parameter typedef ArrSideTwoCategory Side_two_category; private: typedef boost::mpl::bool_<true> true_; typedef boost::mpl::bool_<false> false_; typedef boost::mpl::if_< boost::is_same<Side_one_category, Arr_closed_side_tag>, true_, false_> Side_one_closed; typedef boost::mpl::if_< boost::is_same<Side_two_category, Arr_closed_side_tag>, true_, false_> Side_two_closed; public: /*!\brief * boolean tag that is bool_<true> if one side is identified, * otherwise bool_<false> */ typedef boost::mpl::or_<Side_one_closed, Side_two_closed> result; }; /*! Checks whether one of two boundary sides are open */ template <class ArrSideOneCategory, class ArrSideTwoCategory> struct Arr_has_open_sides_two { public: //! This instance's first template parameter typedef ArrSideOneCategory Side_one_category; //! This instance's second template parameter typedef ArrSideTwoCategory Side_two_category; private: typedef boost::mpl::bool_<true> true_; typedef boost::mpl::bool_<false> false_; typedef boost::mpl::if_< boost::is_same<Side_one_category, Arr_open_side_tag>, true_, false_> Side_one_open; typedef boost::mpl::if_< boost::is_same<Side_two_category, Arr_open_side_tag>, true_, false_> Side_two_open; public: /*!\brief * boolean tag that is bool_<true> if one side is identified, * otherwise bool_<false> */ typedef boost::mpl::or_<Side_one_open, Side_two_open> result; }; /*! Categorizes two boundary sides: * If one side is identified => Arr_has_identified_side_tag * Otherwise if one side is contracted => Arr_has_contracted_side_tag * Otherwise if one side is closed => Arr_has_closed_side_tag * Otherwise if one side is open => Arr_has_open_side_tag * Otherwise => Arr_all_sides_oblivious_tag */ template < class ArrSideOneCategory, class ArrSideTwoCategory> struct Arr_two_sides_category { public: //! This instance's first template parameter typedef ArrSideOneCategory Side_one_category; //! This instance's second template parameter typedef ArrSideTwoCategory Side_two_category; private: // One of the two sides is identified typedef typename Arr_has_identified_sides<Side_one_category, Side_two_category>::result Is_identified; // One of the two sides is contracted typedef typename Arr_has_contracted_sides_two<Side_one_category, Side_two_category>::result Is_contracted; // One of the two sides is closed typedef typename Arr_has_closed_sides_two<Side_one_category, Side_two_category>::result Is_closed; // One of the two sides is open typedef typename Arr_has_open_sides_two<Side_one_category, Side_two_category>::result Is_open; public: typedef typename boost::mpl::if_<Is_identified, Arr_has_identified_side_tag, typename boost::mpl::if_<Is_contracted, Arr_has_contracted_side_tag, typename boost::mpl::if_<Is_closed, Arr_has_closed_side_tag, typename boost::mpl::if_<Is_open, Arr_has_open_side_tag, Arr_all_sides_oblivious_tag>::type>::type>::type>::type result; }; /*! Categorizes all sides: * If one side is identified => Arr_has_identified_side_tag * Otherwise if one side is contracted => Arr_has_contracted_side_tag * Otherwise if one side is closed => Arr_has_closed_side_tag * Otherwise if one side is open => Arr_has_open_side_tag * Otherwise (all sides oblivious) => Arr_all_sides_oblivious_tag */ template < class ArrSideOneCategory, class ArrSideTwoCategory> struct Arr_all_sides_category { public: }; } // namespace CGAL #endif
mohd-faizy/DataScience-With-Python
11_python-data-science-toolbox-(part-2)/1-using-iterators-in-pythonland/01_iterators-vs-iterables.py
''' 01_Iterators vs Iterables Let's do a quick recall of what you've learned about iterables and iterators. Recall from the video that an iterable is an object that can return an iterator, while an iterator is an object that keeps state and produces the next value when you call next() on it. In this exercise, you will identify which object is an iterable and which is an iterator. The environment has been pre-loaded with the variables flash1 and flash2. Try printing out their values with print() and next() to figure out which is an iterable and which is an iterator. Possible Answers -Both flash1 and flash2 are iterators. -Both flash1 and flash2 are iterables. -flash1 is an iterable and flash2 is an iterator. -Take Hint (-15xp) ''' # flash1 is an iterable and flash2 is an iterator.
idGain/ewp-node
src/main/java/pt/ulisboa/ewp/node/api/host/forward/ewp/controller/institutions/ForwardEwpApiInstitutionsGeneralController.java
package pt.ulisboa.ewp.node.api.host.forward.ewp.controller.institutions; import io.swagger.v3.oas.annotations.Operation; import java.util.Collection; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import pt.ulisboa.ewp.node.api.host.forward.ewp.dto.ForwardEwpApiHeiIdsResponseDTO; import pt.ulisboa.ewp.node.api.host.forward.ewp.dto.ForwardEwpApiResponseWithData; import pt.ulisboa.ewp.node.api.host.forward.ewp.security.ForwardEwpApiSecurityCommonConstants; import pt.ulisboa.ewp.node.api.host.forward.ewp.utils.ForwardEwpApiConstants; import pt.ulisboa.ewp.node.api.host.forward.ewp.utils.ForwardEwpApiResponseUtils; import pt.ulisboa.ewp.node.client.ewp.registry.RegistryClient; @RestController @RequestMapping(ForwardEwpApiConstants.API_BASE_URI + "institutions") @Secured({ForwardEwpApiSecurityCommonConstants.ROLE_HOST_WITH_PREFIX}) @Validated public class ForwardEwpApiInstitutionsGeneralController { private final RegistryClient registryClient; protected ForwardEwpApiInstitutionsGeneralController(RegistryClient registryClient) { this.registryClient = registryClient; } @GetMapping(value = "/hei-ids", produces = MediaType.APPLICATION_XML_VALUE) @Operation( summary = "EWP Institutions Forward API.", tags = {"Institutions"}) public ResponseEntity<ForwardEwpApiResponseWithData<ForwardEwpApiHeiIdsResponseDTO>> getAllHeiIds() { Collection<String> heiIds = registryClient.getAllHeiIds(); return ResponseEntity.ok( ForwardEwpApiResponseUtils.createResponseWithMessagesAndData( new ForwardEwpApiHeiIdsResponseDTO(heiIds))); } }
mpatrickaires/faculdade-esup
EstruturaDeDados/stack/Exercicio08.java
<reponame>mpatrickaires/faculdade-esup package stack; import java.util.Scanner; public class Exercicio08 { /* * 08 - Dado uma pilha estática que armazene números, escreva uma função que forneça o * maior, o menor e a média aritmética dos elementos da pilha. Faça uso apenas das funções * da pilha. Após printar as informações pedidas, a pilha deve se encontrar na configuração * original (os elementos na mesma ordem e posição). */ public static void main(String[] args) { StaticStack pilha = popularPilha(); int maiorElementoPilha = pilhaMaiorElemento(pilha); int menorElementoPilha = pilhaMenorElemento(pilha); double mediaElementosPilha = pilhaMediaElementos(pilha); System.out.println("============================================="); System.out.println("Maior elemento da pilha -> " + maiorElementoPilha); System.out.println("Menor elemento da pilha -> " + menorElementoPilha); System.out.println("Média dos elementos da pilha -> " + mediaElementosPilha); System.out.println("============================================="); } public static StaticStack popularPilha() { Scanner scan = new Scanner(System.in); System.out.print("Digite um tamanho para a pilha: "); StaticStack pilha = new StaticStack(scan.nextInt()); System.out.println("----------------------------------------"); for(int contador = 0; contador < pilha.length(); contador++) { System.out.print("Digite o " + (contador + 1) + "º elemento da pilha -> "); pilha.push(scan.nextInt()); } return pilha; } public static int pilhaMaiorElemento(StaticStack pilha) { StaticStack pilhaAuxiliar = new StaticStack(pilha.length()); int maiorElemento = 0; for(int contador = 0; contador < pilha.length(); contador++) { pilhaAuxiliar.push(pilha.pop()); if(pilhaAuxiliar.peek() > maiorElemento || contador == 0) { maiorElemento = pilhaAuxiliar.peek(); } } while(!pilhaAuxiliar.isEmpty()) { pilha.push(pilhaAuxiliar.pop()); } return maiorElemento; } public static int pilhaMenorElemento(StaticStack pilha) { StaticStack pilhaAuxiliar = new StaticStack(pilha.length()); int menorElemento = 0; for(int contador = 0; contador < pilha.length(); contador++) { pilhaAuxiliar.push(pilha.pop()); if(pilhaAuxiliar.peek() < menorElemento || contador == 0) { menorElemento = pilhaAuxiliar.peek(); } } while(!pilhaAuxiliar.isEmpty()) { pilha.push(pilhaAuxiliar.pop()); } return menorElemento; } public static double pilhaMediaElementos(StaticStack pilha) { StaticStack pilhaAuxiliar = new StaticStack(pilha.length()); double soma = 0; for(int contador = 0; contador < pilha.length(); contador++) { pilhaAuxiliar.push(pilha.pop()); soma += pilhaAuxiliar.peek(); } while(!pilhaAuxiliar.isEmpty()) { pilha.push(pilhaAuxiliar.pop()); } return soma / pilha.length(); } }
flipcoder/qor
Qor/PlayerInterface3D.cpp
<reponame>flipcoder/qor #include <boost/scope_exit.hpp> #include "PlayerInterface3D.h" #include "Sprite.h" #include <glm/gtx/vector_angle.hpp> using namespace std; using namespace glm; PlayerInterface3D :: PlayerInterface3D( const shared_ptr<Controller>& input, const shared_ptr<Node>& look_node, const shared_ptr<Node>& node, const shared_ptr<Meta>& profile, std::function<bool()> lock_if //const shared_ptr<ResourceCache<Texture>>& textures ): NodeInterface(input, node), m_wpLookNode(look_node), m_Speed(6.0), m_Sens(1.0f), m_LockIf(lock_if) { TRY(m_Sens = safe_ptr(profile)->at<double>("sensitivity", 1.0)); } void PlayerInterface3D :: event() { auto n = node(); auto in = controller(); if(m_LockIf && m_LockIf()) return; m_Move = vec3(); if(in->button("left")) m_Move += vec3(-1.0f, 0.0f, 0.0f); if(in->button("right")) m_Move += vec3(1.0f, 0.0f, 0.0f); if(in->button("forward")) m_Move += vec3(0.0f, 0.0f, -1.0f); if(in->button("back")) m_Move += vec3(0.0f, 0.0f, 1.0f); if(in->button("jump")) { if(m_bFly) { m_Move += vec3(0.0f, 1.0f, 0.0f); } else { if(in->button("jump").pressed_now()) m_cbJump(); } } if(in->button("crouch")){ if(m_bFly) { m_Move += vec3(0.0f, -1.0f, 0.0f); } } //if(in->button(3)) // m_Move = vec3(-1.0f, 0.0f, 0.0f); if(length(m_Move) > 0.1f) m_Move = normalize(m_Move) * m_Speed; if(in->button("crouch").pressed_now()) { crouch(!m_bCrouched); } if(m_bCrouched) { m_Move *= m_CrouchMultiplier; } if(m_bAllowSprint){ if(in->button(in->button_id("sprint"))) { m_bSprint = true; m_Move *= m_SprintMultiplier; }else{ m_bSprint = false; } } } void PlayerInterface3D :: crouch(bool b) { if(b == m_bCrouched) return; if(m_bCrouched) { if(m_cbUncrouch()) m_bCrouched = !m_bCrouched; } else { m_cbCrouch(); m_bCrouched = !m_bCrouched; } } void PlayerInterface3D :: logic(Freq::Time t) { auto n = node(); auto in = controller(); auto m = in->input()->mouse_rel(); auto ln = look_node(); const float sens = 0.001f * m_Sens; auto p = n->position(); //ln->rotate(m.x * sens, , Space::PARENT); // WAIT: instead, do the above without pending/triggering signals *ln->matrix() = glm::rotate( m.x * sens * float(K_TAU), glm::vec3(0.0f, -1.0f, 0.0f) ) * *ln->matrix(); if(not m_bLockPitch) { //float delta; //if(in->input()->key(SDLK_i)) //{ // delta = 0.5f * t.s(); //} else if(in->input()->key(SDLK_k)) { // delta = -0.5f * t.s(); //} auto delta = m.y * sens; const float maxpitch = 0.25f - 0.001f; delta = std::min(std::max(delta, -maxpitch-m_Pitch), maxpitch-m_Pitch); m_Pitch += delta; ln->rotate(delta, glm::vec3(-1.0f, 0.0f, 0.0f)); //LOGf("pitch: %s", m_Pitch); } else { // okay NOW we can pend and trigger ln->pend(); ln->on_move(); } if(m_LockIf && m_LockIf()) return; auto mag = glm::length(m_Move); if(mag > 0.1f) { auto vert_movement = m_Move.y; auto move = vec3(m_Move.x, 0.0f, m_Move.z); auto xz_mag = glm::length(move); if(xz_mag > 0.1) { move = glm::normalize(move) * mag; if(!m_bFly) { move = ln->orient_to_world(move); move.y = 0.0f; move = ln->orient_from_world(move); move = glm::normalize(move) * xz_mag; } move = n->orient_from_world(ln->orient_to_world(move)); } auto movey = move.y; move = glm::vec3(move.x, 0.0f, move.z); //m_MaxVel = move; //if(!m_bFly) { // auto cur_vel = n->velocity(); // if(length(cur_vel) <= length(move)){ // move = normalize(move) * length(cur_vel); // same dir // move += 100.0f * normalize(move) * t.s(); // } //} move.y = movey; if(!m_bFly) { auto v = n->velocity(); move.y = v.y; }else{ move.y += m_Move.y; } move.y += 0.01f; n->velocity(move); }else{ auto v = n->velocity(); auto move = glm::vec3(0.0f, 0.0f, 0.0f); if(!m_bFly){ //if(length(v) >= 0.01f){ // move = v; // move -= v * 30.0f * t.s(); //} } if(!m_bFly) n->velocity(vec3(move.x, v.y, move.z)); else n->velocity(vec3(move.x, m_Move.y, move.z)); } }
enzoqtvf/homer-view-react
src/containers/Logs/sagas/index.js
<filename>src/containers/Logs/sagas/index.js import { all, fork } from "redux-saga/effects"; import getLogsSaga from "./LogsSagas"; export default function* documentSaga() { yield all([fork(getLogsSaga)]); }
Ajapaik/ajapaik-android-app
app/src/main/java/ee/ajapaik/android/fragment/util/AlertFragment.java
package ee.ajapaik.android.fragment.util; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.os.Bundle; import android.os.Parcelable; import android.view.KeyEvent; import androidx.fragment.app.DialogFragment; import ee.ajapaik.android.BuildConfig; public class AlertFragment extends DialogFragment { public static final int RESULT_NEGATIVE = -1; public static final int RESULT_POSITIVE = 0; public static final int RESULT_NEUTRAL = 1; private static final String KEY_TITLE = "title"; private static final String KEY_MESSAGE = "message"; private static final String KEY_ICON = "icon"; private static final String KEY_CANCEL_BUTTON = "cancel"; private static final String KEY_OTHER_BUTTONS = "other"; private static final String KEY_USER_INFO = "info"; private static final int INVALID_RESOURCE_ID = -1; public static AlertFragment create(String title, String message, String cancelButton) { return create(title, message, cancelButton, (String[])null); } public static AlertFragment create(String title, String message, String cancelButton, String... otherButtons) { AlertFragment fragment = new AlertFragment(); Bundle arguments = new Bundle(); arguments.putString(KEY_TITLE, title); arguments.putString(KEY_MESSAGE, message); arguments.putString(KEY_CANCEL_BUTTON, cancelButton); if(otherButtons != null && otherButtons.length > 0) { arguments.putStringArray(KEY_OTHER_BUTTONS, otherButtons); } fragment.setArguments(arguments); fragment.setCancelable(false); return fragment; } public <T extends Parcelable> T getUserInfo() { return getArguments().getParcelable(KEY_USER_INFO); } public AlertFragment setUserInfo(Parcelable userInfo) { getArguments().putParcelable(KEY_USER_INFO, userInfo); return this; } public AlertFragment setIcon(int iconId) { getArguments().putInt(KEY_ICON, iconId); return this; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle arguments = getArguments(); int iconId = arguments.getInt(KEY_ICON, INVALID_RESOURCE_ID); String title = arguments.getString(KEY_TITLE); String message = arguments.getString(KEY_MESSAGE); String cancelButton = arguments.getString(KEY_CANCEL_BUTTON); String[] otherButtons = arguments.getStringArray(KEY_OTHER_BUTTONS); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { int result = (which == AlertDialog.BUTTON_NEGATIVE) ? RESULT_NEGATIVE : ((which == AlertDialog.BUTTON_POSITIVE) ? RESULT_POSITIVE : RESULT_NEUTRAL); ((ee.ajapaik.android.fragment.util.DialogInterface)getActivity()).onDialogFragmentDismissed(AlertFragment.this, getTargetRequestCode(), result); } catch(Exception e) { if(BuildConfig.DEBUG) { e.printStackTrace(); } } dialog.dismiss(); } }; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); AlertDialog dialog; if(iconId != INVALID_RESOURCE_ID) { builder.setIcon(iconId); } if(title != null) { builder.setTitle(title); } if(message != null) { builder.setMessage(message); } if(cancelButton != null) { builder.setNegativeButton(cancelButton, listener); } if(otherButtons != null) { if(otherButtons.length > 0 && otherButtons[0] != null) { builder.setPositiveButton(otherButtons[0], listener); } if(otherButtons.length > 1 && otherButtons[1] != null) { builder.setNeutralButton(otherButtons[1], listener); } } dialog = builder.create(); dialog.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { try { ((ee.ajapaik.android.fragment.util.DialogInterface)getActivity()).onDialogFragmentCancelled(AlertFragment.this, getTargetRequestCode()); } catch(Exception e) { if(BuildConfig.DEBUG) { e.printStackTrace(); } } dialog.dismiss(); return true; } return false; } }); return dialog; } }
patricklx/carbon-components-ember
addon/components/charts/-components/axis/component.js
<filename>addon/components/charts/-components/axis/component.js import Component from '@glimmer/component'; /** @documenter yuidoc */ /** The ChartAxis ```handlebars ``` @class ChartAxis @public **/ class ChartAxis extends Component { args = { /** * The Axis Title * @argument title * @type String */ title: '', /** * @argument stacked * @type boolean */ stacked: false, /** * @argument primary * @type boolean */ primary: false, /** * @argument secondary * @type boolean */ secondary: false, /** * @argument scaleType * @type String */ scaleType: null } } export default ChartAxis;
CraftAcademy/gigafood
features/step_definitions/active_admin_steps.rb
<reponame>CraftAcademy/gigafood def ensure_user_created(email) user = AdminUser.where(email: email).first_or_create(password: 'password', password_confirmation: 'password') unless user.persisted? raise "Could not create user #{email}: #{user.errors.full_messages}" end user end When /^I fill in the password field with "([^"]*)"$/ do |password| fill_in 'admin_user_password', with: password end Given /^an admin user "([^"]*)" exists$/ do |email| ensure_user_created(email) end When /^(?:I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value| fill_in(field, with: value) end When /^(?:I )press "([^"]*)"$/ do |button| click_link_or_button(button) end Then /^(?:I )should( not)? see( the element)? "([^"]*)"$/ do |negate, is_css, text| should = negate ? :not_to : :to have = is_css ? have_css(text) : have_content(text) expect(page).send should, have end Given(/^an admin exists with email "([^"]*)" and password "([^"]*)"$/) do |email, password| @admin = FactoryGirl.create(:admin_user, email: email, password: password) end And(/^I'm logged in as admin$/) do login_as @admin, scope: :admin_user end
sharpzeb/bootcamp
01-Class-Content/07-Project-1/03-Algorithms/03-acronym-builder/Unsolved/acronym-builder.js
// Write code to create a function that accepts a string and returns an acronym for the given string var acronymBuilder = function(str) {};
egetman/jes
src/main/java/store/jesframework/snapshot/TimeBasedSnapshotStrategy.java
<reponame>egetman/jes package store.jesframework.snapshot; import java.time.Duration; import java.time.LocalDateTime; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import store.jesframework.Aggregate; import store.jesframework.Event; import static java.time.LocalDateTime.now; /** * This strategy applied to the time of the last snapshot. If it more than specidied duration, a snapshot will be done. */ public class TimeBasedSnapshotStrategy implements SnapshotStrategy { private static final int TRACKING_SIZE = 2000; private final Duration snapshotAfter; private final Map<UUID, LocalDateTime> tracking; @SuppressWarnings("WeakerAccess") public TimeBasedSnapshotStrategy(@Nonnull Duration snapshotAfter) { this.snapshotAfter = Objects.requireNonNull(snapshotAfter, "Duration must not be null"); if (snapshotAfter.isNegative()) { throw new IllegalArgumentException("Duration must not be negative"); } // mb not the optimal solution this.tracking = Collections.synchronizedMap(new LinkedHashMap<UUID, LocalDateTime>(TRACKING_SIZE, .75f, true) { @Override public boolean removeEldestEntry(Map.Entry<UUID, LocalDateTime> eldest) { return size() > TRACKING_SIZE; } }); } @Override public boolean isSnapshotNecessary(@Nonnull Aggregate aggregate, @Nullable Collection<Event> events) { final LocalDateTime now = now(); final LocalDateTime lastSeen = tracking.put(aggregate.uuid(), now); if (lastSeen != null) { final Duration fromLastSnapshot = Duration.between(lastSeen, now); return !fromLastSnapshot.minus(snapshotAfter).isNegative(); } return false; } }
yumiaoxia/spring-boot-demos
modules-test/src/main/java/com/itsherman/modulestest/web/dto/PersonWithRawDO.java
<reponame>yumiaoxia/spring-boot-demos<gh_stars>0 package com.itsherman.modulestest.web.dto; import com.itsherman.dto.assembler.annotations.DtoModel; import com.itsherman.modulestest.domain.Person; @DtoModel(from = Person.class) public class PersonWithRawDO extends PersonDO { private BookDO book; public BookDO getBook() { return book; } public void setBook(BookDO book) { this.book = book; } }
hellhound/dentexchange
dentexchange/apps/membership/tests/test_year_choices.py
<filename>dentexchange/apps/membership/tests/test_year_choices.py<gh_stars>1-10 # -*- coding:utf-8 -*- import unittest import mock import datetime from ..utils import YearChoices class YearChoicesTestCase(unittest.TestCase): def test_iter_should_return_50_years_since_current_year(self): # setup current_year = datetime.datetime.now().year years = range(current_year, current_year + 50) # action choices = list(YearChoices()) # assert self.assertEqual(zip(years, years), choices)
zhiming-shen/Xen-Blanket-NG
xen/xen-4.2.2/tools/python/xen/xm/setenforce.py
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #============================================================================ # Author: <NAME> <<EMAIL>> #============================================================================ """Modify the current mode of the Flask XSM module. """ from xen.xm.opts import OptionError from xen.xm import main as xm_main from xen.xm.main import server from xen.util import xsconstants def help(): return """ Usage: xm setenforce [ Enforcing | Permissive | 1 | 0 ] Modifies the current mode of the Flask XSM module to be permissive or enforcing. Using Enforcing or 1 will put the Flask module in enforcing mode. Using Permissive or 0 will put the Flask module in permissive mode.""" def setenforce(mode): if len(mode) == 1 and ( mode == "0" or mode == "1" ): val = int(mode) elif mode.lower() == "enforcing": val = 1 elif mode.lower() == "permissive": val = 0 else: raise OptionError("%s is an unsupported mode" % mode) if xm_main.serverType == xm_main.SERVER_XEN_API: if xsconstants.XS_POLICY_FLASK != \ int(server.xenapi.XSPolicy.get_xstype()): raise OptionError("Unsupported policy type") ret = server.xenapi.XSPolicy.setenforce(val) else: if server.xend.security.on() != xsconstants.XS_POLICY_FLASK: raise OptionError("Unsupported policy type") ret = server.xend.security.setenforce(val) def main(argv): if len(argv) != 2: raise OptionError("Invalid arguments") if "-?" in argv: help() return mode = argv[1]; setenforce(mode) if __name__ == '__main__': try: main(sys.argv) except Exception, e: sys.stderr.write('Error: %s\n' % str(e)) sys.exit(-1)
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/ecf/349.java
<gh_stars>10-100 /**************************************************************************** * Copyright (c) 2004 Composent, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Composent, Inc. - initial API and implementation *****************************************************************************/ package org.eclipse.ecf.tests.core.identity; import junit.framework.TestCase; import org.eclipse.ecf.core.identity.ID; import org.eclipse.ecf.core.identity.IDCreateException; public abstract class IDAbstractTestCase extends TestCase { private ID fixture; protected abstract ID createID() throws IDCreateException; /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); fixture = createID(); assertNotNull(fixture); } /* * (non-Javadoc) * * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); fixture = null; } protected ID getFixture() { return fixture; } }
zakibinary/deriv-app
packages/components/stories/multi-step/stories/basic.js
<filename>packages/components/stories/multi-step/stories/basic.js import React from 'react'; import { boolean } from '@storybook/addon-knobs'; import Button from 'Components/button'; import MultiStep from 'Components/multi-step'; import Wrapper from '../../shared/wrapper'; const steps = [{ component: 'Step 1' }, { component: 'Step 2' }, { component: 'Step 3' }]; const Basic = () => { const multi_step_ref = React.createRef(); const onClick = () => { if (multi_step_ref.current && multi_step_ref.current?.state.step < steps.length - 1) { multi_step_ref.current.nextStep(); } }; return ( <Wrapper is_block className='multi-step-storybook' is_dark={boolean('Dark Theme', false)}> <MultiStep ref={multi_step_ref} lbl_previous='Back' steps={steps} /> <Button onClick={onClick} text='Next step' medium /> </Wrapper> ); }; export default Basic;
Vufuzi/music-fns
src/constants/Interval/Short.js
// https://en.wikipedia.org/wiki/Interval_(music)#Interval_number_and_quality export const R = 0; export const S = 1; export const T = 2; export const TT = 6; export const O = 12; export default { R, S, T, TT, O };
gstearmit/data-structure-algorithm
src/test/java/ir/sk/adt/datastructure/array/SortedArrayTest.java
<reponame>gstearmit/data-structure-algorithm package ir.sk.adt.datastructure.array; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author <a href="<EMAIL>"><NAME></a> on 12/7/2017. */ public class SortedArrayTest { SortedArray array; @Before public void setUp() throws Exception { int maxSize = 100; array = new SortedArray(maxSize); // insert 10 items array.insert(77); array.insert(99); array.insert(44); array.insert(55); array.insert(22); array.insert(88); array.insert(11); array.insert(00); array.insert(66); array.insert(33); } @After public void tearDown() throws Exception { } @Test public void find() throws Exception { int searchKey = 55; // search for item if (array.find(searchKey) != array.size()) System.out.println("Found " + searchKey); else System.out.println("Can’t find " + searchKey); } @Test public void insert() throws Exception { array.display(); // display items array.insert(33); array.display(); // display items } @Test public void delete() throws Exception { array.display(); array.delete(00); // delete 3 items array.display(); } @Test public void display() throws Exception { array.display(); // display items } }
ankurshukla1993/IOT-test
coeey/com/google/android/gms/dynamic/zza.java
package com.google.android.gms.dynamic; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.internal.zzu; import com.google.android.gms.common.zze; import java.util.LinkedList; public abstract class zza<T extends LifecycleDelegate> { private T zzgtj; private Bundle zzgtk; private LinkedList<zzi> zzgtl; private final zzo<T> zzgtm = new zzb(this); private final void zza(Bundle bundle, zzi com_google_android_gms_dynamic_zzi) { if (this.zzgtj != null) { com_google_android_gms_dynamic_zzi.zzb(this.zzgtj); return; } if (this.zzgtl == null) { this.zzgtl = new LinkedList(); } this.zzgtl.add(com_google_android_gms_dynamic_zzi); if (bundle != null) { if (this.zzgtk == null) { this.zzgtk = (Bundle) bundle.clone(); } else { this.zzgtk.putAll(bundle); } } zza(this.zzgtm); } public static void zzb(FrameLayout frameLayout) { zze instance = GoogleApiAvailability.getInstance(); Context context = frameLayout.getContext(); int isGooglePlayServicesAvailable = instance.isGooglePlayServicesAvailable(context); CharSequence zzi = zzu.zzi(context, isGooglePlayServicesAvailable); CharSequence zzk = zzu.zzk(context, isGooglePlayServicesAvailable); View linearLayout = new LinearLayout(frameLayout.getContext()); linearLayout.setOrientation(1); linearLayout.setLayoutParams(new LayoutParams(-2, -2)); frameLayout.addView(linearLayout); View textView = new TextView(frameLayout.getContext()); textView.setLayoutParams(new LayoutParams(-2, -2)); textView.setText(zzi); linearLayout.addView(textView); Intent zza = zze.zza(context, isGooglePlayServicesAvailable, null); if (zza != null) { View button = new Button(context); button.setId(16908313); button.setLayoutParams(new LayoutParams(-2, -2)); button.setText(zzk); linearLayout.addView(button); button.setOnClickListener(new zzf(context, zza)); } } private final void zzcz(int i) { while (!this.zzgtl.isEmpty() && ((zzi) this.zzgtl.getLast()).getState() >= i) { this.zzgtl.removeLast(); } } public final void onCreate(Bundle bundle) { zza(bundle, new zzd(this, bundle)); } public final View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) { FrameLayout frameLayout = new FrameLayout(layoutInflater.getContext()); zza(bundle, new zze(this, frameLayout, layoutInflater, viewGroup, bundle)); if (this.zzgtj == null) { zza(frameLayout); } return frameLayout; } public final void onDestroy() { if (this.zzgtj != null) { this.zzgtj.onDestroy(); } else { zzcz(1); } } public final void onDestroyView() { if (this.zzgtj != null) { this.zzgtj.onDestroyView(); } else { zzcz(2); } } public final void onInflate(Activity activity, Bundle bundle, Bundle bundle2) { zza(bundle2, new zzc(this, activity, bundle, bundle2)); } public final void onLowMemory() { if (this.zzgtj != null) { this.zzgtj.onLowMemory(); } } public final void onPause() { if (this.zzgtj != null) { this.zzgtj.onPause(); } else { zzcz(5); } } public final void onResume() { zza(null, new zzh(this)); } public final void onSaveInstanceState(Bundle bundle) { if (this.zzgtj != null) { this.zzgtj.onSaveInstanceState(bundle); } else if (this.zzgtk != null) { bundle.putAll(this.zzgtk); } } public final void onStart() { zza(null, new zzg(this)); } public final void onStop() { if (this.zzgtj != null) { this.zzgtj.onStop(); } else { zzcz(4); } } protected void zza(FrameLayout frameLayout) { zze instance = GoogleApiAvailability.getInstance(); Context context = frameLayout.getContext(); int isGooglePlayServicesAvailable = instance.isGooglePlayServicesAvailable(context); CharSequence zzi = zzu.zzi(context, isGooglePlayServicesAvailable); CharSequence zzk = zzu.zzk(context, isGooglePlayServicesAvailable); View linearLayout = new LinearLayout(frameLayout.getContext()); linearLayout.setOrientation(1); linearLayout.setLayoutParams(new LayoutParams(-2, -2)); frameLayout.addView(linearLayout); View textView = new TextView(frameLayout.getContext()); textView.setLayoutParams(new LayoutParams(-2, -2)); textView.setText(zzi); linearLayout.addView(textView); Intent zza = zze.zza(context, isGooglePlayServicesAvailable, null); if (zza != null) { View button = new Button(context); button.setId(16908313); button.setLayoutParams(new LayoutParams(-2, -2)); button.setText(zzk); linearLayout.addView(button); button.setOnClickListener(new zzf(context, zza)); } } protected abstract void zza(zzo<T> com_google_android_gms_dynamic_zzo_T); public final T zzapk() { return this.zzgtj; } }
shinkai-tester/python_beginner
Lesson4/matr.py
for i in range(1, 10): for j in range(1, 10): print(i * j, end=' ') print(end='\n')
amendoa/garden
src/js/components/validation.js
<filename>src/js/components/validation.js import $ from 'jquery' import emitter from '../utils/emitter' import rules from './validation/defaults' const NAME = 'validation' const DEFAULTS = { events: 'blur', selector: '[data-required]' } class Validation { constructor (element, options) { this.$element = $(element) this.options = $.extend({}, DEFAULTS, (options || {})) } init () { this._fields = this.$element.find(this.options.selector) this.bindListeners() return this } bindListeners () { this.handler = (e) => { this.validate(e.target) } this.$element.off(this.options.events, this.options.selector, this.handler) this.$element.on(this.options.events, this.options.selector, this.handler) } setPristine (field) { emitter.emit('validation:pristine', field) } validate (field) { let rules = field.getAttribute('data-validate') if (!rules) { return } rules = rules.split(' ').reduce((errors, rule) => { if (!this.rules[rule].call(this, field, this.$element)) { errors.push(rule) } return errors }, []) emitter.emit(`validation:${!rules.length ? 'success' : 'error'}`, field, rules) return !rules.length } validateAll () { return Array.prototype.map.call( this.getFilteredInputs(), this.validate, this ).every(validation => validation) } getFilteredInputs () { return Array.prototype.filter.call( this.$element.find(this.options.selector), this.getValidInputs ) } getValidInputs (input) { return input.hasAttribute('data-validate') } } Validation.prototype.rules = rules /* istanbul ignore next */ $.fn[NAME] = function (options) { options = options || {} return this.each(function () { if (!$.data(this, NAME)) { $.data(this, NAME, new Validation(this, options).init()) } }) } export default Validation
sousuke0422/Emojicord
shared/src/main/java/net/teamfruit/emojicord/emoji/EmojiFontRenderer.java
package net.teamfruit.emojicord.emoji; #if MC_14_LATER import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.client.renderer.RenderType; #endif #if MC_12_LATER import net.minecraft.client.gui.fonts.IGlyph; import net.minecraft.client.gui.fonts.TexturedGlyph; #endif #if MC_10_LATER import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Matrix4f; #endif import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.util.ResourceLocation; import net.teamfruit.emojicord.CoreInvoke; import net.teamfruit.emojicord.EmojicordConfig; import net.teamfruit.emojicord.EmojicordScope; import net.teamfruit.emojicord.compat.Compat; import net.teamfruit.emojicord.compat.CompatBaseVertex; import net.teamfruit.emojicord.compat.CompatVertex; import net.teamfruit.emojicord.compat.OpenGL; import net.teamfruit.emojicord.emoji.EmojiContext.EmojiContextAttribute; import net.teamfruit.emojicord.emoji.EmojiText.EmojiTextElement; import org.lwjgl.opengl.GL11; import javax.annotation.Nullable; import java.util.EnumSet; @CoreInvoke public class EmojiFontRenderer { @CoreInvoke public static boolean shadow; @CoreInvoke public static int index; private static EmojiContext CurrentContext; @CoreInvoke public static String updateEmojiContext(final String text) { if (EmojicordConfig.spec.isAvailable() && EmojicordConfig.RENDER.renderEnabled.get()) { final EnumSet<EmojiContextAttribute> attributes = EnumSet.noneOf(EmojiContextAttribute.class); final StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); if (EmojicordScope.instance.checkIsInput(stacks)) attributes.add(EmojiContextAttribute.CHAT_INPUT); if (EmojicordScope.instance.checkIsMessage(stacks)) attributes.add(EmojiContextAttribute.CHAT_MESSAGE); CurrentContext = EmojiContext.EmojiContextCache.instance.getContext(text, attributes); return CurrentContext.text; } CurrentContext = null; return text; } /* public static void main(final String... args) { Log.log.info("Start"); final int count = 1_000_000; Log.log.info("Count: "+count); final long time = System.nanoTime(); for (int i = 0; i<count; i++) Thread.currentThread().getStackTrace(); final long diff = System.nanoTime()-time; Log.log.info("Finish"); Log.log.info(diff/1e9); Log.log.info(diff/1e9/count); } */ #if MC_12_LATER public static abstract class CompatGlyph implements IGlyph { public final float width; public final float height; public CompatGlyph(final float width, final float height) { this.width = width; this.height = height; } @Override public float getAdvance() { return this.width; } @Override public float getBoldOffset() { return 0; } @Override public float getShadowOffset() { return 0; } } @CoreInvoke public static @Nullable EmojiGlyph getEmojiGlyph(final char c, final int index) { if (CurrentContext!=null) { final EmojiTextElement emojiElement = CurrentContext.emojis.get(index); if (emojiElement!=null) { final EmojiId emojiId = emojiElement.id; if (emojiId!=null) return new EmojiGlyph(emojiId); } } return null; } @CoreInvoke public static class EmojiGlyph extends CompatGlyph { public static final float GlyphWidth = 10; public static final float GlyphHeight = 10; private final EmojiId emojiId; public EmojiGlyph(final EmojiId emojiId) { super(GlyphWidth, GlyphHeight); this.emojiId = emojiId; } @CoreInvoke public EmojiTexturedGlyph getTexturedGlyph() { return new EmojiTexturedGlyph(this.emojiId); } } @CoreInvoke public static class EmojiTexturedGlyph extends TexturedGlyph { public EmojiTexturedGlyph(final ResourceLocation texture, final float width, final float height) { super( #if MC_14_LATER RenderType.getText(texture), RenderType.getTextSeeThrough(texture) #else texture #endif , 0, 1, 0, 1, 0, width, 0+3, height+3); } public EmojiTexturedGlyph(final EmojiId emojiId) { this(EmojiObject.EmojiObjectCache.instance.getEmojiObject(emojiId).loadAndGetResourceLocation(), EmojiGlyph.GlyphWidth, EmojiGlyph.GlyphHeight); } #if MC_14_LATER @Override public void render(boolean italic, float x, float y, Matrix4f matrix, IVertexBuilder vbuilder, float red, float green, float blue, float alpha, int packedLight) { if (!shadow) super.render(italic, x, y, matrix, vbuilder, 1, 1, 1, alpha, packedLight); } #else @Override public void render(final TextureManager textureManager, final boolean hasShadow, final float x, final float y, final BufferBuilder vbuilder, final float red, final float green, final float blue, final float alpha) { if (!shadow) super.render(textureManager, hasShadow, x, y, vbuilder, 1, 1, 1, alpha); } #endif } #else @CoreInvoke public static boolean renderEmojiChar(final char c, final boolean italic, final float x, final float y, final float red, final float green, final float blue, final float alpha) { if (CurrentContext != null) { final EmojiTextElement emojiElement = CurrentContext.emojis.get(index); if (emojiElement != null) { final EmojiId emojiId = emojiElement.id; if (emojiId != null) { final EmojiObject emoji = EmojiObject.EmojiObjectCache.instance.getEmojiObject(emojiId); if (!shadow) { Compat.getMinecraft().getTextureManager().bindTexture(emoji.loadAndGetResourceLocation()); renderEmoji(emoji, x, y, red, green, blue, alpha); } return c == EmojiContext.EMOJI_REPLACE_CHARACTOR; } } } return false; } public static void renderEmoji(final EmojiObject emoji, final float x, final float y, final float red, final float green, final float blue, final float alpha) { final float textureSize = 16.0F; final float textureX = 0.0F / textureSize; final float textureY = 0.0F / textureSize; final float textureOffset = 16.0F / textureSize; final float size = 10.0F; final float offsetY = 1.0F; final float offsetX = 0.0F; OpenGL.glPushAttrib(); final int rgba = OpenGL.glGetColorRGBA(); OpenGL.glColor4f(1.0F, 1.0F, 1.0F, (OpenGL.glGetColorRGBA() >> 24 & 0xff) / 256f); //OpenGL.glEnable(GL11.GL_BLEND); //OpenGL.glEnable(GL11.GL_ALPHA_TEST); //OpenGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); //OpenGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); //OpenGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); //OpenGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); final CompatBaseVertex bufferbuilder = CompatVertex.getTessellator(); bufferbuilder.beginTexture(GL11.GL_QUADS); bufferbuilder.pos(x - offsetX, y - offsetY, 0.0F).tex(textureX, textureY); bufferbuilder.pos(x - offsetX, y + size - offsetY, 0.0F).tex(textureX, textureY + textureOffset); bufferbuilder.pos(x - offsetX + size, y + size - offsetY, 0.0F).tex(textureX + textureOffset, textureY + textureOffset); bufferbuilder.pos(x - offsetX + size, y - offsetY, 0.0F).tex(textureX + textureOffset, textureY); bufferbuilder.draw(); //OpenGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); //OpenGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); //OpenGL.glDisable(GL11.GL_ALPHA_TEST); //OpenGL.glDisable(GL11.GL_BLEND); OpenGL.glColorRGBA(rgba); OpenGL.glPopAttrib(); } #endif }
holla-world/CRBoxInputView
Example/Pods/BearSkill/Pod/Layout/UIView+BearSet.h
<filename>Example/Pods/BearSkill/Pod/Layout/UIView+BearSet.h // // UIView+BearSet.h // // Created by bear on 15/11/25. // Copyright (c) 2015年 Bear. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSUInteger, kAXIS) { kAXIS_Y, kAXIS_X, kAXIS_X_Y, }; typedef NS_ENUM(NSUInteger, kLAYOUT_AXIS) { kLAYOUT_AXIS_Y, kLAYOUT_AXIS_X, }; typedef NS_ENUM(NSUInteger, kDIRECTION) { kDIR_LEFT, kDIR_RIGHT, kDIR_UP, kDIR_DOWN, }; typedef NS_ENUM(NSUInteger, SetNeedWHSort) { kSetNeed_Width, kSetNeed_Height, }; // 设置对齐类型 typedef NS_ENUM(NSUInteger, SetAlignmentType) { kSetAlignmentType_Idle, // 不处理对齐方式 kSetAlignmentType_Center, // 剧中对齐 kSetAlignmentType_Start, // 上/左对齐 kSetAlignmentType_End, // 下/右对齐 kSetAlignmentType_CustomCenter, // 自定义剧中的位置 }; // offParameter结构体 struct OffPara { CGFloat offStart; CGFloat offEnd; BOOL autoCalu; }; typedef struct OffPara OffPara; // offParameter内联 CG_INLINE OffPara OffParaMake(CGFloat offStart, CGFloat offEnd, BOOL autoCalu) { OffPara offPara; offPara.offStart = offStart; offPara.offEnd = offEnd; offPara.autoCalu = autoCalu; return offPara; } // gapParameter结构体 struct GapPara { CGFloat gapDistance; BOOL autoCalu; }; typedef struct GapPara GapPara; // gapParameter内联 CG_INLINE GapPara GapParaMake(CGFloat gapDistance, BOOL autoCalu) { GapPara gapPara; gapPara.gapDistance = gapDistance; gapPara.autoCalu = autoCalu; return gapPara; } @interface UIView (BearSet) /** * 普通的方法 */ - (void)removeAllSubViews; // 描边 - (void)setLine:(UIColor *)color cornerRadius:(NSUInteger)cornerRadius borderWidth:(CGFloat)borderWidth; // 毛玻璃效果处理 - (void)blurEffectWithStyle:(UIBlurEffectStyle)style Alpha:(CGFloat)alpha; // 设置边框 - (void)setMyBorder:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth; // 自定义分割线View OffY - (void)setMySeparatorLineOffY:(int)offStart offEnd:(int)offEnd lineWidth:(CGFloat)lineWidth lineColor:(UIColor *)lineColor offY:(CGFloat)offY; // 自定义底部分割线View - (void)setMySeparatorLine:(CGFloat)offStart offEnd:(CGFloat)offEnd lineWidth:(CGFloat)lineWidth lineColor:(UIColor *)lineColor; /** * 画线--View * 通过view,画横向/纵向的线 * * @param startPoint 起点 * @param endPoint 终点 * @param lineWidth 线宽 * @param lineColor 线颜色 * * @return view上绘制的线view */ - (UIView *)drawLine:(CGPoint)startPoint endPoint:(CGPoint)endPoint lineWidth:(CGFloat)lineWidth lineColor:(UIColor *)lineColor; // 通过layer,画任意方向的线 - (void)drawLineWithLayer:(CGPoint)startPoint endPoint:(CGPoint)endPoint lineWidth:(CGFloat)lineWidth lineColor:(UIColor *)lineColor; /** * 在View中绘制虚线 * * @param axis 横向/纵向绘制虚线 * @param dashColor 虚线颜色 * @param dashPattern 虚线间距数组,默认@[@3, @3] */ - (void)drawDashLineWithAxis:(kLAYOUT_AXIS)axis dashColor:(UIColor *)dashColor dashPattern:(NSArray<NSNumber *> *)dashPattern; /** * 虚线Layer * * @param axis 横向/纵向绘制虚线 * @param dashColor 虚线颜色 * @param dashPattern 虚线间距数组,默认@[@3, @3] */ + (CAShapeLayer *)dashLayerWithAxis:(kLAYOUT_AXIS)axis dashColor:(UIColor *)dashColor dashPattern:(NSArray<NSNumber *> *)dashPattern frame:(CGRect)frame; /** 在layer上添加分离图片 @param image 图片 @param rect 图片裁剪比例 CGRectMake(0, 0, 0.5, 0.5) @param contentsGravity 图片填充模式 */ - (void)addSpriteImage:(UIImage *)image withContentRect:(CGRect)rect contentsGravity:(NSString *)contentsGravity; /** * 布局扩展方法 */ // Getter - (CGFloat)x; - (CGFloat)y; - (CGFloat)maxX; - (CGFloat)maxY; - (CGFloat)width; - (CGFloat)height; - (CGPoint)origin; - (CGSize)size; - (CGFloat)centerX; - (CGFloat)centerY; //Setter - (void)setX:(CGFloat)x; - (void)setMaxX:(CGFloat)maxX; - (void)setMaxX_DontMoveMinX:(CGFloat)maxX; - (void)setY:(CGFloat)y; - (void)setMaxY:(CGFloat)maxY; - (void)setMaxY_DontMoveMinY:(CGFloat)maxY; - (void)setWidth:(CGFloat)width; - (void)setHeight:(CGFloat)height; - (void)setOrigin:(CGPoint)point; - (void)setOrigin:(CGPoint)point sizeToFit:(BOOL)sizeToFit; - (void)setSize:(CGSize)size; - (void)setCenterX:(CGFloat)x; - (void)setCenterY:(CGFloat)y; - (void)setWidth_DonotMoveCenter:(CGFloat)width; - (void)setHeight_DonotMoveCenter:(CGFloat)height; - (void)setSize_DonotMoveCenter:(CGSize)size; - (void)sizeToFit_DonotMoveCenter; - (void)sizeToFit_DonotMoveSide:(kDIRECTION)dir centerRemain:(BOOL)centerRemain; /** * 保持宽高比,自动设置Size * * @param referWidth 参考宽度 * @param referHeight 参考高度 * @param setWidth 实际宽度,自动计算高度 */ - (void)BearSetSizeRemainWHRatio_referWidth:(NSNumber *)referWidth referHeight:(NSNumber *)referHeight setSort:(SetNeedWHSort)setSort setValue:(NSNumber *)setValue; /** * 保持宽高比,自动设置Size * * @param referWidth 参考宽度 * @param referHeight 参考高度 * @param setWidth 实际宽度,自动计算高度 * * @return * setSort == kSetNeed_Width时,返回高度 * setSort == kSetNeed_Height时,返回宽度 */ + (CGSize)caculateSizeRemainWHRatio_referWidth:(NSNumber *)referWidth referHeight:(NSNumber *)referHeight setSort:(SetNeedWHSort)setSort setValue:(NSNumber *)setValue; /** * 保持宽高比,自动设置Bounds * * @param referWidth 参考宽度 * @param referHeight 参考高度 * @param setWidth 实际宽度,自动计算高度 * * @return * setSort == kSetNeed_Width时,返回高度 * setSort == kSetNeed_Height时,返回宽度 */ + (CGRect)caculateBoundsRemainWHRatio_referWidth:(NSNumber *)referWidth referHeight:(NSNumber *)referHeight setSort:(SetNeedWHSort)setSort setValue:(NSNumber *)setValue; /** * 和父类view剧中 * * 当前view和父类view的 X轴/Y轴/中心点 对其 */ - (void)BearSetCenterToParentViewWithAxis:(kAXIS)axis; /** * 和指定的view剧中 * * 当前view和指定view的 X轴/Y轴/中心点 对其 */ - (void)BearSetCenterToView:(UIView *)destinationView withAxis:(kAXIS)axis; /** * view与view的相对位置 */ - (void)BearSetRelativeLayoutWithDirection:(kDIRECTION)direction destinationView:(UIView *)destinationView parentRelation:(BOOL)parentRelation distance:(CGFloat)distance center:(BOOL)center; /** * view的相对布局,带sizeToFit */ - (void)BearSetRelativeLayoutWithDirection:(kDIRECTION)direction destinationView:(UIView *)destinationView parentRelation:(BOOL)parentRelation distance:(CGFloat)distance center:(BOOL)center sizeToFit:(BOOL)sizeToFit; #pragma mark - AutoLay V1 /** * 根据子view自动布局 -- 自动计算:起始点,结束点,间距(三值相等) * 说明: 在父类view尺寸不等于需求尺寸时,会显示日志并且取消布局 */ + (void)BearAutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis center:(BOOL)center; /** * 根据子view自动布局 -- 需要设置:起始点,结束点; -- 自动计算:间距 * 说明: 在父类view尺寸不等于需求尺寸时,会显示日志并且取消布局 */ + (void)BearAutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis center:(BOOL)center offStart:(CGFloat)offStart offEnd:(CGFloat)offEnd; /** * 根据子view自动布局 -- 需要设置:间距; -- 自动计算:起始点,结束点 * 说明: 在父类view尺寸不等于需求尺寸时,会显示日志并且取消布局 */ + (void)BearAutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis center:(BOOL)center gapDistance:(CGFloat)gapDistance; /** * 根据子view自动布局 -- 需要设置:起始点,结束点,间距 * 说明: 在父类view尺寸不等于需求尺寸时,会自动变化 */ + (void)BearAutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis center:(BOOL)center offStart:(CGFloat)offStart offEnd:(CGFloat)offEnd gapDistance:(CGFloat)gapDistance; /** * 根据子view自动布局 -- 需要设置:gapArray间距比例数组,间距总和 * 说明: 在父类view尺寸不等于需求尺寸时,会自动变化 */ + (void)BearAutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis center:(BOOL)center gapAray:(NSArray *)gapArray gapDisAll:(CGFloat)gapDisAll; /** * 根据子view自动布局 -- 需要设置:gapArray间距比例数组; -- 自动计算:间距总和 * 说明: 在父类view尺寸不等于需求尺寸时,无法自动布局 */ + (void)BearAutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis center:(BOOL)center gapAray:(NSArray *)gapArray; #pragma mark - AutoLay V2 /** * 根据子view自动布局 -- 自动计算:起始点,结束点,间距(三值相等) * 说明: 在父类view尺寸不等于需求尺寸时,会显示日志并且取消布局 */ + (void)BearV2AutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis alignmentType:(SetAlignmentType)alignmentType alignmentOffDis:(CGFloat)alignmentOffDis; /** * 根据子view自动布局 -- 需要设置:起始点,结束点; -- 自动计算:间距 * 说明: 在父类view尺寸不等于需求尺寸时,会显示日志并且取消布局 */ + (void)BearV2AutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis alignmentType:(SetAlignmentType)alignmentType alignmentOffDis:(CGFloat)alignmentOffDis offStart:(CGFloat)offStart offEnd:(CGFloat)offEnd; /** * 根据子view自动布局 -- 需要设置:间距; -- 自动计算:起始点,结束点 * 说明: 在父类view尺寸不等于需求尺寸时,会显示日志并且取消布局 */ + (void)BearV2AutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis alignmentType:(SetAlignmentType)alignmentType alignmentOffDis:(CGFloat)alignmentOffDis gapDistance:(CGFloat)gapDistance; /** * 根据子view自动布局 -- 需要设置:起始点,结束点,间距 * 说明: 在父类view尺寸不等于需求尺寸时,会自动变化 */ + (void)BearV2AutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis alignmentType:(SetAlignmentType)alignmentType alignmentOffDis:(CGFloat)alignmentOffDis offStart:(CGFloat)offStart offEnd:(CGFloat)offEnd gapDistance:(CGFloat)gapDistance; /** * 根据子view自动布局 -- 需要设置:gapArray间距比例数组,间距总和 * 说明: 在父类view尺寸不等于需求尺寸时,会自动变化 */ + (void)BearV2AutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis alignmentType:(SetAlignmentType)alignmentType alignmentOffDis:(CGFloat)alignmentOffDis gapAray:(NSArray *)gapArray gapDisAll:(CGFloat)gapDisAll; /** * 根据子view自动布局 -- 需要设置:gapArray间距比例数组; -- 自动计算:间距总和 * 说明: 在父类view尺寸不等于需求尺寸时,无法自动布局 */ + (void)BearV2AutoLayViewArray:(NSMutableArray *)viewArray layoutAxis:(kLAYOUT_AXIS)layoutAxis alignmentType:(SetAlignmentType)alignmentType alignmentOffDis:(CGFloat)alignmentOffDis gapAray:(NSArray *)gapArray; @end
dealflowteam/Idfy
idfy_rest_client/models/transaction.py
# -*- coding: utf-8 -*- """ idfy_rest_client.models.transaction This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ from idfy_rest_client.api_helper import APIHelper class Transaction(object): """Implementation of the 'Transaction' model. TODO: type model description here. Attributes: id (string): Transaction ID date (datetime): The date for the transaction product_id (string): Product ID (SIGN, IDENTIFICATION etc) description (string): Transaction description count (int): Number of transactions for the selected date customer_number (int): Your customer number in our invocing system external_reference (string): Your reference to the transaction (by ExternalRef in the API call) department_id (string): The Departments ID if specified """ # Create a mapping from Model property names to API property names _names = { "id":'ID', "date":'Date', "product_id":'ProductID', "description":'Description', "count":'Count', "customer_number":'CustomerNumber', "external_reference":'ExternalReference', "department_id":'DepartmentId' } def __init__(self, id=None, date=None, product_id=None, description=None, count=None, customer_number=None, external_reference=None, department_id=None, additional_properties = {}): """Constructor for the Transaction class""" # Initialize members of the class self.id = id self.date = APIHelper.RFC3339DateTime(date) if date else None self.product_id = product_id self.description = description self.count = count self.customer_number = customer_number self.external_reference = external_reference self.department_id = department_id # Add additional model properties to the instance self.additional_properties = additional_properties @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary id = dictionary.get('ID') date = APIHelper.RFC3339DateTime.from_value(dictionary.get("Date")).datetime if dictionary.get("Date") else None product_id = dictionary.get('ProductID') description = dictionary.get('Description') count = dictionary.get('Count') customer_number = dictionary.get('CustomerNumber') external_reference = dictionary.get('ExternalReference') department_id = dictionary.get('DepartmentId') # Clean out expected properties from dictionary for key in cls._names.values(): if key in dictionary: del dictionary[key] # Return an object of this model return cls(id, date, product_id, description, count, customer_number, external_reference, department_id, dictionary)
suggestio/suggestio
src1/server/www/app/models/mext/tw/TwitterService.scala
package models.mext.tw import io.suggest.ext.svc.MExtServices import models.mext.{IAdvExtService, IExtService} import util.adv.ext.OAuth1ServiceActorFactory import util.ext.tw.TwitterHelper import scala.reflect.ClassTag /** * Suggest.io * User: <NAME> <<EMAIL>> * Created: 10.04.15 19:14 * Description: Абстрактная реализация twitter-сервиса. */ class TwitterService extends IExtService with IAdvExtService { override def advExt = this override def dfltTargetUrl = Some( MExtServices.Twitter.mainPageUrl ) override def helperCt = ClassTag( classOf[TwitterHelper] ) /** twitter работает через OAuth1. */ override def extAdvServiceActorFactoryCt = ClassTag( classOf[OAuth1ServiceActorFactory] ) override def cspSrcDomains: Iterable[String] = { "*.twitter.com" :: Nil } }
laszlomakk/BonjourKeyGossiping
app/src/main/java/uk/ac/cam/cl/lm649/bonjourtesting/messaging/MsgServerManager.java
/** Copyright (C) 2016 <NAME> All code under the BonjourTesting project is licensed under the Apache 2.0 License */ package uk.ac.cam.cl.lm649.bonjourtesting.messaging; import java.io.IOException; import java.util.concurrent.ConcurrentSkipListMap; import uk.ac.cam.cl.lm649.bonjourtesting.util.FLogger; import uk.ac.cam.cl.lm649.bonjourtesting.bonjour.ServiceStub; public final class MsgServerManager { private final static String TAG = "MsgServerManager"; private static MsgServerManager INSTANCE = null; public final ConcurrentSkipListMap<ServiceStub, MsgClient> serviceToMsgClientMap = new ConcurrentSkipListMap<>(); private final MsgServerPlaintext msgServerPlaintext; private final MsgServerEncrypted msgServerEncrypted; private MsgServerManager() { msgServerPlaintext = new MsgServerPlaintext(); msgServerEncrypted = new MsgServerEncrypted(); } public static synchronized MsgServerManager getInstance() { if (null == INSTANCE) { INSTANCE = new MsgServerManager(); } return INSTANCE; } public void start() throws IOException { FLogger.i(TAG, "start() called."); msgServerPlaintext.start(); msgServerEncrypted.start(); } public void stop(){ FLogger.i(TAG, "stop() called."); msgServerPlaintext.stop(); msgServerEncrypted.stop(); for (MsgClient msgClient : serviceToMsgClientMap.values()) { msgClient.close(); } serviceToMsgClientMap.clear(); } public MsgServerPlaintext getMsgServerPlaintext() { return msgServerPlaintext; } public MsgServerEncrypted getMsgServerEncrypted() { return msgServerEncrypted; } }
fugroup/mongocore
test/json_test.rb
test 'JSON' model = Model.new parent = Parent.new model.parent = parent is model.save json = JSON.parse(model.to_json) is json['id'], :a? => String is json['parent_id'], :a? => String is json['duration'], :a? => Integer o = BSON::ObjectId.new is o.to_json, "\"#{o.to_s}\"" t = {:id => o} is t.to_json, "{\"id\":\"#{o.to_s}\"}" t = {:id => [o, o]} is t.to_json, "{\"id\":[\"#{o.to_s}\",\"#{o.to_s}\"]}"
Cwc-Test/CpcdosOS2.1
build/djgpp/include/sys/nearptr.h
/* Copyright (C) 2012 <NAME>, see COPYING.DJ for details */ /* Copyright (C) 2003 <NAME>, see COPYING.DJ for details */ /* Copyright (C) 1995 <NAME>, see COPYING.DJ for details */ #ifndef __dj_include_sys_nearptr_h_ #define __dj_include_sys_nearptr_h_ #ifdef __cplusplus extern "C" { #endif #ifndef __dj_ENFORCE_ANSI_FREESTANDING #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) \ || !defined(__STRICT_ANSI__) || defined(__cplusplus) #endif /* (__STDC_VERSION__ >= 199901L) || !__STRICT_ANSI__ */ #ifndef __STRICT_ANSI__ #ifndef _POSIX_SOURCE /* Functions to enable "near" pointer access to DOS memory under DPMI CW Sandmann 7-95 NO WARRANTY: WARNING, since these functions disable memory protection, they MAY DESTROY EVERYTHING ON YOUR COMPUTER! */ int __djgpp_nearptr_enable(void); /* Returns 0 if feature not avail */ void __djgpp_nearptr_disable(void); /* Enables protection */ extern int __djgpp_selector_limit; /* Limit on CS and on DS if prot */ extern int __djgpp_base_address; /* Used in calculation below */ #define __djgpp_conventional_base (-__djgpp_base_address) #endif /* !_POSIX_SOURCE */ #endif /* !__STRICT_ANSI__ */ #endif /* !__dj_ENFORCE_ANSI_FREESTANDING */ #ifndef __dj_ENFORCE_FUNCTION_CALLS #endif /* !__dj_ENFORCE_FUNCTION_CALLS */ #ifdef __cplusplus } #endif #endif /* !__dj_include_sys_nearptr_h_ */