code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import * as React from "react"; import { Trans } from "@lingui/macro"; import { Badge, designTokens as dt, Icon, Legacy } from "@dcos/ui-kit"; import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum"; import DateUtil from "../utils/DateUtil"; const YEAR = 31557600000; const isOutdated = (lastUpdatedAt: string) => DateUtil.strToMs(lastUpdatedAt) < Date.now() - YEAR; export const warningIcon = (lastUpdatedAt: string) => isOutdated(lastUpdatedAt) ? ( <Legacy.Tooltip content={ <Trans render="span"> This service has not been updated for at least 1 year. We recommend you update if possible. </Trans> } data-cy="outdated-warning" interactive={true} maxWidth={250} wrapText={true} > <Icon color={dt.yellow} shape={SystemIcons.Yield} size={dt.iconSizeXs} /> </Legacy.Tooltip> ) : null; export const render = (lastUpdatedAt: string) => ( <span data-cy="last-updated"> <Trans>Last Updated: {lastUpdatedAt}</Trans>{" "} {isOutdated(lastUpdatedAt) ? ( <span className="badge-outline-warning"> <Badge appearance="outline"> <span> {warningIcon(lastUpdatedAt)} <Trans id="Outdated Version" /> </span> </Badge> </span> ) : null} </span> );
dcos/dcos-ui
src/js/components/LastUpdated.tsx
TypeScript
apache-2.0
1,334
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.schemaorg.core; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.schemaorg.SchemaOrgTypeImpl; import com.google.schemaorg.ValueType; import com.google.schemaorg.core.datatype.DateTime; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.GoogConstants; import com.google.schemaorg.goog.PopularityScoreSpecification; /** Implementation of {@link DepartAction}. */ public class DepartActionImpl extends MoveActionImpl implements DepartAction { private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet(); private static ImmutableSet<String> initializePropertySet() { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add(CoreConstants.PROPERTY_ACTION_STATUS); builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE); builder.add(CoreConstants.PROPERTY_AGENT); builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME); builder.add(CoreConstants.PROPERTY_DESCRIPTION); builder.add(CoreConstants.PROPERTY_END_TIME); builder.add(CoreConstants.PROPERTY_ERROR); builder.add(CoreConstants.PROPERTY_FROM_LOCATION); builder.add(CoreConstants.PROPERTY_IMAGE); builder.add(CoreConstants.PROPERTY_INSTRUMENT); builder.add(CoreConstants.PROPERTY_LOCATION); builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE); builder.add(CoreConstants.PROPERTY_NAME); builder.add(CoreConstants.PROPERTY_OBJECT); builder.add(CoreConstants.PROPERTY_PARTICIPANT); builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION); builder.add(CoreConstants.PROPERTY_RESULT); builder.add(CoreConstants.PROPERTY_SAME_AS); builder.add(CoreConstants.PROPERTY_START_TIME); builder.add(CoreConstants.PROPERTY_TARGET); builder.add(CoreConstants.PROPERTY_TO_LOCATION); builder.add(CoreConstants.PROPERTY_URL); builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION); builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE); return builder.build(); } static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<DepartAction.Builder> implements DepartAction.Builder { @Override public DepartAction.Builder addActionStatus(ActionStatusType value) { return addProperty(CoreConstants.PROPERTY_ACTION_STATUS, value); } @Override public DepartAction.Builder addActionStatus(String value) { return addProperty(CoreConstants.PROPERTY_ACTION_STATUS, Text.of(value)); } @Override public DepartAction.Builder addAdditionalType(URL value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value); } @Override public DepartAction.Builder addAdditionalType(String value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value)); } @Override public DepartAction.Builder addAgent(Organization value) { return addProperty(CoreConstants.PROPERTY_AGENT, value); } @Override public DepartAction.Builder addAgent(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_AGENT, value.build()); } @Override public DepartAction.Builder addAgent(Person value) { return addProperty(CoreConstants.PROPERTY_AGENT, value); } @Override public DepartAction.Builder addAgent(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_AGENT, value.build()); } @Override public DepartAction.Builder addAgent(String value) { return addProperty(CoreConstants.PROPERTY_AGENT, Text.of(value)); } @Override public DepartAction.Builder addAlternateName(Text value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value); } @Override public DepartAction.Builder addAlternateName(String value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value)); } @Override public DepartAction.Builder addDescription(Text value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value); } @Override public DepartAction.Builder addDescription(String value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value)); } @Override public DepartAction.Builder addEndTime(DateTime value) { return addProperty(CoreConstants.PROPERTY_END_TIME, value); } @Override public DepartAction.Builder addEndTime(String value) { return addProperty(CoreConstants.PROPERTY_END_TIME, Text.of(value)); } @Override public DepartAction.Builder addError(Thing value) { return addProperty(CoreConstants.PROPERTY_ERROR, value); } @Override public DepartAction.Builder addError(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_ERROR, value.build()); } @Override public DepartAction.Builder addError(String value) { return addProperty(CoreConstants.PROPERTY_ERROR, Text.of(value)); } @Override public DepartAction.Builder addFromLocation(Place value) { return addProperty(CoreConstants.PROPERTY_FROM_LOCATION, value); } @Override public DepartAction.Builder addFromLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_FROM_LOCATION, value.build()); } @Override public DepartAction.Builder addFromLocation(String value) { return addProperty(CoreConstants.PROPERTY_FROM_LOCATION, Text.of(value)); } @Override public DepartAction.Builder addImage(ImageObject value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public DepartAction.Builder addImage(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value.build()); } @Override public DepartAction.Builder addImage(URL value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public DepartAction.Builder addImage(String value) { return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value)); } @Override public DepartAction.Builder addInstrument(Thing value) { return addProperty(CoreConstants.PROPERTY_INSTRUMENT, value); } @Override public DepartAction.Builder addInstrument(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_INSTRUMENT, value.build()); } @Override public DepartAction.Builder addInstrument(String value) { return addProperty(CoreConstants.PROPERTY_INSTRUMENT, Text.of(value)); } @Override public DepartAction.Builder addLocation(Place value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public DepartAction.Builder addLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value.build()); } @Override public DepartAction.Builder addLocation(PostalAddress value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public DepartAction.Builder addLocation(PostalAddress.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value.build()); } @Override public DepartAction.Builder addLocation(Text value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public DepartAction.Builder addLocation(String value) { return addProperty(CoreConstants.PROPERTY_LOCATION, Text.of(value)); } @Override public DepartAction.Builder addMainEntityOfPage(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public DepartAction.Builder addMainEntityOfPage(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build()); } @Override public DepartAction.Builder addMainEntityOfPage(URL value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public DepartAction.Builder addMainEntityOfPage(String value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value)); } @Override public DepartAction.Builder addName(Text value) { return addProperty(CoreConstants.PROPERTY_NAME, value); } @Override public DepartAction.Builder addName(String value) { return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value)); } @Override public DepartAction.Builder addObject(Thing value) { return addProperty(CoreConstants.PROPERTY_OBJECT, value); } @Override public DepartAction.Builder addObject(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_OBJECT, value.build()); } @Override public DepartAction.Builder addObject(String value) { return addProperty(CoreConstants.PROPERTY_OBJECT, Text.of(value)); } @Override public DepartAction.Builder addParticipant(Organization value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value); } @Override public DepartAction.Builder addParticipant(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value.build()); } @Override public DepartAction.Builder addParticipant(Person value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value); } @Override public DepartAction.Builder addParticipant(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value.build()); } @Override public DepartAction.Builder addParticipant(String value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, Text.of(value)); } @Override public DepartAction.Builder addPotentialAction(Action value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value); } @Override public DepartAction.Builder addPotentialAction(Action.Builder value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build()); } @Override public DepartAction.Builder addPotentialAction(String value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value)); } @Override public DepartAction.Builder addResult(Thing value) { return addProperty(CoreConstants.PROPERTY_RESULT, value); } @Override public DepartAction.Builder addResult(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_RESULT, value.build()); } @Override public DepartAction.Builder addResult(String value) { return addProperty(CoreConstants.PROPERTY_RESULT, Text.of(value)); } @Override public DepartAction.Builder addSameAs(URL value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, value); } @Override public DepartAction.Builder addSameAs(String value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value)); } @Override public DepartAction.Builder addStartTime(DateTime value) { return addProperty(CoreConstants.PROPERTY_START_TIME, value); } @Override public DepartAction.Builder addStartTime(String value) { return addProperty(CoreConstants.PROPERTY_START_TIME, Text.of(value)); } @Override public DepartAction.Builder addTarget(EntryPoint value) { return addProperty(CoreConstants.PROPERTY_TARGET, value); } @Override public DepartAction.Builder addTarget(EntryPoint.Builder value) { return addProperty(CoreConstants.PROPERTY_TARGET, value.build()); } @Override public DepartAction.Builder addTarget(String value) { return addProperty(CoreConstants.PROPERTY_TARGET, Text.of(value)); } @Override public DepartAction.Builder addToLocation(Place value) { return addProperty(CoreConstants.PROPERTY_TO_LOCATION, value); } @Override public DepartAction.Builder addToLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_TO_LOCATION, value.build()); } @Override public DepartAction.Builder addToLocation(String value) { return addProperty(CoreConstants.PROPERTY_TO_LOCATION, Text.of(value)); } @Override public DepartAction.Builder addUrl(URL value) { return addProperty(CoreConstants.PROPERTY_URL, value); } @Override public DepartAction.Builder addUrl(String value) { return addProperty(CoreConstants.PROPERTY_URL, Text.of(value)); } @Override public DepartAction.Builder addDetailedDescription(Article value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value); } @Override public DepartAction.Builder addDetailedDescription(Article.Builder value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build()); } @Override public DepartAction.Builder addDetailedDescription(String value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value)); } @Override public DepartAction.Builder addPopularityScore(PopularityScoreSpecification value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value); } @Override public DepartAction.Builder addPopularityScore(PopularityScoreSpecification.Builder value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build()); } @Override public DepartAction.Builder addPopularityScore(String value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value)); } @Override public DepartAction build() { return new DepartActionImpl(properties, reverseMap); } } public DepartActionImpl( Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) { super(properties, reverseMap); } @Override public String getFullTypeName() { return CoreConstants.TYPE_DEPART_ACTION; } @Override public boolean includesProperty(String property) { return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property) || PROPERTY_SET.contains(GoogConstants.NAMESPACE + property) || PROPERTY_SET.contains(property); } }
google/schemaorg-java
src/main/java/com/google/schemaorg/core/impl/DepartActionImpl.java
Java
apache-2.0
14,918
/********************************************************************************************************************** * 描述: * 字典排序。 * * 变更历史: * 作者:李亮 时间:2017年01月04日 新建 * *********************************************************************************************************************/ using System.Collections; namespace Wlitsoft.Framework.WeixinSDK.Message.Security.Crypto { /// <summary> /// 字典排序。 /// <para>微信官方提供。</para> /// </summary> internal sealed class DictionarySort : IComparer { public int Compare(object oLeft, object oRight) { string sLeft = oLeft as string; string sRight = oRight as string; int iLeftLength = sLeft.Length; int iRightLength = sRight.Length; int index = 0; while (index < iLeftLength && index < iRightLength) { if (sLeft[index] < sRight[index]) return -1; else if (sLeft[index] > sRight[index]) return 1; else index++; } return iLeftLength - iRightLength; } } }
Wlitsoft/WeixinSDK
src/WeixinSDK/Message/Security/Crypto/DictionarySort.cs
C#
apache-2.0
1,269
/** * Copyright (c) 2013-2019 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.service.client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.Response; import org.glassfish.jersey.client.proxy.WebResourceFactory; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.locationtech.geowave.service.BaseService; public class BaseServiceClient { private final BaseService baseService; public BaseServiceClient(final String baseUrl) { this(baseUrl, null, null); } public BaseServiceClient(final String baseUrl, final String user, final String password) { baseService = WebResourceFactory.newResource( BaseService.class, ClientBuilder.newClient().register(MultiPartFeature.class).target(baseUrl)); } public Response operation_status(final String id) { final Response resp = baseService.operation_status(id); return resp; } }
spohnan/geowave
services/client/src/main/java/org/locationtech/geowave/service/client/BaseServiceClient.java
Java
apache-2.0
1,316
package com.site.blog.my.core.entity; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class Blog { private Long blogId; private String blogTitle; private String blogSubUrl; private String blogCoverImage; private Integer blogCategoryId; private String blogCategoryName; private String blogTags; private Byte blogStatus; private Long blogViews; private Byte enableComment; private Byte isDeleted; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; private Date updateTime; private String blogContent; public Long getBlogId() { return blogId; } public void setBlogId(Long blogId) { this.blogId = blogId; } public String getBlogTitle() { return blogTitle; } public void setBlogTitle(String blogTitle) { this.blogTitle = blogTitle == null ? null : blogTitle.trim(); } public String getBlogSubUrl() { return blogSubUrl; } public void setBlogSubUrl(String blogSubUrl) { this.blogSubUrl = blogSubUrl == null ? null : blogSubUrl.trim(); } public String getBlogCoverImage() { return blogCoverImage; } public void setBlogCoverImage(String blogCoverImage) { this.blogCoverImage = blogCoverImage == null ? null : blogCoverImage.trim(); } public Integer getBlogCategoryId() { return blogCategoryId; } public void setBlogCategoryId(Integer blogCategoryId) { this.blogCategoryId = blogCategoryId; } public String getBlogCategoryName() { return blogCategoryName; } public void setBlogCategoryName(String blogCategoryName) { this.blogCategoryName = blogCategoryName == null ? null : blogCategoryName.trim(); } public String getBlogTags() { return blogTags; } public void setBlogTags(String blogTags) { this.blogTags = blogTags == null ? null : blogTags.trim(); } public Byte getBlogStatus() { return blogStatus; } public void setBlogStatus(Byte blogStatus) { this.blogStatus = blogStatus; } public Long getBlogViews() { return blogViews; } public void setBlogViews(Long blogViews) { this.blogViews = blogViews; } public Byte getEnableComment() { return enableComment; } public void setEnableComment(Byte enableComment) { this.enableComment = enableComment; } public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getBlogContent() { return blogContent; } public void setBlogContent(String blogContent) { this.blogContent = blogContent == null ? null : blogContent.trim(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", blogId=").append(blogId); sb.append(", blogTitle=").append(blogTitle); sb.append(", blogSubUrl=").append(blogSubUrl); sb.append(", blogCoverImage=").append(blogCoverImage); sb.append(", blogCategoryId=").append(blogCategoryId); sb.append(", blogCategoryName=").append(blogCategoryName); sb.append(", blogTags=").append(blogTags); sb.append(", blogStatus=").append(blogStatus); sb.append(", blogViews=").append(blogViews); sb.append(", enableComment=").append(enableComment); sb.append(", isDeleted=").append(isDeleted); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append(", blogContent=").append(blogContent); sb.append("]"); return sb.toString(); } }
ZHENFENG13/My-Blog
src/main/java/com/site/blog/my/core/entity/Blog.java
Java
apache-2.0
4,282
package sblib.bobsun.sblib.net; import android.content.Context; import android.os.Handler; import android.os.Message; import java.lang.reflect.Method; import java.util.Objects; import sblib.bobsun.sblib.net.annotations.NetworkResult; /** * Created by bobsun on 15-7-7. */ public abstract class NetworkOperation { private String mTag; private Object mObject; private OnFinishHandler mHandler; public NetworkOperation(Object object, String operationTag){ this.mTag = operationTag; this.mObject = object; } public NetworkOperation(OnFinishHandler handler){ this.mHandler = handler; } public abstract OperationResult doNetworkOperation(); public void run(){ new Thread(new Runnable() { @Override public void run() { OperationResult result = doNetworkOperation(); if (result == null) throw new NullPointerException("Function doNetworkOperation can not return null!"); mHandler.returnResult(result); } }).start(); } // private void findHandlerAndRun(){ // for (Method method : mObject.getClass().getDeclaredMethods()){ // if (method.isAnnotationPresent(NetworkResult.class)){ // // } // } // } }
SpongeBobSun/SBLib
sblib/src/main/java/sblib/bobsun/sblib/net/NetworkOperation.java
Java
apache-2.0
1,329
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.web3j.springboot; import java.math.BigInteger; import java.util.List; import javax.annotation.Generated; import org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon; import org.springframework.boot.context.properties.ConfigurationProperties; import org.web3j.protocol.Web3j; /** * The web3j component uses the Web3j client API and allows you to add/read * nodes to/from a web3j compliant content repositories. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @ConfigurationProperties(prefix = "camel.component.web3j") public class Web3jComponentConfiguration extends ComponentConfigurationPropertiesCommon { /** * Whether to enable auto configuration of the web3j component. This is * enabled by default. */ private Boolean enabled; /** * Default configuration */ private Web3jConfigurationNestedConfiguration configuration; /** * Whether the component should resolve property placeholders on itself when * starting. Only properties which are of String type can use property * placeholders. */ private Boolean resolvePropertyPlaceholders = true; public Web3jConfigurationNestedConfiguration getConfiguration() { return configuration; } public void setConfiguration( Web3jConfigurationNestedConfiguration configuration) { this.configuration = configuration; } public Boolean getResolvePropertyPlaceholders() { return resolvePropertyPlaceholders; } public void setResolvePropertyPlaceholders( Boolean resolvePropertyPlaceholders) { this.resolvePropertyPlaceholders = resolvePropertyPlaceholders; } public static class Web3jConfigurationNestedConfiguration { public static final Class CAMEL_NESTED_CLASS = org.apache.camel.component.web3j.Web3jConfiguration.class; /** * The preconfigured Web3j object. */ private Web3j web3j; /** * The priority of a whisper message. */ private BigInteger priority; /** * The time to live in seconds of a whisper message. */ private BigInteger ttl; /** * Gas price used for each paid gas. */ private BigInteger gasPrice; /** * The maximum gas allowed in this block. */ private BigInteger gasLimit; /** * The value sent within a transaction. */ private BigInteger value; /** * The compiled code of a contract OR the hash of the invoked method * signature and encoded parameters. */ private String data; /** * The address the transaction is send from */ private String fromAddress; /** * The address the transaction is directed to. */ private String toAddress; /** * A random hexadecimal(32 bytes) ID identifying the client. */ private String clientId; /** * A hexadecimal string representation (32 bytes) of the hash rate. */ private String hashrate; /** * The mix digest (256 bits) used for submitting a proof-of-work * solution. */ private String mixDigest; /** * The header's pow-hash (256 bits) used for submitting a proof-of-work * solution. */ private String headerPowHash; /** * The nonce found (64 bits) used for submitting a proof-of-work * solution. */ private String nonce; /** * The source code to compile. */ private String sourceCode; /** * The information about a transaction requested by transaction hash. */ private String transactionHash; /** * The local database name. */ private String databaseName; /** * The key name in the database. */ private String keyName; /** * The filter id to use. */ private BigInteger filterId; /** * The transactions/uncle index position in the block. */ private BigInteger index; /** * The signed transaction data for a new message call transaction or a * contract creation for signed transactions. */ private String signedTransactionData; /** * Hash of the block where this transaction was in. */ private String blockHash; /** * Message to sign by calculating an Ethereum specific signature. */ private String sha3HashOfDataToSign; /** * The transaction index position withing a block. */ private BigInteger position; /** * Contract address or a list of addresses. */ private List addresses; /** * Topics are order-dependent. Each topic can also be a list of topics. * Specify multiple topics separated by comma. */ private List topics; /** * Contract address. */ private String address; /** * If true it returns the full transaction objects, if false only the * hashes of the transactions. */ private Boolean fullTransactionObjects = false; /** * Operation to use. */ private String operation = "transaction"; public Web3j getWeb3j() { return web3j; } public void setWeb3j(Web3j web3j) { this.web3j = web3j; } public BigInteger getPriority() { return priority; } public void setPriority(BigInteger priority) { this.priority = priority; } public BigInteger getTtl() { return ttl; } public void setTtl(BigInteger ttl) { this.ttl = ttl; } public BigInteger getGasPrice() { return gasPrice; } public void setGasPrice(BigInteger gasPrice) { this.gasPrice = gasPrice; } public BigInteger getGasLimit() { return gasLimit; } public void setGasLimit(BigInteger gasLimit) { this.gasLimit = gasLimit; } public BigInteger getValue() { return value; } public void setValue(BigInteger value) { this.value = value; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getHashrate() { return hashrate; } public void setHashrate(String hashrate) { this.hashrate = hashrate; } public String getMixDigest() { return mixDigest; } public void setMixDigest(String mixDigest) { this.mixDigest = mixDigest; } public String getHeaderPowHash() { return headerPowHash; } public void setHeaderPowHash(String headerPowHash) { this.headerPowHash = headerPowHash; } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public String getSourceCode() { return sourceCode; } public void setSourceCode(String sourceCode) { this.sourceCode = sourceCode; } public String getTransactionHash() { return transactionHash; } public void setTransactionHash(String transactionHash) { this.transactionHash = transactionHash; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getKeyName() { return keyName; } public void setKeyName(String keyName) { this.keyName = keyName; } public BigInteger getFilterId() { return filterId; } public void setFilterId(BigInteger filterId) { this.filterId = filterId; } public BigInteger getIndex() { return index; } public void setIndex(BigInteger index) { this.index = index; } public String getSignedTransactionData() { return signedTransactionData; } public void setSignedTransactionData(String signedTransactionData) { this.signedTransactionData = signedTransactionData; } public String getBlockHash() { return blockHash; } public void setBlockHash(String blockHash) { this.blockHash = blockHash; } public String getSha3HashOfDataToSign() { return sha3HashOfDataToSign; } public void setSha3HashOfDataToSign(String sha3HashOfDataToSign) { this.sha3HashOfDataToSign = sha3HashOfDataToSign; } public BigInteger getPosition() { return position; } public void setPosition(BigInteger position) { this.position = position; } public List getAddresses() { return addresses; } public void setAddresses(List addresses) { this.addresses = addresses; } public List getTopics() { return topics; } public void setTopics(List topics) { this.topics = topics; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Boolean getFullTransactionObjects() { return fullTransactionObjects; } public void setFullTransactionObjects(Boolean fullTransactionObjects) { this.fullTransactionObjects = fullTransactionObjects; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } } }
dmvolod/camel
platforms/spring-boot/components-starter/camel-web3j-starter/src/main/java/org/apache/camel/component/web3j/springboot/Web3jComponentConfiguration.java
Java
apache-2.0
11,965
/* * Copyright (c) 2012-2015 S-Core 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. */ define(['other-lib/underscore/lodash.min', 'webida-lib/util/path', './reference', './html-io', 'lib/css-parse-stringify/css-parse', ], function (_, pathUtil, reference, htmlio, cssParse) { 'use strict'; function getRemoteFile(path, c) { require(['webida-lib/app'], function (ide) { //ide.getMount().readFile(path, function (error, content) { ide.getFSCache().readFile(path, function (error, content) { if (content === undefined) { content = null; } c(error, content); }); }); } var FileServer = { files: {}, getRemoteFileCallback: getRemoteFile, listenersForReferencesUpdate: [] }; /** * @contructor * @param {string} path the file path of this text */ function FileModel(path) { this.path = path; this.version = undefined; this.text = undefined; this.html = {}; this.css = {}; } FileModel.prototype.getHtmlDom = function () { if (this.html.version === this.version && this.html.dom !== undefined) { return this.html.dom; } var dom = htmlio.parse(this.text); this.html = {}; this.html.dom = dom; this.html.version = this.version; return dom; }; FileModel.prototype.getHtmlScripts = function () { if (this.html.version === this.version && this.html.scripts !== undefined) { return this.html.scripts; } var dom = this.getHtmlDom(); var scripts = []; if (dom) { scripts = dom.getElementsByTagName('script'); } this.html.scripts = scripts; return scripts; }; FileModel.prototype._getTextLineEnds = function () { if (this.textLineEndsVersion && this.textLineEndsVersion === this.version) { return this.textLineEnds; } var ends = []; var lastIndex = 0; var re = /\r?\n/g; while (re.test(this.text)) { ends.push(re.lastIndex); lastIndex = re.lastIndex; } ends.push(this.text.length - 1); this.textLineEnds = ends; this.textLineEndsVersion = this.version; return ends; }; FileModel.prototype.getPositionFromIndex = function (index) { var ends = this._getTextLineEnds(); for (var i = 0; i < ends.length; i++) { if (ends[i] > index) { return { line : i, ch : index - ends[i] }; } } return { line : ends.length - 1, ch : 0 }; }; FileModel.prototype.getIndexFromPosition = function (line, ch) { var ends = this._getTextLineEnds(); var beforeLine = line - 1; if (beforeLine >= 0 && beforeLine < ends.length) { return ends[beforeLine] + ch; } return -1; }; FileModel.prototype.isSubfile = function () { return this.parent; }; /** * @return {[FileModel]} sub files (script) of html **/ FileModel.prototype.getHtmlScriptSubfiles = function () { if (this.html.version === this.version && this.html.scriptSubfiles !== undefined) { return this.html.scriptSubfiles; } var scriptSubfiles = []; var scripts = this.getHtmlScripts(); var i = 1000; if (scripts) { _.each(scripts, function (script) { if (script.closingStart - script.openingEnd > 1) { var subpath = this.path + '*' + (++i) + '.js'; var startIndex = script.openingEnd + 1; var endIndex = script.closingStart - 1; var subfile = FileServer.setText(subpath, this.text.substring(startIndex, endIndex)); subfile.subfileStartPosition = this.getPositionFromIndex(startIndex); subfile.subfileEndPosition = this.getPositionFromIndex(endIndex); subfile.parent = this; scriptSubfiles.push(subfile); reference.addReference(this.path, subpath); } }, this); } var subpath, subfile; for (i = scriptSubfiles.length; true; i++) { subpath = this.path + '*' + (++i) + '.js'; subfile = FileServer.getLocalFile(subpath); if (subfile) { FileServer.setText(subpath, null); reference.removeReference(this.path, subpath); } else { break; } } this.html.scriptSubfiles = scriptSubfiles; return scriptSubfiles; }; FileModel.prototype.getHtmlScriptPaths = function () { if (this.html.version === this.version && this.html.scriptPaths !== undefined) { return this.html.scriptPaths; } var scripts = this.getHtmlScripts(); var scriptPaths = []; if (scripts) { var dirPath = pathUtil.getDirPath(this.path); _.each(scripts, function (script) { var src = script.getAttribute('src'); if (src) { var abspath = pathUtil.flatten(pathUtil.combine(dirPath, src)); scriptPaths.push(abspath); } }); } this.html.scriptPaths = scriptPaths; return scriptPaths; }; FileModel.prototype.getHtmlLinks = function () { if (this.html.version === this.version && this.html.links !== undefined) { return this.html.links; } var dom = this.getHtmlDom(); var links = []; if (dom) { links = dom.getElementsByTagName('link'); } this.html.links = links; return links; }; FileModel.prototype.getHtmlLinkPaths = function () { if (this.html.version === this.version && this.html.linkPaths !== undefined) { return this.html.linkPaths; } var links = this.getHtmlLinks(); var linkPaths = []; if (links) { var dirPath = pathUtil.getDirPath(this.path); _.each(links, function (link) { var href = link.getAttribute('href'); if (href) { var abspath = pathUtil.flatten(pathUtil.combine(dirPath, href)); linkPaths.push(abspath); } }); } this.html.linkPaths = linkPaths; return linkPaths; }; FileModel.prototype.getHtmlIds = function () { if (this.html.version === this.version && this.html.ids !== undefined) { return this.html.ids; } var dom = this.getHtmlDom(); var elems = dom.getElementsByTagName('*'); var ids = []; _.each(elems, function (elem) { if (elem.hasAttribute('id')) { ids.push(elem.getAttribute('id')); } }); this.html.ids = ids; return ids; }; FileModel.prototype.getHtmlClasses = function () { if (this.html.version === this.version && this.html.classes !== undefined) { return this.html.classes; } var dom = this.getHtmlDom(); var elems = dom.getElementsByTagName('*'); var classes = []; _.each(elems, function (elem) { if (elem.hasAttribute('class')) { classes = _.union(classes, elem.getAttribute('class').split(/\s+/)); } }); this.html.classes = classes; return classes; }; function getHtmlNodeOfIndex(nodes, index) { if (nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i].openingStart < index && (nodes[i].openingEnd >= index || nodes[i].closingEnd >= index)) { var childnode = getHtmlNodeOfIndex(nodes[i].children, index); if (childnode) { return childnode; } else { return nodes[i]; } } } } return null; } FileModel.prototype.getHtmlNodeOfIndex = function (index) { var dom = this.getHtmlDom(); return getHtmlNodeOfIndex(dom.children, index); }; FileModel.prototype.getHtmlNodeOfPos = function (line, ch) { var index = this.getIndexFromPosition(line, ch); return this.getHtmlNodeOfIndex(index); }; // CSS methods FileModel.prototype.getCssom = function () { if (this.css.version === this.version && this.css.cssom !== undefined) { return this.css.cssom; } var cssom = cssParse(this.text); this.css = {}; this.css.cssom = cssom; this.css.version = this.version; return cssom; }; FileModel.prototype.getCssIds = function () { if (this.css.version === this.version && this.css.ids !== undefined) { return this.css.ids; } var cssom = this.getCssom(); var ids = []; if (cssom && cssom.stylesheet && cssom.stylesheet.rules) { _.each(cssom.stylesheet.rules, function (rule) { _.each(rule.selectors, function (selector) { var regexp = /#(\w*)/g; var match; while ((match = regexp.exec(selector))) { if (match.length > 1) { ids.push(match[1]); } } }); }); } this.css.ids = ids; return ids; }; FileModel.prototype.getCssClasses = function () { if (this.css.version === this.version && this.css.classes !== undefined) { return this.css.classes; } var cssom = this.getCssom(); var classes = []; if (cssom && cssom.stylesheet && cssom.stylesheet.rules) { _.each(cssom.stylesheet.rules, function (rule) { _.each(rule.selectors, function (selector) { var regexp = /\.(\w*)/g; var match; while ((match = regexp.exec(selector))) { if (match.length > 1) { classes.push(match[1]); } } }); }); } this.css.classes = classes; return classes; }; /** @param {function} getRemoteFileCallback callback function for get remote file */ FileServer.init = function (getRemoteFileCallback) { FileServer.getRemoteFileCallback = getRemoteFileCallback; }; FileServer._newFile = function (path) { var file = new FileModel(path); FileServer.files[path] = file; return file; }; FileServer.setText = function (path, text) { var file = this.getLocalFile(path); if (!file) { file = this._newFile(path); } if (text === undefined) { console.error('## cc : text should not be undefined'); return file; } var newversion = new Date().getTime(); file.version = newversion; file.text = text; _updateReferences(file); return file; }; FileServer.setUpdated = function (path) { var file = this.getLocalFile(path); if (file) { var newversion = new Date().getTime(); file.version = newversion; } return file; }; var _updateReferences = function (file) { if (pathUtil.endsWith(file.path, '.html', true)) { var oldrefs = reference.getReferenceTos(file.path) || []; /*if (pathUtil.isJavaScript(file.path)) { } else if (pathUtil.isJson(file.path)) { // TODO impl } else */ if (pathUtil.isHtml(file.path)) { reference.removeReferences(file.path); _.each(file.getHtmlScriptSubfiles(), function (subfile) { reference.addReference(file.path, subfile.path); }); _.each(file.getHtmlScriptPaths(), function (scriptpath) { reference.addReference(file.path, scriptpath); }); _.each(file.getHtmlLinkPaths(), function (csspath) { reference.addReference(file.path, csspath); }); } var newrefs = reference.getReferenceTos(file.path) || []; _.each(FileServer.listenersForReferencesUpdate, function (listener) { listener(file, newrefs, oldrefs); }); } }; FileServer.addReferenceUpdateListener = function (c) { FileServer.listenersForReferencesUpdate.push(c); }; FileServer.removeReferenceUpdateListener = function (c) { FileServer.listenersForReferencesUpdate = _.without(FileServer.listenersForReferencesUpdate, c); }; /** @param {Fn(error,file)} c **/ FileServer.getFile = function (path, c) { var file = FileServer.files[path]; if (!file) { file = this._newFile(path); } if (file.text !== undefined) { c(undefined, file); } else if (file.waitings) { file.waitings.push(c); } else { file.waitings = []; file.waitings.push(c); var self = this; FileServer.getRemoteFileCallback(path, function (error, data) { if (error) { console.warn(path + ' : ' + error); } self.setText(path, data); _.each(file.waitings, function (c) { c(error, file); }); delete file.waitings; }); } }; FileServer.getLocalFile = function (path) { return FileServer.files[path]; }; FileServer.getUpdatedFile = function (path, version) { var file = this.getLocalFile(path); if (file) { if (version && file.version === version) { file = null; } } else { console.warn('## cc : unknown file requested [' + path + ']'); } return file; }; return FileServer; });
5hk/webida-client
apps/ide/src/plugins/codeeditor/content-assist/file-server.js
JavaScript
apache-2.0
15,220
angular.module('JobsTrackerSpring') .controller('PositionsEditCtrl', ['$scope', '$location', '$routeParams', 'PositionResource', function ($scope, $location, $routeParams, PositionResource) { 'use strict'; $scope.submitLabel = 'Update'; $scope.position = PositionResource.get({id: $routeParams.id}); $scope.submit = function () { if ($scope.positionForm.$valid) { PositionResource.update( {id: $scope.position.id}, $scope.position ).$promise.then( function (data) { $scope.$emit('successMessage', 'Saved ' + $scope.position.position); $location.path('/positions/' + $scope.position.id); }, function (err) { $scope.emit('errorMessage', 'Error while saving: ' + err); }); } }; }]);
witty-pigeon/jobstracker-spring
src/main/webapp/WEB-INF/js/controllers/positions-edit-ctrl.js
JavaScript
apache-2.0
1,066
from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT from testutils import TEARDOWN from library.user import User from library.project import Project from library.repository import Repository from library.repository import pull_harbor_image from library.repository import push_image_to_project from testutils import harbor_server from library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self): project = Project() self.project= project user = User() self.user= user repo = Repository() self.repo= repo @classmethod def tearDown(self): print "Case completed" @unittest.skipIf(TEARDOWN == False, "Test data won't be erased.") def test_ClearData(self): #1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.repo_name_in_project_a, **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.repo_name_in_project_b, **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.repo_name_in_project_c, **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.repo_name_pa, **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA); self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): """ Test case: Robot Account Test step and expected result: 1. Create user(UA); 2. Create private project(PA), private project(PB) and public project(PC) by user(UA); 3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA); 4. Create a new robot account(RA) with pull and push privilige in project(PA) by user(UA); 5. Check robot account info, it should has both pull and push priviliges; 6. Pull image(ImagePA) from project(PA) by robot account(RA), it must be successful; 7. Push image(ImageRA) to project(PA) by robot account(RA), it must be successful; 8. Push image(ImageRA) to project(PB) by robot account(RA), it must be not successful; 9. Pull image(ImagePB) from project(PB) by robot account(RA), it must be not successful; 10. Pull image from project(PC), it must be successful; 11. Push image(ImageRA) to project(PC) by robot account(RA), it must be not successful; 12. Update action property of robot account(RA); 13. Pull image(ImagePA) from project(PA) by robot account(RA), it must be not successful; 14. Push image(ImageRA) to project(PA) by robot account(RA), it must be not successful; 15. Push image(ImageRA) to project(PA) by robot account(RA), it must be not successful; Tear down: 1. Delete project(PA) (PB) (PC); 2. Delete user(UA). """ url = ADMIN_CLIENT["endpoint"] admin_name = ADMIN_CLIENT["username"] admin_password = ADMIN_CLIENT["password"] user_ra_password = "Aa123456" image_project_a = "tomcat" image_project_b = "hello-world" image_project_c = "mysql" image_robot_account = "mariadb" tag = "latest" print "#1. Create user(UA);" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = user_ra_password, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name, password = user_ra_password) print "#2. Create private project(PA), private project(PB) and public project(PC) by user(UA);" TestProjects.project_ra_id_a, project_ra_name_a = self.project.create_project(metadata = {"public": "false"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, project_ra_name_b = self.project.create_project(metadata = {"public": "false"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, project_ra_name_c = self.project.create_project(metadata = {"public": "true"}, **TestProjects.USER_RA_CLIENT) print "#3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA);" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print "#4. Create a new robot account(RA) with pull and push privilige in project(PA) by user(UA);" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, project_ra_name_a, **TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print "#5. Check robot account info, it should has both pull and push priviliges;" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print "#6. Pull image(ImagePA) from project(PA) by robot account(RA), it must be successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print "#7. Push image(ImageRA) to project(PA) by robot account(RA), it must be successful;" TestProjects.repo_name_pa, _ = push_image_to_project(project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print "#8. Push image(ImageRA) to project(PB) by robot account(RA), it must be not successful;" push_image_to_project(project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = "denied: requested access to the resource is denied") print "#9. Pull image(ImagePB) from project(PB) by robot account(RA), it must be not successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = r"pull access denied for " + harbor_server + "/" + TestProjects.repo_name_in_project_b) print "#10. Pull image from project(PC), it must be successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print "#11. Push image(ImageRA) to project(PC) by robot account(RA), it must be not successful;" push_image_to_project(project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = "denied: requested access to the resource is denied") print "#12. Update action property of robot account(RA);" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print "#13. Pull image(ImagePA) from project(PA) by robot account(RA), it must be not successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = "401 Client Error: Unauthorized") print "#14. Push image(ImageRA) to project(PA) by robot account(RA), it must be not successful;" push_image_to_project(project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message = "401 Client Error: Unauthorized") print "#15. Delete robot account(RA), it must be not successful;" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if __name__ == '__main__': unittest.main()
steven-zou/harbor
tests/apitests/python/test_robot_account.py
Python
apache-2.0
8,278
'use strict'; angular.module('dashboardApp') .directive('hasAnyAuthority', ['Principal', function (Principal) { return { restrict: 'A', link: function (scope, element, attrs) { var setVisible = function () { element.removeClass('hidden'); }, setHidden = function () { element.addClass('hidden'); }, defineVisibility = function (reset) { var result; if (reset) { setVisible(); } result = Principal.hasAnyAuthority(authorities); if (result) { setVisible(); } else { setHidden(); } }, authorities = attrs.hasAnyAuthority.replace(/\s+/g, '').split(','); if (authorities.length > 0) { defineVisibility(true); } } }; }]) .directive('hasAuthority', ['Principal', function (Principal) { return { restrict: 'A', link: function (scope, element, attrs) { var setVisible = function () { element.removeClass('hidden'); }, setHidden = function () { element.addClass('hidden'); }, defineVisibility = function (reset) { if (reset) { setVisible(); } Principal.hasAuthority(authority) .then(function (result) { if (result) { setVisible(); } else { setHidden(); } }); }, authority = attrs.hasAuthority.replace(/\s+/g, ''); if (authority.length > 0) { defineVisibility(true); } } }; }]);
SemanticCloud/SemanticCloud
Dashboard/src/main/webapp/scripts/components/auth/authority.directive.js
JavaScript
apache-2.0
2,342
import { test } from 'qunit'; import moduleForAcceptance from 'cargo/tests/helpers/module-for-acceptance'; import hasText from 'cargo/tests/helpers/has-text'; moduleForAcceptance('Acceptance | team page'); test('has team organization display', async function(assert) { server.loadFixtures(); await visit('/teams/github:org:thehydroimpulse'); hasText(assert, '.team-info h1', 'org'); hasText(assert, '.team-info h2', 'thehydroimpulseteam'); }); test('has link to github in team header', async function(assert) { server.loadFixtures(); await visit('/teams/github:org:thehydroimpulse'); const $githubLink = findWithAssert('.info a'); assert.equal($githubLink.attr('href').trim(), 'https://github.com/org_test'); }); test('github link has image in team header', async function(assert) { server.loadFixtures(); await visit('/teams/github:org:thehydroimpulse'); const $githubImg = findWithAssert('.info a img'); assert.equal($githubImg.attr('src').trim(), '/assets/GitHub-Mark-32px.png'); }); test('team organization details has github profile icon', async function(assert) { server.loadFixtures(); await visit('/teams/github:org:thehydroimpulse'); const $githubProfileImg = findWithAssert('.info img'); assert.equal($githubProfileImg.attr('src').trim(), 'https://avatars.githubusercontent.com/u/565790?v=3&s=170'); });
steveklabnik/crates.io
tests/acceptance/team-page-test.js
JavaScript
apache-2.0
1,391
package org.pikater.core.options.search; import org.pikater.core.agents.experiment.search.Agent_GridSearch; import org.pikater.core.ontology.subtrees.agentinfo.AgentInfo; import org.pikater.core.ontology.subtrees.batchdescription.Search; import org.pikater.core.ontology.subtrees.newoption.base.NewOption; import org.pikater.core.ontology.subtrees.newoption.restrictions.RangeRestriction; import org.pikater.core.ontology.subtrees.newoption.values.FloatValue; import org.pikater.core.ontology.subtrees.newoption.values.IntegerValue; import org.pikater.core.options.SlotsHelper; public class GridSearch_Box { public static AgentInfo get() { NewOption optionB = new NewOption("B", new IntegerValue(10), new RangeRestriction( new IntegerValue(1), new IntegerValue(100000)) ); optionB.setDescription("Maximum block size"); NewOption optionN = new NewOption("N", new IntegerValue(10), new RangeRestriction( new IntegerValue(1), new IntegerValue(100000)) ); optionN.setDescription("Default number of tries"); NewOption optionZ = new NewOption("Z", new FloatValue(10), new RangeRestriction( new FloatValue(0.0f), new FloatValue(1000.0f)) ); optionZ.setDescription("Zero for logarithmic steps"); AgentInfo agentInfo = new AgentInfo(); agentInfo.importAgentClass(Agent_GridSearch.class); agentInfo.importOntologyClass(Search.class); agentInfo.setName("Grid"); agentInfo.setDescription("GridSearch Description"); agentInfo.addOption(optionB); agentInfo.addOption(optionN); agentInfo.addOption(optionZ); //Slot Definition agentInfo.setOutputSlots(SlotsHelper.getOutputSlots_Search()); return agentInfo; } }
tomkren/pikater
src/org/pikater/core/options/search/GridSearch_Box.java
Java
apache-2.0
1,696
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.plaf.UIResource; import java.awt.Graphics; import java.awt.Color; import java.awt.Component; import java.awt.Polygon; import java.io.Serializable; /** * Factory object that can vend Icons appropriate for the basic L & F. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author David Kloba * @author Georges Saab */ public class BasicIconFactory implements Serializable { private static Icon frame_icon; private static Icon checkBoxIcon; private static Icon radioButtonIcon; private static Icon checkBoxMenuItemIcon; private static Icon radioButtonMenuItemIcon; private static Icon menuItemCheckIcon; private static Icon menuItemArrowIcon; private static Icon menuArrowIcon; public static Icon getMenuItemCheckIcon() { if (menuItemCheckIcon == null) { menuItemCheckIcon = new MenuItemCheckIcon(); } return menuItemCheckIcon; } public static Icon getMenuItemArrowIcon() { if (menuItemArrowIcon == null) { menuItemArrowIcon = new MenuItemArrowIcon(); } return menuItemArrowIcon; } public static Icon getMenuArrowIcon() { if (menuArrowIcon == null) { menuArrowIcon = new MenuArrowIcon(); } return menuArrowIcon; } public static Icon getCheckBoxIcon() { if (checkBoxIcon == null) { checkBoxIcon = new CheckBoxIcon(); } return checkBoxIcon; } public static Icon getRadioButtonIcon() { if (radioButtonIcon == null) { radioButtonIcon = new RadioButtonIcon(); } return radioButtonIcon; } public static Icon getCheckBoxMenuItemIcon() { if (checkBoxMenuItemIcon == null) { checkBoxMenuItemIcon = new CheckBoxMenuItemIcon(); } return checkBoxMenuItemIcon; } public static Icon getRadioButtonMenuItemIcon() { if (radioButtonMenuItemIcon == null) { radioButtonMenuItemIcon = new RadioButtonMenuItemIcon(); } return radioButtonMenuItemIcon; } public static Icon createEmptyFrameIcon() { if(frame_icon == null) frame_icon = new EmptyFrameIcon(); return frame_icon; } private static class EmptyFrameIcon implements Icon, Serializable { int height = 16; int width = 14; public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return width; } public int getIconHeight() { return height; } }; private static class CheckBoxIcon implements Icon, Serializable { final static int csize = 13; public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return csize; } public int getIconHeight() { return csize; } } private static class RadioButtonIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return 13; } public int getIconHeight() { return 13; } } // end class RadioButtonIcon private static class CheckBoxMenuItemIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); boolean isSelected = model.isSelected(); if (isSelected) { g.drawLine(x+7, y+1, x+7, y+3); g.drawLine(x+6, y+2, x+6, y+4); g.drawLine(x+5, y+3, x+5, y+5); g.drawLine(x+4, y+4, x+4, y+6); g.drawLine(x+3, y+5, x+3, y+7); g.drawLine(x+2, y+4, x+2, y+6); g.drawLine(x+1, y+3, x+1, y+5); } } public int getIconWidth() { return 9; } public int getIconHeight() { return 9; } } // End class CheckBoxMenuItemIcon private static class RadioButtonMenuItemIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); if (b.isSelected() == true) { g.fillOval(x+1, y+1, getIconWidth(), getIconHeight()); } } public int getIconWidth() { return 6; } public int getIconHeight() { return 6; } } // End class RadioButtonMenuItemIcon private static class MenuItemCheckIcon implements Icon, UIResource, Serializable{ public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return 9; } public int getIconHeight() { return 9; } } // End class MenuItemCheckIcon private static class MenuItemArrowIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return 4; } public int getIconHeight() { return 8; } } // End class MenuItemArrowIcon private static class MenuArrowIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { Polygon p = new Polygon(); p.addPoint(x, y); p.addPoint(x+getIconWidth(), y+getIconHeight()/2); p.addPoint(x, y+getIconHeight()); g.fillPolygon(p); } public int getIconWidth() { return 4; } public int getIconHeight() { return 8; } } // End class MenuArrowIcon }
haikuowuya/android_system_code
src/javax/swing/plaf/basic/BasicIconFactory.java
Java
apache-2.0
6,470
# Copyright 2013 OpenStack Foundation # # 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 uuid import mock from keystone import auth from keystone.auth.plugins import base from keystone import exception from keystone.tests import unit from keystone.tests.unit.ksfixtures import auth_plugins # for testing purposes only METHOD_NAME = 'simple_challenge_response' METHOD_OPTS = { METHOD_NAME: 'keystone.tests.unit.test_auth_plugin.SimpleChallengeResponse', } EXPECTED_RESPONSE = uuid.uuid4().hex DEMO_USER_ID = uuid.uuid4().hex class SimpleChallengeResponse(base.AuthMethodHandler): def authenticate(self, context, auth_payload, user_context): if 'response' in auth_payload: if auth_payload['response'] != EXPECTED_RESPONSE: raise exception.Unauthorized('Wrong answer') user_context['user_id'] = DEMO_USER_ID else: return {"challenge": "What's the name of your high school?"} class TestAuthPlugin(unit.SQLDriverOverrides, unit.TestCase): def setUp(self): super(TestAuthPlugin, self).setUp() self.api = auth.controllers.Auth() def test_unsupported_auth_method(self): method_name = uuid.uuid4().hex auth_data = {'methods': [method_name]} auth_data[method_name] = {'test': 'test'} auth_data = {'identity': auth_data} self.assertRaises(exception.AuthMethodNotSupported, auth.controllers.AuthInfo.create, auth_data) def test_addition_auth_steps(self): self.useFixture( auth_plugins.ConfigAuthPlugins(self.config_fixture, methods=[METHOD_NAME], **METHOD_OPTS)) self.useFixture(auth_plugins.LoadAuthPlugins(METHOD_NAME)) auth_data = {'methods': [METHOD_NAME]} auth_data[METHOD_NAME] = { 'test': 'test'} auth_data = {'identity': auth_data} auth_info = auth.controllers.AuthInfo.create(auth_data) auth_context = {'extras': {}, 'method_names': []} try: self.api.authenticate(self.make_request(), auth_info, auth_context) except exception.AdditionalAuthRequired as e: self.assertIn('methods', e.authentication) self.assertIn(METHOD_NAME, e.authentication['methods']) self.assertIn(METHOD_NAME, e.authentication) self.assertIn('challenge', e.authentication[METHOD_NAME]) # test correct response auth_data = {'methods': [METHOD_NAME]} auth_data[METHOD_NAME] = { 'response': EXPECTED_RESPONSE} auth_data = {'identity': auth_data} auth_info = auth.controllers.AuthInfo.create(auth_data) auth_context = {'extras': {}, 'method_names': []} self.api.authenticate(self.make_request(), auth_info, auth_context) self.assertEqual(DEMO_USER_ID, auth_context['user_id']) # test incorrect response auth_data = {'methods': [METHOD_NAME]} auth_data[METHOD_NAME] = { 'response': uuid.uuid4().hex} auth_data = {'identity': auth_data} auth_info = auth.controllers.AuthInfo.create(auth_data) auth_context = {'extras': {}, 'method_names': []} self.assertRaises(exception.Unauthorized, self.api.authenticate, self.make_request(), auth_info, auth_context) def test_duplicate_method(self): # Having the same method twice doesn't cause load_auth_methods to fail. self.useFixture( auth_plugins.ConfigAuthPlugins(self.config_fixture, ['external', 'external'])) auth.controllers.load_auth_methods() self.assertIn('external', auth.controllers.AUTH_METHODS) class TestAuthPluginDynamicOptions(TestAuthPlugin): def config_overrides(self): super(TestAuthPluginDynamicOptions, self).config_overrides() # Clear the override for the [auth] ``methods`` option so it is # possible to load the options from the config file. self.config_fixture.conf.clear_override('methods', group='auth') def config_files(self): config_files = super(TestAuthPluginDynamicOptions, self).config_files() config_files.append(unit.dirs.tests_conf('test_auth_plugin.conf')) return config_files class TestMapped(unit.TestCase): def setUp(self): super(TestMapped, self).setUp() self.api = auth.controllers.Auth() def config_files(self): config_files = super(TestMapped, self).config_files() config_files.append(unit.dirs.tests_conf('test_auth_plugin.conf')) return config_files def _test_mapped_invocation_with_method_name(self, method_name): with mock.patch.object(auth.plugins.mapped.Mapped, 'authenticate', return_value=None) as authenticate: request = self.make_request() auth_data = { 'identity': { 'methods': [method_name], method_name: {'protocol': method_name}, } } auth_info = auth.controllers.AuthInfo.create(auth_data) auth_context = {'extras': {}, 'method_names': [], 'user_id': uuid.uuid4().hex} self.api.authenticate(request, auth_info, auth_context) # make sure Mapped plugin got invoked with the correct payload ((context, auth_payload, auth_context), kwargs) = authenticate.call_args self.assertEqual(method_name, auth_payload['protocol']) def test_mapped_with_remote_user(self): method_name = 'saml2' auth_data = {'methods': [method_name]} # put the method name in the payload so its easier to correlate # method name with payload auth_data[method_name] = {'protocol': method_name} auth_data = {'identity': auth_data} auth_context = {'extras': {}, 'method_names': [], 'user_id': uuid.uuid4().hex} self.useFixture(auth_plugins.LoadAuthPlugins(method_name)) with mock.patch.object(auth.plugins.mapped.Mapped, 'authenticate', return_value=None) as authenticate: auth_info = auth.controllers.AuthInfo.create(auth_data) request = self.make_request(environ={'REMOTE_USER': 'foo@idp.com'}) self.api.authenticate(request, auth_info, auth_context) # make sure Mapped plugin got invoked with the correct payload ((context, auth_payload, auth_context), kwargs) = authenticate.call_args self.assertEqual(method_name, auth_payload['protocol']) def test_supporting_multiple_methods(self): method_names = ('saml2', 'openid', 'x509') self.useFixture(auth_plugins.LoadAuthPlugins(*method_names)) for method_name in method_names: self._test_mapped_invocation_with_method_name(method_name)
cernops/keystone
keystone/tests/unit/test_auth_plugin.py
Python
apache-2.0
7,772
/* * Copyright 2012 Open Source Robotics Foundation * * 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. * */ /* Desc: A laser sensor using OpenGL * Author: Mihai Emanuel Dolha * Date: 29 March 2012 */ #include <dirent.h> #include <sstream> #include "gazebo/sdf/sdf.hh" #include "gazebo/rendering/ogre_gazebo.h" #include "gazebo/common/Assert.hh" #include "gazebo/common/Events.hh" #include "gazebo/common/Console.hh" #include "gazebo/common/Exception.hh" #include "gazebo/common/Mesh.hh" #include "gazebo/common/MeshManager.hh" #include "gazebo/common/Timer.hh" #include "gazebo/math/Pose.hh" #include "gazebo/rendering/Visual.hh" #include "gazebo/rendering/Conversions.hh" #include "gazebo/rendering/Scene.hh" #include "gazebo/rendering/GpuLaser.hh" using namespace gazebo; using namespace rendering; int GpuLaser::texCount = 0; ////////////////////////////////////////////////// GpuLaser::GpuLaser(const std::string &_namePrefix, ScenePtr _scene, bool _autoRender) : Camera(_namePrefix, _scene, _autoRender) { this->laserBuffer = NULL; this->laserScan = NULL; this->matFirstPass = NULL; this->matSecondPass = NULL; this->w2nd = 0; this->h2nd = 0; this->visual.reset(); } ////////////////////////////////////////////////// GpuLaser::~GpuLaser() { delete [] this->laserBuffer; delete [] this->laserScan; } ////////////////////////////////////////////////// void GpuLaser::Load(sdf::ElementPtr &_sdf) { Camera::Load(_sdf); } ////////////////////////////////////////////////// void GpuLaser::Load() { Camera::Load(); } ////////////////////////////////////////////////// void GpuLaser::Init() { Camera::Init(); this->w2nd = this->GetImageWidth(); this->h2nd = this->GetImageHeight(); this->visual.reset(new Visual(this->GetName()+"second_pass_canvas", this->GetScene()->GetWorldVisual())); } ////////////////////////////////////////////////// void GpuLaser::Fini() { Camera::Fini(); } ////////////////////////////////////////////////// void GpuLaser::CreateLaserTexture(const std::string &_textureName) { this->camera->yaw(Ogre::Radian(this->horzHalfAngle)); this->camera->pitch(Ogre::Radian(this->vertHalfAngle)); this->CreateOrthoCam(); this->textureCount = this->cameraCount; if (this->textureCount == 2) { cameraYaws[0] = -this->hfov/2; cameraYaws[1] = +this->hfov; cameraYaws[2] = 0; cameraYaws[3] = -this->hfov/2; } else { cameraYaws[0] = -this->hfov; cameraYaws[1] = +this->hfov; cameraYaws[2] = +this->hfov; cameraYaws[3] = -this->hfov; } for (unsigned int i = 0; i < this->textureCount; ++i) { std::stringstream texName; texName << _textureName << "first_pass_" << i; this->firstPassTextures[i] = Ogre::TextureManager::getSingleton().createManual( texName.str(), "General", Ogre::TEX_TYPE_2D, this->GetImageWidth(), this->GetImageHeight(), 0, Ogre::PF_FLOAT32_RGB, Ogre::TU_RENDERTARGET).getPointer(); this->Set1stPassTarget( this->firstPassTextures[i]->getBuffer()->getRenderTarget(), i); this->firstPassTargets[i]->setAutoUpdated(false); } this->matFirstPass = (Ogre::Material*)( Ogre::MaterialManager::getSingleton().getByName("Gazebo/LaserScan1st").get()); this->matFirstPass->load(); this->secondPassTexture = Ogre::TextureManager::getSingleton().createManual( _textureName + "second_pass", "General", Ogre::TEX_TYPE_2D, this->GetImageWidth(), this->GetImageHeight(), 0, Ogre::PF_FLOAT32_RGB, Ogre::TU_RENDERTARGET).getPointer(); this->Set2ndPassTarget( this->secondPassTexture->getBuffer()->getRenderTarget()); this->secondPassTarget->setAutoUpdated(false); this->matSecondPass = (Ogre::Material*)( Ogre::MaterialManager::getSingleton().getByName("Gazebo/LaserScan2nd").get()); this->matSecondPass->load(); Ogre::TextureUnitState *texUnit; for (unsigned int i = 0; i < this->textureCount; ++i) { unsigned int texIndex = texCount++; Ogre::Technique *technique = this->matSecondPass->getTechnique(0); GZ_ASSERT(technique, "GpuLaser material script error: technique not found"); Ogre::Pass *pass = technique->getPass(0); GZ_ASSERT(pass, "GpuLaser material script error: pass not found"); texUnit = pass->createTextureUnitState( this->firstPassTextures[i]->getName(), texIndex); this->texIdx.push_back(texIndex); texUnit->setTextureFiltering(Ogre::TFO_NONE); texUnit->setTextureAddressingMode(Ogre::TextureUnitState::TAM_MIRROR); } this->CreateCanvas(); } ////////////////////////////////////////////////// void GpuLaser::PostRender() { // common::Timer postRenderT, blitT; // postRenderT.Start(); // double blitDur = 0.0; // double postRenderDur = 0.0; for (unsigned int i = 0; i < this->textureCount; ++i) { this->firstPassTargets[i]->swapBuffers(); } this->secondPassTarget->swapBuffers(); if (this->newData && this->captureData) { Ogre::HardwarePixelBufferSharedPtr pixelBuffer; unsigned int width = this->secondPassViewport->getActualWidth(); unsigned int height = this->secondPassViewport->getActualHeight(); // Get access to the buffer and make an image and write it to file pixelBuffer = this->secondPassTexture->getBuffer(); size_t size = Ogre::PixelUtil::getMemorySize( width, height, 1, Ogre::PF_FLOAT32_RGB); // Blit the depth buffer if needed if (!this->laserBuffer) this->laserBuffer = new float[size]; memset(this->laserBuffer, 255, size); Ogre::PixelBox dstBox(width, height, 1, Ogre::PF_FLOAT32_RGB, this->laserBuffer); // blitT.Start(); pixelBuffer->blitToMemory(dstBox); // blitDur = blitT.GetElapsed().Double(); if (!this->laserScan) this->laserScan = new float[this->w2nd * this->h2nd * 3]; memcpy(this->laserScan, this->laserBuffer, this->w2nd * this->h2nd * 3 * sizeof(this->laserScan[0])); this->newLaserFrame(this->laserScan, this->w2nd, this->h2nd, 3, "BLABLA"); } this->newData = false; // postRenderDur = postRenderT.GetElapsed().Double(); /* std::cerr << " Render: " << this->lastRenderDuration * 1000 << " BLIT: " << blitDur * 1000 << " postRender: " << postRenderDur * 1000 << " TOTAL: " << (this->lastRenderDuration + postRenderDur) * 1000 << " Total - BLIT: " << (this->lastRenderDuration + postRenderDur - blitDur) * 1000 << "\n"; */ } ///////////////////////////////////////////////// void GpuLaser::UpdateRenderTarget(Ogre::RenderTarget *_target, Ogre::Material *_material, Ogre::Camera *_cam, bool _updateTex) { Ogre::RenderSystem *renderSys; Ogre::Viewport *vp = NULL; Ogre::SceneManager *sceneMgr = this->scene->GetManager(); Ogre::Pass *pass; renderSys = this->scene->GetManager()->getDestinationRenderSystem(); // Get pointer to the material pass pass = _material->getBestTechnique()->getPass(0); // Render the depth texture // OgreSceneManager::_render function automatically sets farClip to 0. // Which normally equates to infinite distance. We don't want this. So // we have to set the distance every time. _cam->setFarClipDistance(this->GetFarClip()); Ogre::AutoParamDataSource autoParamDataSource; vp = _target->getViewport(0); // Need this line to render the ground plane. No idea why it's necessary. renderSys->_setViewport(vp); sceneMgr->_setPass(pass, true, false); autoParamDataSource.setCurrentPass(pass); autoParamDataSource.setCurrentViewport(vp); autoParamDataSource.setCurrentRenderTarget(_target); autoParamDataSource.setCurrentSceneManager(sceneMgr); autoParamDataSource.setCurrentCamera(_cam, true); renderSys->setLightingEnabled(false); renderSys->_setFog(Ogre::FOG_NONE); #if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6 pass->_updateAutoParamsNoLights(&autoParamDataSource); #else pass->_updateAutoParams(&autoParamDataSource, 1); #endif if (_updateTex) { pass->getFragmentProgramParameters()->setNamedConstant("tex1", this->texIdx[0]); if (this->texIdx.size() > 1) { pass->getFragmentProgramParameters()->setNamedConstant("tex2", this->texIdx[1]); if (this->texIdx.size() > 2) pass->getFragmentProgramParameters()->setNamedConstant("tex3", this->texIdx[2]); } } // NOTE: We MUST bind parameters AFTER updating the autos if (pass->hasVertexProgram()) { renderSys->bindGpuProgram( pass->getVertexProgram()->_getBindingDelegate()); #if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6 renderSys->bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, pass->getVertexProgramParameters()); #else renderSys->bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, pass->getVertexProgramParameters(), 1); #endif } if (pass->hasFragmentProgram()) { renderSys->bindGpuProgram( pass->getFragmentProgram()->_getBindingDelegate()); #if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6 renderSys->bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, pass->getFragmentProgramParameters()); #else renderSys->bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, pass->getFragmentProgramParameters(), 1); #endif } } ///////////////////////////////////////////////// void GpuLaser::notifyRenderSingleObject(Ogre::Renderable *_rend, const Ogre::Pass* /*pass*/, const Ogre::AutoParamDataSource* /*source*/, const Ogre::LightList* /*lights*/, bool /*supp*/) { Ogre::Vector4 retro = Ogre::Vector4(0, 0, 0, 0); try { retro = _rend->getCustomParameter(1); } catch(Ogre::ItemIdentityException& e) { _rend->setCustomParameter(1, Ogre::Vector4(0, 0, 0, 0)); } Ogre::Pass *pass = this->currentMat->getBestTechnique()->getPass(0); Ogre::RenderSystem *renderSys = this->scene->GetManager()->getDestinationRenderSystem(); Ogre::AutoParamDataSource autoParamDataSource; Ogre::Viewport *vp = this->currentTarget->getViewport(0); renderSys->_setViewport(vp); autoParamDataSource.setCurrentRenderable(_rend); autoParamDataSource.setCurrentPass(pass); autoParamDataSource.setCurrentViewport(vp); autoParamDataSource.setCurrentRenderTarget(this->currentTarget); autoParamDataSource.setCurrentSceneManager(this->scene->GetManager()); autoParamDataSource.setCurrentCamera(this->camera, true); pass->_updateAutoParams(&autoParamDataSource, Ogre::GPV_GLOBAL || Ogre::GPV_PER_OBJECT); pass->getFragmentProgramParameters()->setNamedConstant("retro", retro[0]); renderSys->bindGpuProgram( pass->getVertexProgram()->_getBindingDelegate()); renderSys->bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, pass->getVertexProgramParameters(), Ogre::GPV_GLOBAL || Ogre::GPV_PER_OBJECT); renderSys->bindGpuProgram( pass->getFragmentProgram()->_getBindingDelegate()); renderSys->bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, pass->getFragmentProgramParameters(), Ogre::GPV_GLOBAL || Ogre::GPV_PER_OBJECT); } ////////////////////////////////////////////////// void GpuLaser::RenderImpl() { common::Timer firstPassTimer, secondPassTimer; firstPassTimer.Start(); Ogre::SceneManager *sceneMgr = this->scene->GetManager(); sceneMgr->_suppressRenderStateChanges(true); sceneMgr->addRenderObjectListener(this); for (unsigned int i = 0; i < this->textureCount; ++i) { if (this->textureCount > 1) { // Cannot call Camera::RotateYaw because it rotates in world frame, // but we need rotation in camera local frame this->sceneNode->roll(Ogre::Radian(this->cameraYaws[i])); } this->currentMat = this->matFirstPass; this->currentTarget = this->firstPassTargets[i]; this->UpdateRenderTarget(this->firstPassTargets[i], this->matFirstPass, this->camera); this->firstPassTargets[i]->update(false); } if (this->textureCount > 1) this->sceneNode->roll(Ogre::Radian(this->cameraYaws[3])); sceneMgr->removeRenderObjectListener(this); double firstPassDur = firstPassTimer.GetElapsed().Double(); secondPassTimer.Start(); this->visual->SetVisible(true); this->UpdateRenderTarget(this->secondPassTarget, this->matSecondPass, this->orthoCam, true); this->secondPassTarget->update(false); this->visual->SetVisible(false); sceneMgr->_suppressRenderStateChanges(false); double secondPassDur = secondPassTimer.GetElapsed().Double(); this->lastRenderDuration = firstPassDur + secondPassDur; } ////////////////////////////////////////////////// const float* GpuLaser::GetLaserData() { return this->laserBuffer; } ///////////////////////////////////////////////// void GpuLaser::CreateOrthoCam() { this->orthoCam = this->scene->GetManager()->createCamera( this->GetName() + "_ortho_cam"); // Use X/Y as horizon, Z up this->orthoCam->pitch(Ogre::Degree(90)); // Don't yaw along variable axis, causes leaning this->orthoCam->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z); this->orthoCam->setDirection(1, 0, 0); this->pitchNodeOrtho = this->GetScene()->GetWorldVisual()->GetSceneNode()->createChildSceneNode( this->GetName()+"OrthoPitchNode"); this->pitchNodeOrtho->attachObject(this->orthoCam); this->orthoCam->setAutoAspectRatio(true); if (this->orthoCam) { this->orthoCam->setNearClipDistance(0.01); this->orthoCam->setFarClipDistance(0.02); this->orthoCam->setRenderingDistance(0.02); this->orthoCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC); } } ///////////////////////////////////////////////// Ogre::Matrix4 GpuLaser::BuildScaledOrthoMatrix(float _left, float _right, float _bottom, float _top, float _near, float _far) { float invw = 1 / (_right - _left); float invh = 1 / (_top - _bottom); float invd = 1 / (_far - _near); Ogre::Matrix4 proj = Ogre::Matrix4::ZERO; proj[0][0] = 2 * invw; proj[0][3] = -(_right + _left) * invw; proj[1][1] = 2 * invh; proj[1][3] = -(_top + _bottom) * invh; proj[2][2] = -2 * invd; proj[2][3] = -(_far + _near) * invd; proj[3][3] = 1; return proj; } ////////////////////////////////////////////////// void GpuLaser::Set1stPassTarget(Ogre::RenderTarget *_target, unsigned int _index) { this->firstPassTargets[_index] = _target; if (this->firstPassTargets[_index]) { // Setup the viewport to use the texture this->firstPassViewports[_index] = this->firstPassTargets[_index]->addViewport(this->camera); this->firstPassViewports[_index]->setClearEveryFrame(true); this->firstPassViewports[_index]->setOverlaysEnabled(false); this->firstPassViewports[_index]->setShadowsEnabled(false); this->firstPassViewports[_index]->setSkiesEnabled(false); this->firstPassViewports[_index]->setBackgroundColour( Ogre::ColourValue(this->far, 0.0, 1.0)); this->firstPassViewports[_index]->setVisibilityMask( GZ_VISIBILITY_ALL & ~GZ_VISIBILITY_GUI); } if (_index == 0) { this->camera->setAspectRatio(this->rayCountRatio); this->camera->setFOVy(Ogre::Radian(this->vfov)); } } ////////////////////////////////////////////////// void GpuLaser::Set2ndPassTarget(Ogre::RenderTarget *_target) { this->secondPassTarget = _target; if (this->secondPassTarget) { // Setup the viewport to use the texture this->secondPassViewport = this->secondPassTarget->addViewport(this->orthoCam); this->secondPassViewport->setClearEveryFrame(true); this->secondPassViewport->setOverlaysEnabled(false); this->secondPassViewport->setShadowsEnabled(false); this->secondPassViewport->setSkiesEnabled(false); this->secondPassViewport->setBackgroundColour( Ogre::ColourValue(0.0, 1.0, 0.0)); this->secondPassViewport->setVisibilityMask( GZ_VISIBILITY_ALL & ~GZ_VISIBILITY_GUI); } Ogre::Matrix4 p = this->BuildScaledOrthoMatrix( 0, static_cast<float>(this->GetImageWidth() / 10.0), 0, static_cast<float>(this->GetImageHeight() / 10.0), 0.01, 0.02); this->orthoCam->setCustomProjectionMatrix(true, p); } ///////////////////////////////////////////////// void GpuLaser::SetRangeCount(unsigned int _w, unsigned int _h) { this->w2nd = _w; this->h2nd = _h; } ///////////////////////////////////////////////// void GpuLaser::CreateMesh() { std::string meshName = this->GetName() + "_undistortion_mesh"; common::Mesh *mesh = new common::Mesh(); mesh->SetName(meshName); common::SubMesh *submesh = new common::SubMesh(); double dx, dy; submesh->SetPrimitiveType(common::SubMesh::POINTS); double viewHeight = this->GetImageHeight()/10.0; if (h2nd == 1) dy = 0; else dy = 0.1; dx = 0.1; double startX = dx; double startY = viewHeight; double phi = this->vfov / 2; double vAngMin = -phi; if (this->GetImageHeight() == 1) phi = 0; unsigned int ptsOnLine = 0; for (unsigned int j = 0; j < this->h2nd; ++j) { double gamma = 0; if (this->h2nd != 1) gamma = ((2 * phi / (this->h2nd - 1)) * j) + vAngMin; for (unsigned int i = 0; i < this->w2nd; ++i) { double thfov = this->textureCount * this->hfov; double theta = this->hfov / 2; double delta = ((thfov / (this->w2nd - 1)) * i); unsigned int texture = delta / (theta*2); if (texture > this->textureCount-1) { texture -= 1; delta -= (thfov / (this->w2nd - 1)); } delta = delta - (texture * (theta*2)); delta = delta - theta; startX -= dx; if (ptsOnLine == this->GetImageWidth()) { ptsOnLine = 0; startX = 0; startY -= dy; } ptsOnLine++; submesh->AddVertex(texture/1000.0, startX, startY); double u, v; if (this->isHorizontal) { u = -(cos(phi) * tan(delta))/(2 * tan(theta) * cos(gamma)) + 0.5; v = math::equal(phi, 0.0) ? -tan(gamma)/(2 * tan(phi)) + 0.5 : 0.5; } else { v = -(cos(theta) * tan(gamma))/(2 * tan(phi) * cos(delta)) + 0.5; u = math::equal(theta, 0.0) ? -tan(delta)/(2 * tan(theta)) + 0.5 : 0.5; } submesh->AddTexCoord(u, v); } } for (unsigned int j = 0; j < (this->h2nd ); ++j) for (unsigned int i = 0; i < (this->w2nd ); ++i) submesh->AddIndex(this->w2nd * j + i); mesh->AddSubMesh(submesh); this->undistMesh = mesh; common::MeshManager::Instance()->AddMesh(this->undistMesh); } ///////////////////////////////////////////////// void GpuLaser::CreateCanvas() { this->CreateMesh(); Ogre::Node *parent = this->visual->GetSceneNode()->getParent(); parent->removeChild(this->visual->GetSceneNode()); this->pitchNodeOrtho->addChild(this->visual->GetSceneNode()); this->visual->InsertMesh(this->undistMesh); std::ostringstream stream; std::string meshName = this->undistMesh->GetName(); stream << this->visual->GetSceneNode()->getName() << "_ENTITY_" << meshName; this->object = (Ogre::MovableObject*) (this->visual->GetSceneNode()->getCreator()->createEntity(stream.str(), meshName)); this->visual->AttachObject(this->object); this->object->setVisibilityFlags(GZ_VISIBILITY_ALL); math::Pose pose; pose.pos = math::Vector3(0.01, 0, 0); pose.rot.SetFromEuler(math::Vector3(0, 0, 0)); this->visual->SetPose(pose); this->visual->SetMaterial("Gazebo/Green"); this->visual->SetAmbient(common::Color(0, 1, 0, 1)); this->visual->SetVisible(true); this->scene->AddVisual(this->visual); } ////////////////////////////////////////////////// void GpuLaser::SetHorzHalfAngle(double _angle) { this->horzHalfAngle = _angle; } ////////////////////////////////////////////////// void GpuLaser::SetVertHalfAngle(double _angle) { this->vertHalfAngle = _angle; } ////////////////////////////////////////////////// double GpuLaser::GetHorzHalfAngle() const { return this->horzHalfAngle; } ////////////////////////////////////////////////// double GpuLaser::GetVertHalfAngle() const { return this->vertHalfAngle; } ////////////////////////////////////////////////// void GpuLaser::SetIsHorizontal(bool _horizontal) { this->isHorizontal = _horizontal; } ////////////////////////////////////////////////// bool GpuLaser::IsHorizontal() const { return this->isHorizontal; } ////////////////////////////////////////////////// double GpuLaser::GetHorzFOV() const { return this->hfov; } ////////////////////////////////////////////////// double GpuLaser::GetVertFOV() const { return this->vfov; } ////////////////////////////////////////////////// void GpuLaser::SetHorzFOV(double _hfov) { this->hfov = _hfov; } ////////////////////////////////////////////////// void GpuLaser::SetVertFOV(double _vfov) { this->vfov = _vfov; } ////////////////////////////////////////////////// double GpuLaser::GetCosHorzFOV() const { return this->chfov; } ////////////////////////////////////////////////// void GpuLaser::SetCosHorzFOV(double _chfov) { this->chfov = _chfov; } ////////////////////////////////////////////////// double GpuLaser::GetCosVertFOV() const { return this->cvfov; } ////////////////////////////////////////////////// void GpuLaser::SetCosVertFOV(double _cvfov) { this->cvfov = _cvfov; } ////////////////////////////////////////////////// double GpuLaser::GetNearClip() const { return this->near; } ////////////////////////////////////////////////// double GpuLaser::GetFarClip() const { return this->far; } ////////////////////////////////////////////////// void GpuLaser::SetNearClip(double _near) { this->near = _near; } ////////////////////////////////////////////////// void GpuLaser::SetFarClip(double _far) { this->far = _far; } ////////////////////////////////////////////////// double GpuLaser::GetCameraCount() const { return this->cameraCount; } ////////////////////////////////////////////////// void GpuLaser::SetCameraCount(double _cameraCount) { this->cameraCount = _cameraCount; } ////////////////////////////////////////////////// double GpuLaser::GetRayCountRatio() const { return this->rayCountRatio; } ////////////////////////////////////////////////// void GpuLaser::SetRayCountRatio(double _rayCountRatio) { this->rayCountRatio = _rayCountRatio; }
spyhak/mac_gazebo
gazebo/rendering/GpuLaser.cc
C++
apache-2.0
22,898
package org.apache.cassandra.io.sstable; /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.*; import org.junit.Test; import org.junit.runner.RunWith; import org.apache.cassandra.OrderedJUnit4ClassRunner; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.*; import org.apache.cassandra.db.columniterator.IdentityQueryFilter; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.LocalPartitioner; import org.apache.cassandra.dht.LocalToken; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.service.CacheService; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.io.util.MmappedSegmentedFile; import org.apache.cassandra.io.util.SegmentedFile; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.thrift.IndexExpression; import org.apache.cassandra.thrift.IndexOperator; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.CLibrary; import org.apache.cassandra.utils.Pair; @RunWith(OrderedJUnit4ClassRunner.class) public class SSTableReaderTest extends SchemaLoader { static Token t(int i) { return StorageService.getPartitioner().getToken(ByteBufferUtil.bytes(String.valueOf(i))); } @Test public void testGetPositionsForRanges() throws IOException, ExecutionException, InterruptedException { Table table = Table.open("Keyspace1"); ColumnFamilyStore store = table.getColumnFamilyStore("Standard2"); // insert data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 10; j++) { ByteBuffer key = ByteBufferUtil.bytes(String.valueOf(j)); RowMutation rm = new RowMutation("Keyspace1", key); rm.add(new QueryPath("Standard2", null, ByteBufferUtil.bytes("0")), ByteBufferUtil.EMPTY_BYTE_BUFFER, j); rm.apply(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store); List<Range<Token>> ranges = new ArrayList<Range<Token>>(); // 1 key ranges.add(new Range<Token>(t(0), t(1))); // 2 keys ranges.add(new Range<Token>(t(2), t(4))); // wrapping range from key to end ranges.add(new Range<Token>(t(6), StorageService.getPartitioner().getMinimumToken())); // empty range (should be ignored) ranges.add(new Range<Token>(t(9), t(91))); // confirm that positions increase continuously SSTableReader sstable = store.getSSTables().iterator().next(); long previous = -1; for (Pair<Long,Long> section : sstable.getPositionsForRanges(ranges)) { assert previous <= section.left : previous + " ! < " + section.left; assert section.left < section.right : section.left + " ! < " + section.right; previous = section.right; } } @Test public void testSpannedIndexPositions() throws IOException, ExecutionException, InterruptedException { MmappedSegmentedFile.MAX_SEGMENT_SIZE = 40; // each index entry is ~11 bytes, so this will generate lots of segments Table table = Table.open("Keyspace1"); ColumnFamilyStore store = table.getColumnFamilyStore("Standard1"); // insert a bunch of data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 100; j += 2) { ByteBuffer key = ByteBufferUtil.bytes(String.valueOf(j)); RowMutation rm = new RowMutation("Keyspace1", key); rm.add(new QueryPath("Standard1", null, ByteBufferUtil.bytes("0")), ByteBufferUtil.EMPTY_BYTE_BUFFER, j); rm.apply(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store); // check that all our keys are found correctly SSTableReader sstable = store.getSSTables().iterator().next(); for (int j = 0; j < 100; j += 2) { DecoratedKey dk = Util.dk(String.valueOf(j)); FileDataInput file = sstable.getFileDataInput(sstable.getPosition(dk, SSTableReader.Operator.EQ).position); DecoratedKey keyInDisk = SSTableReader.decodeKey(sstable.partitioner, sstable.descriptor, ByteBufferUtil.readWithShortLength(file)); assert keyInDisk.equals(dk) : String.format("%s != %s in %s", keyInDisk, dk, file.getPath()); } // check no false positives for (int j = 1; j < 110; j += 2) { DecoratedKey dk = Util.dk(String.valueOf(j)); assert sstable.getPosition(dk, SSTableReader.Operator.EQ) == null; } } @Test public void testPersistentStatistics() throws IOException, ExecutionException, InterruptedException { Table table = Table.open("Keyspace1"); ColumnFamilyStore store = table.getColumnFamilyStore("Standard1"); for (int j = 0; j < 100; j += 2) { ByteBuffer key = ByteBufferUtil.bytes(String.valueOf(j)); RowMutation rm = new RowMutation("Keyspace1", key); rm.add(new QueryPath("Standard1", null, ByteBufferUtil.bytes("0")), ByteBufferUtil.EMPTY_BYTE_BUFFER, j); rm.apply(); } store.forceBlockingFlush(); clearAndLoad(store); assert store.getMaxRowSize() != 0; } private void clearAndLoad(ColumnFamilyStore cfs) throws IOException { cfs.clearUnsafe(); cfs.loadNewSSTables(); } @Test public void testGetPositionsForRangesWithKeyCache() throws IOException, ExecutionException, InterruptedException { Table table = Table.open("Keyspace1"); ColumnFamilyStore store = table.getColumnFamilyStore("Standard2"); CacheService.instance.keyCache.setCapacity(100); // insert data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 10; j++) { ByteBuffer key = ByteBufferUtil.bytes(String.valueOf(j)); RowMutation rm = new RowMutation("Keyspace1", key); rm.add(new QueryPath("Standard2", null, ByteBufferUtil.bytes("0")), ByteBufferUtil.EMPTY_BYTE_BUFFER, j); rm.apply(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store); SSTableReader sstable = store.getSSTables().iterator().next(); long p2 = sstable.getPosition(k(2), SSTableReader.Operator.EQ).position; long p3 = sstable.getPosition(k(3), SSTableReader.Operator.EQ).position; long p6 = sstable.getPosition(k(6), SSTableReader.Operator.EQ).position; long p7 = sstable.getPosition(k(7), SSTableReader.Operator.EQ).position; Pair<Long, Long> p = sstable.getPositionsForRanges(makeRanges(t(2), t(6))).iterator().next(); // range are start exclusive so we should start at 3 assert p.left == p3; // to capture 6 we have to stop at the start of 7 assert p.right == p7; } @Test public void testPersistentStatisticsWithSecondaryIndex() throws IOException, ExecutionException, InterruptedException { // Create secondary index and flush to disk Table table = Table.open("Keyspace1"); ColumnFamilyStore store = table.getColumnFamilyStore("Indexed1"); ByteBuffer key = ByteBufferUtil.bytes(String.valueOf("k1")); RowMutation rm = new RowMutation("Keyspace1", key); rm.add(new QueryPath("Indexed1", null, ByteBufferUtil.bytes("birthdate")), ByteBufferUtil.bytes(1L), System.currentTimeMillis()); rm.apply(); store.forceBlockingFlush(); // check if opening and querying works assertIndexQueryWorks(store); } @Test public void testPersistentStatisticsFromOlderIndexedSSTable() throws IOException, ExecutionException, InterruptedException { // copy legacy indexed sstables String root = System.getProperty("legacy-sstable-root"); assert root != null; File rootDir = new File(root + File.separator + "hb" + File.separator + "Keyspace1"); assert rootDir.isDirectory(); File destDir = Directories.create("Keyspace1", "Indexed1").getDirectoryForNewSSTables(0); assert destDir != null; FileUtils.createDirectory(destDir); for (File srcFile : rootDir.listFiles()) { if (!srcFile.getName().startsWith("Indexed1")) continue; File destFile = new File(destDir, srcFile.getName()); CLibrary.createHardLink(srcFile, destFile); assert destFile.exists() : destFile.getAbsoluteFile(); } ColumnFamilyStore store = Table.open("Keyspace1").getColumnFamilyStore("Indexed1"); // check if opening and querying works assertIndexQueryWorks(store); } @Test public void testOpeningSSTable() throws Exception { String ks = "Keyspace1"; String cf = "Standard1"; // clear and create just one sstable for this test Table table = Table.open(ks); ColumnFamilyStore store = table.getColumnFamilyStore(cf); store.clearUnsafe(); store.disableAutoCompaction(); DecoratedKey firstKey = null, lastKey = null; long timestamp = System.currentTimeMillis(); for (int i = 0; i < DatabaseDescriptor.getIndexInterval(); i++) { DecoratedKey key = Util.dk(String.valueOf(i)); if (firstKey == null) firstKey = key; if (lastKey == null) lastKey = key; if (store.metadata.getKeyValidator().compare(lastKey.key, key.key) < 0) lastKey = key; RowMutation rm = new RowMutation(ks, key.key); rm.add(new QueryPath(cf, null, ByteBufferUtil.bytes("col")), ByteBufferUtil.EMPTY_BYTE_BUFFER, timestamp); rm.apply(); } store.forceBlockingFlush(); SSTableReader sstable = store.getSSTables().iterator().next(); Descriptor desc = sstable.descriptor; // test to see if sstable can be opened as expected SSTableReader target = SSTableReader.open(desc); byte[][] keySamples = target.getKeySamples(); assert keySamples.length == 1 && Arrays.equals(keySamples[0], firstKey.key.array()); assert target.first.equals(firstKey); assert target.last.equals(lastKey); } @Test public void testLoadingSummaryUsesCorrectPartitioner() throws Exception { Table table = Table.open("Keyspace1"); ColumnFamilyStore store = table.getColumnFamilyStore("Indexed1"); ByteBuffer key = ByteBufferUtil.bytes(String.valueOf("k1")); RowMutation rm = new RowMutation("Keyspace1", key); rm.add(new QueryPath("Indexed1", null, ByteBufferUtil.bytes("birthdate")), ByteBufferUtil.bytes(1L), System.currentTimeMillis()); rm.apply(); store.forceBlockingFlush(); ColumnFamilyStore indexCfs = store.indexManager.getIndexForColumn(ByteBufferUtil.bytes("birthdate")).getIndexCfs(); assert indexCfs.partitioner instanceof LocalPartitioner; SSTableReader sstable = indexCfs.getSSTables().iterator().next(); assert sstable.first.token instanceof LocalToken; SegmentedFile.Builder ibuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode()); SegmentedFile.Builder dbuilder = sstable.compression ? SegmentedFile.getCompressedBuilder() : SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode()); SSTableReader.saveSummary(sstable, ibuilder, dbuilder); SSTableReader reopened = SSTableReader.open(sstable.descriptor); assert reopened.first.token instanceof LocalToken; } private void assertIndexQueryWorks(ColumnFamilyStore indexedCFS) throws IOException { assert "Indexed1".equals(indexedCFS.getColumnFamilyName()); // make sure all sstables including 2ary indexes load from disk for (ColumnFamilyStore cfs : indexedCFS.concatWithIndexes()) clearAndLoad(cfs); // query using index to see if sstable for secondary index opens IndexExpression expr = new IndexExpression(ByteBufferUtil.bytes("birthdate"), IndexOperator.EQ, ByteBufferUtil.bytes(1L)); List<IndexExpression> clause = Arrays.asList(expr); IPartitioner p = StorageService.getPartitioner(); Range<RowPosition> range = Util.range("", ""); List<Row> rows = indexedCFS.search(clause, range, 100, new IdentityQueryFilter()); assert rows.size() == 1; } private List<Range<Token>> makeRanges(Token left, Token right) { return Arrays.<Range<Token>>asList(new Range[]{ new Range<Token>(left, right) }); } private DecoratedKey k(int i) { return new DecoratedKey(t(i), ByteBufferUtil.bytes(String.valueOf(i))); } }
dprguiuc/Cassandra-Wasef
test/unit/org/apache/cassandra/io/sstable/SSTableReaderTest.java
Java
apache-2.0
14,522
package com.android.appypapy.utils; import com.android.appypapy.messaging.AppySentenceMessage; import com.android.appypapy.messaging.FavoriteSentenceMessage; /** * Created by kln on 27/11/2016. */ public class EnumUtils { public static AppySentenceMessage.SentenceReadTypes ordinalToSentenceReadType(int ordinal) { AppySentenceMessage.SentenceReadTypes[] values = AppySentenceMessage.SentenceReadTypes.values(); for (AppySentenceMessage.SentenceReadTypes sentenceReadType : values) { if (sentenceReadType.ordinal() == ordinal) { return sentenceReadType; } } return AppySentenceMessage.SentenceReadTypes.MUTE; } public static FavoriteSentenceMessage.FavoriteSentenceCrud ordinalToFavoriteSentenceCrud(int ordinal) { FavoriteSentenceMessage.FavoriteSentenceCrud[] values = FavoriteSentenceMessage.FavoriteSentenceCrud.values(); for (FavoriteSentenceMessage.FavoriteSentenceCrud favoriteSentenceCrud : values) { if (favoriteSentenceCrud.ordinal() == ordinal) { return favoriteSentenceCrud; } } return FavoriteSentenceMessage.FavoriteSentenceCrud.UPDATED; } }
Wawamaniac/AppyPapy
ApplyUI/src/main/java/com/android/appypapy/utils/EnumUtils.java
Java
apache-2.0
1,136
namespace EntityFrameworkHelper.Model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Agent")] public partial class Agent { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Agent() { AgentCommissionRatio = new HashSet<AgentCommissionRatio>(); AgentInCity = new HashSet<AgentInCity>(); AgentInRestaurant = new HashSet<AgentInRestaurant>(); AgentInRestaurantRejectedRecord = new HashSet<AgentInRestaurantRejectedRecord>(); CityBusinessDistrict = new HashSet<CityBusinessDistrict>(); CityLandMark = new HashSet<CityLandMark>(); Restaurant = new HashSet<Restaurant>(); UserInAgent = new HashSet<UserInAgent>(); } public Guid AgentID { get; set; } [Required] [StringLength(60)] public string Tel { get; set; } [StringLength(500)] public string Remark { get; set; } [StringLength(50)] public string LinkMan { get; set; } public DateTime CreateTime { get; set; } public DateTime UpdateTime { get; set; } public bool FreezeFlag { get; set; } [Required] [StringLength(30)] public string CompanyName { get; set; } [StringLength(50)] public string CompanyAddress { get; set; } [StringLength(12)] public string PostCode { get; set; } [StringLength(20)] public string OpeningAnAccountProvince { get; set; } [StringLength(20)] public string OpeningAnAccountCity { get; set; } [StringLength(30)] public string OpeningAnAccount { get; set; } [StringLength(30)] public string BankAccount { get; set; } [StringLength(10)] public string Payee { get; set; } public bool DirectLoginRestaurantFlag { get; set; } public decimal Amount { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<AgentCommissionRatio> AgentCommissionRatio { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<AgentInCity> AgentInCity { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<AgentInRestaurant> AgentInRestaurant { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<AgentInRestaurantRejectedRecord> AgentInRestaurantRejectedRecord { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CityBusinessDistrict> CityBusinessDistrict { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CityLandMark> CityLandMark { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Restaurant> Restaurant { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<UserInAgent> UserInAgent { get; set; } } }
luoyefeiwu/Jerry
Jerry/架构/EntityFrameworkHelper/Model/Agent.cs
C#
apache-2.0
3,852
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.shard; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FilterDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.Lock; import org.apache.lucene.store.NoLockFactory; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.index.Index; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.store.Store; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; final class LocalShardSnapshot implements Closeable { private final IndexShard shard; private final Store store; private final Engine.IndexCommitRef indexCommit; private final AtomicBoolean closed = new AtomicBoolean(false); LocalShardSnapshot(IndexShard shard) { this.shard = shard; store = shard.store(); store.incRef(); boolean success = false; try { indexCommit = shard.acquireIndexCommit(true); success = true; } finally { if (success == false) { store.decRef(); } } } Index getIndex() { return shard.indexSettings().getIndex(); } Directory getSnapshotDirectory() { /* this directory will not be used for anything else but reading / copying files to another directory * we prevent all write operations on this directory with UOE - nobody should close it either. */ return new FilterDirectory(store.directory()) { @Override public String[] listAll() throws IOException { Collection<String> fileNames = indexCommit.getIndexCommit().getFileNames(); final String[] fileNameArray = fileNames.toArray(new String[fileNames.size()]); return fileNameArray; } @Override public void deleteFile(String name) throws IOException { throw new UnsupportedOperationException("this directory is read-only"); } @Override public void sync(Collection<String> names) throws IOException { throw new UnsupportedOperationException("this directory is read-only"); } @Override public void rename(String source, String dest) throws IOException { throw new UnsupportedOperationException("this directory is read-only"); } @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { throw new UnsupportedOperationException("this directory is read-only"); } @Override public IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException { throw new UnsupportedOperationException("this directory is read-only"); } @Override public Lock obtainLock(String name) throws IOException { /* we do explicitly a no-lock instance since we hold an index commit from a SnapshotDeletionPolicy so we * can we certain that nobody messes with the files on disk. We also hold a ref on the store which means * no external source will delete files either.*/ return NoLockFactory.INSTANCE.obtainLock(in, name); } @Override public void close() throws IOException { throw new UnsupportedOperationException("nobody should close this directory wrapper"); } }; } @Override public void close() throws IOException { if (closed.compareAndSet(false, true)) { try { indexCommit.close(); } finally { store.decRef(); } } } IndexMetaData getIndexMetaData() { return shard.indexSettings.getIndexMetaData(); } @Override public String toString() { return "local_shard_snapshot:[" + shard.shardId() + " indexCommit: " + indexCommit + "]"; } }
nezirus/elasticsearch
core/src/main/java/org/elasticsearch/index/shard/LocalShardSnapshot.java
Java
apache-2.0
5,012
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.sena.ejemplotemplates.model.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Enrique */ @Entity @Table(name = "lista_chequeo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "ListaChequeo.findAll", query = "SELECT l FROM ListaChequeo l") , @NamedQuery(name = "ListaChequeo.findByIdLista", query = "SELECT l FROM ListaChequeo l WHERE l.idLista = :idLista") , @NamedQuery(name = "ListaChequeo.findByEstado", query = "SELECT l FROM ListaChequeo l WHERE l.estado = :estado")}) public class ListaChequeo implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "id_lista") private String idLista; @Basic(optional = false) @NotNull @Column(name = "estado") private boolean estado; @JoinColumn(name = "programa_codigo_version", referencedColumnName = "codigo_version") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Programa programaCodigoVersion; @OneToMany(cascade = CascadeType.ALL, mappedBy = "listaChequeo1", fetch = FetchType.LAZY) private Collection<ItemChecker> itemCheckerCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "listaChequeo", fetch = FetchType.LAZY) private Collection<FichaHasLista> fichaHasListaCollection; public ListaChequeo() { } public ListaChequeo(String idLista) { this.idLista = idLista; } public ListaChequeo(String idLista, boolean estado) { this.idLista = idLista; this.estado = estado; } public String getIdLista() { return idLista; } public void setIdLista(String idLista) { this.idLista = idLista; } public boolean getEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public Programa getProgramaCodigoVersion() { return programaCodigoVersion; } public void setProgramaCodigoVersion(Programa programaCodigoVersion) { this.programaCodigoVersion = programaCodigoVersion; } @XmlTransient public Collection<ItemChecker> getItemCheckerCollection() { return itemCheckerCollection; } public void setItemCheckerCollection(Collection<ItemChecker> itemCheckerCollection) { this.itemCheckerCollection = itemCheckerCollection; } @XmlTransient public Collection<FichaHasLista> getFichaHasListaCollection() { return fichaHasListaCollection; } public void setFichaHasListaCollection(Collection<FichaHasLista> fichaHasListaCollection) { this.fichaHasListaCollection = fichaHasListaCollection; } @Override public int hashCode() { int hash = 0; hash += (idLista != null ? idLista.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ListaChequeo)) { return false; } ListaChequeo other = (ListaChequeo) object; if ((this.idLista == null && other.idLista != null) || (this.idLista != null && !this.idLista.equals(other.idLista))) { return false; } return true; } @Override public String toString() { return "co.edu.sena.ejemplotemplates.model.entities.ListaChequeo[ idLista=" + idLista + " ]"; } }
SENA-CEET/1349397-Trimestre-4
java/Servlets/ejemploTemplates/src/main/java/co/edu/sena/ejemplotemplates/model/entities/ListaChequeo.java
Java
apache-2.0
4,316
var u = Ti.Android != undefined ? 'dp' : 0; //A window object which will be associated with the stack of windows exports.AppWindow = function(args) { var instance = Ti.UI.createWindow(args); var view = Ti.UI.createView({ height : 40 + u, width : 320 + u, layout : 'horizontal', top : 0 + u, borderColor : '#133899', borderWidth : 1, borderRadius : 1 }); instance.add(view); var buttonshare = Ti.UI.createButton({ title : 'Share', left : 5 + u, right : 5 + u, bottom : 1 + u, height : 40 + u, width : 150 + u }); view.add(buttonshare); var buttoncheckin = Ti.UI.createButton({ title : 'Check-In', left : 5 + u, right : 5 + u, bottom : 1 + u, height : 40 + u, width : 150 + u }); view.add(buttoncheckin); buttoncheckin.addEventListener('click', function() { globals.tabs.currentTab.open(Ti.UI.createWindow({ title : 'New Window', backgroundColor : 'white' })); }); //news feed var scrollView = Titanium.UI.createScrollView({ contentWidth:'auto', contentHeight:'auto', top:50, showVerticalScrollIndicator:true, showHorizontalScrollIndicator:false }); instance.add(scrollView); var view = Ti.UI.createView({ backgroundColor:'#EFEFEF', borderRadius:10, width:300, height:1000, top:0 }); scrollView.add(view); var button = Titanium.UI.createButton({ title:'Scroll to Top', height:40, width:200, bottom:10 }); view.add(button); button.addEventListener('click', function() { scrollView.scrollTo(0,0); }); return instance; };
fziegler/plates
Resources/views/main/AppWindow.js
JavaScript
apache-2.0
1,546
/* * Copyright 2013-2015 the original author or authors. * * 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 example.springdata.jpa.java8; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import lombok.extern.slf4j.Slf4j; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Integration test to show the usage of Java 8 date time APIs with Spring Data JPA auditing. * * @author Oliver Gierke * @author Thomas Darimont */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration @Transactional @Slf4j public class Java8IntegrationTests { @EnableAsync @EntityScan(basePackageClasses = { Java8IntegrationTests.class, Jsr310JpaConverters.class }) @EnableJpaAuditing @SpringBootApplication static class Config {} @Autowired CustomerRepository repository; @Test public void providesFindOneWithOptional() { Customer carter = repository.save(new Customer("Carter", "Beauford")); assertThat(repository.findOne(carter.getId()).isPresent(), is(true)); assertThat(repository.findOne(carter.getId() + 1), is(Optional.<Customer> empty())); } @Test public void auditingSetsJdk8DateTimeTypes() { Customer customer = repository.save(new Customer("Dave", "Matthews")); assertThat(customer.getCreatedDate(), is(notNullValue())); assertThat(customer.getModifiedDate(), is(notNullValue())); } @Test public void invokesDefaultMethod() { Customer customer = repository.save(new Customer("Dave", "Matthews")); Optional<Customer> result = repository.findByLastname(customer); assertThat(result.isPresent(), is(true)); assertThat(result.get(), is(customer)); } /** * Streaming data from the store by using a repository method that returns a {@link Stream}. Note, that since the * resulting {@link Stream} contains state it needs to be closed explicitly after use! */ @Test public void useJava8StreamsWithCustomQuery() { Customer customer1 = repository.save(new Customer("Customer1", "Foo")); Customer customer2 = repository.save(new Customer("Customer2", "Bar")); try (Stream<Customer> stream = repository.streamAllCustomers()) { assertThat(stream.collect(Collectors.toList()), hasItems(customer1, customer2)); } } /** * Streaming data from the store by using a repository method that returns a {@link Stream} with a derived query. * Note, that since the resulting {@link Stream} contains state it needs to be closed explicitly after use! */ @Test public void useJava8StreamsWithDerivedQuery() { Customer customer1 = repository.save(new Customer("Customer1", "Foo")); Customer customer2 = repository.save(new Customer("Customer2", "Bar")); try (Stream<Customer> stream = repository.findAllByLastnameIsNotNull()) { assertThat(stream.collect(Collectors.toList()), hasItems(customer1, customer2)); } } /** * Here we demonstrate the usage of {@link CompletableFuture} as a result wrapper for asynchronous repository query * methods. Note, that we need to disable the surrounding transaction to be able to asynchronously read the written * data from from another thread within the same test method. */ @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void supportsCompletableFuturesAsReturnTypeWrapper() throws Exception { repository.save(new Customer("Customer1", "Foo")); repository.save(new Customer("Customer2", "Bar")); CompletableFuture<Void> future = repository.readAllBy().thenAccept(customers -> { assertThat(customers, hasSize(2)); customers.forEach(customer -> log.info(customer.toString())); log.info("Completed!"); }); while (!future.isDone()) { log.info("Waiting for the CompletableFuture to finish..."); TimeUnit.MILLISECONDS.sleep(500); } future.get(); log.info("Done!"); } }
thomasdarimont/whats-new-in-spring-data
03-java8/src/test/java/example/springdata/jpa/java8/Java8IntegrationTests.java
Java
apache-2.0
5,147
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.common.dataflow; import java.nio.ByteBuffer; import org.apache.asterix.common.api.INcApplicationContext; import org.apache.asterix.common.transactions.ILogMarkerCallback; import org.apache.asterix.common.transactions.PrimaryIndexLogMarkerCallback; import org.apache.hyracks.api.comm.VSizeFrame; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.api.exceptions.ErrorCode; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAccessor; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender; import org.apache.hyracks.dataflow.common.comm.util.FrameUtils; import org.apache.hyracks.dataflow.common.data.accessors.FrameTupleReference; import org.apache.hyracks.dataflow.common.utils.TaskUtil; import org.apache.hyracks.storage.am.common.api.IModificationOperationCallbackFactory; import org.apache.hyracks.storage.am.common.api.ITupleFilterFactory; import org.apache.hyracks.storage.am.common.dataflow.IIndexDataflowHelperFactory; import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback; import org.apache.hyracks.storage.am.common.ophelpers.IndexOperation; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexAccessor; import org.apache.hyracks.storage.am.lsm.common.dataflow.LSMIndexInsertUpdateDeleteOperatorNodePushable; import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndex; public class LSMInsertDeleteOperatorNodePushable extends LSMIndexInsertUpdateDeleteOperatorNodePushable { public static final String KEY_INDEX = "Index"; private final boolean isPrimary; // This class has both lsmIndex and index (in super class) pointing to the same object private AbstractLSMIndex lsmIndex; private int i = 0; /** * The following three variables are used to keep track of the information regarding flushing partial frame such as * 1. whether there was a partial frame flush for the current frame, * ==> captured in flushedPartialTuples variable * 2. the last flushed tuple index in the frame if there was a partial frame flush, * ==> captured in lastFlushedTupleIdx variable * 3. the current tuple index the frame, where this operator is working on the current tuple. * ==> captured in currentTupleIdx variable * These variables are reset for each frame, i.e., whenever nextFrame() is called, these variables are reset. */ private boolean flushedPartialTuples; private int currentTupleIdx; private int lastFlushedTupleIdx; public LSMInsertDeleteOperatorNodePushable(IHyracksTaskContext ctx, int partition, int[] fieldPermutation, RecordDescriptor inputRecDesc, IndexOperation op, boolean isPrimary, IIndexDataflowHelperFactory indexHelperFactory, IModificationOperationCallbackFactory modCallbackFactory, ITupleFilterFactory tupleFilterFactory) throws HyracksDataException { super(ctx, partition, indexHelperFactory, fieldPermutation, inputRecDesc, op, modCallbackFactory, tupleFilterFactory); this.isPrimary = isPrimary; } @Override public void open() throws HyracksDataException { accessor = new FrameTupleAccessor(inputRecDesc); writeBuffer = new VSizeFrame(ctx); appender = new FrameTupleAppender(writeBuffer); indexHelper.open(); lsmIndex = (AbstractLSMIndex) indexHelper.getIndexInstance(); try { if (isPrimary && ctx.getSharedObject() != null) { PrimaryIndexLogMarkerCallback callback = new PrimaryIndexLogMarkerCallback(lsmIndex); TaskUtil.put(ILogMarkerCallback.KEY_MARKER_CALLBACK, callback, ctx); } writer.open(); modCallback = modOpCallbackFactory.createModificationOperationCallback(indexHelper.getResource(), ctx, this); indexAccessor = lsmIndex.createAccessor(modCallback, NoOpOperationCallback.INSTANCE); if (tupleFilterFactory != null) { tupleFilter = tupleFilterFactory.createTupleFilter(ctx); frameTuple = new FrameTupleReference(); } INcApplicationContext runtimeCtx = (INcApplicationContext) ctx.getJobletContext().getServiceContext().getApplicationContext(); LSMIndexUtil.checkAndSetFirstLSN(lsmIndex, runtimeCtx.getTransactionSubsystem().getLogManager()); } catch (Throwable th) { throw new HyracksDataException(th); } } @Override public void nextFrame(ByteBuffer buffer) throws HyracksDataException { currentTupleIdx = 0; lastFlushedTupleIdx = 0; flushedPartialTuples = false; accessor.reset(buffer); ILSMIndexAccessor lsmAccessor = (ILSMIndexAccessor) indexAccessor; int tupleCount = accessor.getTupleCount(); try { for (; i < tupleCount; i++, currentTupleIdx++) { if (tupleFilter != null) { frameTuple.reset(accessor, i); if (!tupleFilter.accept(frameTuple)) { continue; } } tuple.reset(accessor, i); switch (op) { case INSERT: if (i == 0 && isPrimary) { lsmAccessor.insert(tuple); } else { lsmAccessor.forceInsert(tuple); } break; case DELETE: if (i == 0 && isPrimary) { lsmAccessor.delete(tuple); } else { lsmAccessor.forceDelete(tuple); } break; default: { throw HyracksDataException.create(ErrorCode.INVALID_OPERATOR_OPERATION, op.toString(), LSMInsertDeleteOperatorNodePushable.class.getSimpleName()); } } } } catch (HyracksDataException e) { if (e.getErrorCode() == ErrorCode.INVALID_OPERATOR_OPERATION) { throw e; } else { throw HyracksDataException.create(ErrorCode.ERROR_PROCESSING_TUPLE, e, i); } } catch (Exception e) { throw HyracksDataException.create(ErrorCode.ERROR_PROCESSING_TUPLE, e, i); } writeBuffer.ensureFrameSize(buffer.capacity()); if (flushedPartialTuples) { flushPartialFrame(); } else { FrameUtils.copyAndFlip(buffer, writeBuffer.getBuffer()); FrameUtils.flushFrame(writeBuffer.getBuffer(), writer); } i = 0; } /** * flushes tuples in a frame from lastFlushedTupleIdx(inclusive) to currentTupleIdx(exclusive) */ @Override public void flushPartialFrame() throws HyracksDataException { if (lastFlushedTupleIdx == currentTupleIdx) { //nothing to flush return; } for (int i = lastFlushedTupleIdx; i < currentTupleIdx; i++) { FrameUtils.appendToWriter(writer, appender, accessor, i); } appender.write(writer, true); lastFlushedTupleIdx = currentTupleIdx; flushedPartialTuples = true; } @Override public void close() throws HyracksDataException { if (lsmIndex != null) { try { indexHelper.close(); } finally { writer.close(); } } } @Override public void fail() throws HyracksDataException { if (lsmIndex != null) { writer.fail(); } } public boolean isPrimary() { return isPrimary; } }
heriram/incubator-asterixdb
asterixdb/asterix-common/src/main/java/org/apache/asterix/common/dataflow/LSMInsertDeleteOperatorNodePushable.java
Java
apache-2.0
8,803
<?php namespace Wechat; /** * Class POI * * @package Wechat * @description 门店 */ class POI { const API_ADD = "http://api.weixin.qq.com/cgi-bin/poi/addpoi"; const API_GET = 'http://api.weixin.qq.com/cgi-bin/poi/getpoi'; const API_GET_LIST = 'http://api.weixin.qq.com/cgi-bin/poi/getpoilist'; const API_UPDATE = 'http://api.weixin.qq.com/cgi-bin/poi/updatepoi'; const API_DELETE = 'http://api.weixin.qq.com/cgi-bin/poi/delpoi'; const API_GET_WX_CATEGORY = 'http://api.weixin.qq.com/cgi-bin/poi/getwxcategory'; private $_access_token; public function __construct($access_token) { $this->_access_token = $access_token; } /** * 添加门店 * * @param array $data * * @return array */ public function add(array $data) { return Util::request(self::API_ADD, $data, $this->_access_token); } /** * 查询门店 * * @param $poi_id |微信的门店ID,微信内门店唯一标示ID * * @return array */ public function get($poi_id) { $data = [ 'poi_id' => $poi_id, ]; return Util::request(self::API_GET, $data, $this->_access_token); } /** * 查询门店列表 * * @param $begin |开始位置,0 即为从第一条开始查询 * @param $limit |返回数据条数,最大允许50,默认为20 * * @return array */ public function getList($begin, $limit) { $data = [ 'begin' => $begin, 'limit' => $limit, ]; return Util::request(self::API_GET, $data, $this->_access_token); } /** * 修改门店服务信息 * * @param $poi_id |微信的门店ID,微信内门店唯一标示ID * @param array $data * * @return array */ public function update($poi_id, array $data) { $data = [ 'business' => [ 'base_info' => array_merge($data, ['poi_id' => $poi_id]), ], ]; return Util::request(self::API_UPDATE, $data, $this->_access_token); } /** * 删除门店 * * @param $poi_id |微信的门店ID,微信内门店唯一标示ID * * @return array */ public function delete($poi_id) { $data = [ 'poi_id' => $poi_id, ]; return Util::request(self::API_DELETE, $data, $this->_access_token); } /** * 门店类目表 * * @return array */ public function getWXCategory() { return Util::request(self::API_GET_WX_CATEGORY, [], $this->_access_token, \S\Http::METHOD_GET); } }
ifintech/phplib
Ext/Wechat/POI.php
PHP
apache-2.0
2,675
package io import ( "github.com/spf13/cobra" ) // A ReaderParams represent the user parameters for a Reader Node type ReaderParams struct { InputFile string ReaderModule string } func (r *ReaderParams) SetFlagsOptions(command *cobra.Command) { command.PersistentFlags().StringVar(&r.InputFile, "input-file", "-", "Input file name, use empty string for stdin.") command.PersistentFlags().StringVar(&r.ReaderModule, "reader-module", TEXT_READER_NAME, "Reader module used to read the input file.") } func (r *ReaderParams) Validate() (bool, error) { return true, nil } // A WriterParams represent the user parameters for a Writer Node type WriterParams struct { OutputFile string WriterModule string } func (w *WriterParams) SetFlagsOptions(command *cobra.Command) { command.PersistentFlags().StringVar(&w.OutputFile, "output-file", "-", "Output file name, use empty string for stdout.") command.PersistentFlags().StringVar(&w.WriterModule, "writer-module", TEXT_WRITER_NAME, "Writer module used to write the output file.") } func (w *WriterParams) Validate() (bool, error) { return true, nil }
clcert/mercury
platform/io/params.go
GO
apache-2.0
1,115
export * from "./nativescript-googlemaps";
marcbuils/nativescript-googlemaps
src/index.d.ts
TypeScript
apache-2.0
43
/* * Licensed to David Pilato (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package fr.pilato.spring.elasticsearch.xml; import org.w3c.dom.Element; /** * XML Parser helpers * Source from: http://www.java2s.com/Tutorial/Java/0440__XML/GetElementBooleanValue.htm */ class XMLParserUtil { static boolean getElementBooleanValue(Element element, String attribute) { return getElementBooleanValue(element, attribute, false); } static boolean getElementBooleanValue(Element element, String attribute, boolean defaultValue) { if (!element.hasAttribute(attribute)) return defaultValue; return Boolean.valueOf(getElementStringValue(element, attribute)); } static String getElementStringValue(Element element, String attribute) { return element.getAttribute(attribute); } }
dadoonet/spring-elasticsearch
src/main/java/fr/pilato/spring/elasticsearch/xml/XMLParserUtil.java
Java
apache-2.0
1,549
package com.example.mohit.tpomnnit.student.InterviewExperience; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.mohit.tpomnnit.R; import com.ramotion.foldingcell.FoldingCell; import java.util.HashSet; import java.util.List; /** * Simple example of ListAdapter for using with Folding Cell * Adapter holds indexes of unfolded elements for correct work with default reusable views behavior */ public class InterViewAdapter extends ArrayAdapter<Interview> { private HashSet<Integer> unfoldedIndexes = new HashSet<>(); private View.OnClickListener defaultRequestBtnClickListener; public InterViewAdapter(Context context, List<Interview> objects) { super(context, 0, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { // get item for selected view Interview item = getItem(position); // if cell is exists - reuse it, if not - create the new one from resource FoldingCell cell = (FoldingCell) convertView; ViewHolder viewHolder; if (cell == null) { viewHolder = new ViewHolder(); LayoutInflater vi = LayoutInflater.from(getContext()); cell = (FoldingCell) vi.inflate(R.layout.interview_cell, parent, false); // binding view parts to view holder viewHolder.company = (TextView) cell.findViewById(R.id.company); viewHolder.company1 = (TextView) cell.findViewById(R.id.company1); viewHolder.name = (TextView) cell.findViewById(R.id.name); viewHolder.profile = (TextView) cell.findViewById(R.id.profile); viewHolder.profil1 = (TextView) cell.findViewById(R.id.profile1); viewHolder.date = (TextView) cell.findViewById(R.id.date); viewHolder.year = (TextView) cell.findViewById(R.id.year); viewHolder.experience = (TextView) cell.findViewById(R.id.experience); viewHolder.nameini = (TextView) cell.findViewById(R.id.nameini); cell.setTag(viewHolder); } else { // for existing cell set valid valid state(without animation) if (unfoldedIndexes.contains(position)) { cell.unfold(true); } else { cell.fold(true); } viewHolder = (ViewHolder) cell.getTag(); } // bind data from selected element to view through view holder viewHolder.company.setText(item.getCompany()); viewHolder.company1.setText(item.getCompany()); viewHolder.name.setText(item.getName()); viewHolder.profile.setText(item.getProfile()); viewHolder.profil1.setText(item.getProfile()); viewHolder.date.setText(item.getDate()); viewHolder.year.setText(item.getYear()); viewHolder.experience.setText(item.getExperience()); if(!item.getCompany().equals("")) { Character t = item.getCompany().charAt(0); String str = t.toString(); viewHolder.nameini.setText(str); } // set custom btn handler for list item from that item /*if (item.getRequestBtnClickListener() != null) { viewHolder.contentRequestBtn.setOnClickListener(item.getRequestBtnClickListener()); } else {*/ // (optionally) add "default" handler if no handler found in item //viewHolder.contentRequestBtn.setOnClickListener(defaultRequestBtnClickListener); //} return cell; } // simple methods for register cell state changes public void registerToggle(int position) { if (unfoldedIndexes.contains(position)) registerFold(position); else registerUnfold(position); } public void registerFold(int position) { unfoldedIndexes.remove(position); } public void registerUnfold(int position) { unfoldedIndexes.add(position); } public View.OnClickListener getDefaultRequestBtnClickListener() { return defaultRequestBtnClickListener; } public void setDefaultRequestBtnClickListener(View.OnClickListener defaultRequestBtnClickListener) { this.defaultRequestBtnClickListener = defaultRequestBtnClickListener; } // View lookup cache private static class ViewHolder { TextView company,name,profile,year,date,experience,profil1,company1,nameini; } }
mkfeuhrer/TPO-MNNIT
app/src/main/java/com/example/mohit/tpomnnit/student/InterviewExperience/InterViewAdapter.java
Java
apache-2.0
4,554
import pandas as pd import numpy as np import os from datetime import datetime import numbers import requests import re from sklearn.linear_model import LinearRegression from statsmodels.api import OLS import cPickle from sklearn.cluster import DBSCAN import requests import json from matplotlib.path import Path from matplotlib import colors, cm class BaltimoreData(): def __init__(self, *args): self.DATA_PATH = os.path.join(os.path.dirname(__file__), "data/baltimore/") self.NEIGHBORHOOD_URL = "http://catalog.civicdashboards.com/dataset/e90d8498-44dd-4390-9bb9-5a53e85221eb/resource/6045d7d0-263e-416c-80fe-af1fb9f30650/download/3327ba9ba6f54cfdb9a5ef18244ae710temp.geojson" self.CSV_FILE = self.DATA_PATH + "Baltimore_Complaint_Data.csv" self.df = pd.DataFrame() self.meta = dict() self.args = args def filter_df(self, df): for arg in self.args: assert len(arg)==2, "Filter must define field and filter values" assert arg[0] in df.columns key = arg[0] val = self._set_list(arg[1]) df = df[df[key].isin(val)].reset_index(drop=True) return df def initData(self, **kwargs): if 'download_data' in kwargs: if kwargs['download_data']: self.pull_data() if 'download_metadata' in kwargs: if kwargs['download_metadata']: self.pull_metadata() if 'limit' in kwargs: if kwargs['limit']: limit = kwargs['limit'] else: limit = None if 'repull' in kwargs: if kwargs['repull']: self.read_data(limit=limit) self._apply_weapons_flag() self.read_meta() self.df['CITY'] = 'Baltimore' return self def _split_latlng(self): Lat_Lng = self.df['Location'].str.replace('\(|\)', '').str.split(', ') self.df['Latitude'] = Lat_Lng.map(lambda x: x[0]) self.df['Longitude'] = Lat_Lng.map(lambda x: x[1]) return self def read_data(self, limit=None): self.df = pd.read_csv(self.CSV_FILE, nrows=limit) self.df.rename(columns={'Location': 'Address', 'CrimeDate': 'Date', 'Inside/Outside': 'Location Description', 'Location 1': 'Location', 'District': 'DIST_NUM', 'Description': 'Primary Type', 'Weapon': 'Description'}, inplace=True) self.df = self.df[self.df.Location.notnull()].reset_index(drop=True) self._split_latlng() self.df['Location Description'] = self.df['Location Description'].apply(self.location_descriptions) return self @staticmethod def location_descriptions(x): if x=="I": return "Inside" elif x=="O": return "Outside" else: return x def read_meta(self): self.meta['census'] = self._read_census() self.meta['community'] = self._read_community() self.meta['ward'] = self._read_ward() self.meta['neighborhood'] = self._read_neighborhood() def _read_census(self): demo_census = self._read_demo_census() housing_census = self._read_demo_census() family_census = self._read_family_census() crime_census = self._read_crime_census() workforce_census = self._read_workforce_census() arts_census = self._read_arts_census() education_census = self._read_education_census() sustainability_census = self._read_sustainability_census() census = demo_census census = census.merge(housing_census, on='COMMUNITY AREA NAME') census = census.merge(family_census, on='COMMUNITY AREA NAME') census = census.merge(housing_census, on='COMMUNITY AREA NAME') census = census.merge(crime_census, on='COMMUNITY AREA NAME') census = census.merge(workforce_census, on='COMMUNITY AREA NAME') census = census.merge(arts_census, on='COMMUNITY AREA NAME') census = census.merge(education_census, on='COMMUNITY AREA NAME') census = census.merge(sustainability_census, on='COMMUNITY AREA NAME') return census [[c for c in census.columns if c[-2:] not in ('_x', '_y')]] def _read_community(self): community = pd.read_csv(self.DATA_PATH + 'BNIA_neighborhood.csv').rename(columns={'CSA2010': 'Community Area', 'the_geom': 'the_geom_community'}) community['COMMUNITY'] = community['Community Area'].str.upper() return community def _read_neighborhood(self): neighborhood = pd.read_csv(self.DATA_PATH + 'neighborhood.csv').rename(columns={'NBRDESC': 'NEIGHBORHOOD', 'LABEL': 'Neighborhood', 'the_geom': 'the_geom_neighborhood'}) return neighborhood def _read_ward(self): ward = pd.read_csv(self.DATA_PATH + 'ward.csv').rename(columns={'NAME_1': 'Ward'}) return ward def _read_demo_census(self): census_demo = pd.read_excel(self.DATA_PATH + 'BNIA_demo_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_demo def _read_housing_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_housing_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def _read_family_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_family_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def _read_crime_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_crime_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def _read_workforce_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_workforce_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def _read_arts_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_arts_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def _read_education_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_education_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def _read_sustainability_census(self): census_action = pd.read_excel(self.DATA_PATH + 'BNIA_sustainability_data.csv', header=1).rename(columns={'CSA2010': 'COMMUNITY AREA NAME'}) return census_action def pull_data(self): os.system("curl 'https://data.baltimorecity.gov/api/views/v9wg-c9g7/rows.csv?accessType=DOWNLOAD' -o '%sBaltimore_Complaint_Data.csv'" % self.DATA_PATH) return self def pull_metadata(self): os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Census-2010-2014.xlsx' -o '%sBNIA_demo_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Housing-2010-2014.xlsx' -o '%sBNIA_housing_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Children-and-Family-Health-2010-2014.xlsx' -o '%sBNIA_family_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS14-Crime-2010-2014.xlsx' -o '%sBNIA_crime_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Workforce-2010-2014.xlsx' -o '%sBNIA_workforce_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Arts-2011-2014.xlsx' -o '%sBNIA_arts_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Education-2010-2014.xlsx' -o '%sBNIA_education_data.csv'" % self.DATA_PATH) os.system("curl 'http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Sustainability-2010-2014.xlsx' -o '%sBNIA_sustainability_data.csv'" % self.DATA_PATH) os.system("curl 'https://data.baltimorecity.gov/api/views/5j2q-jsy4/rows.csv?accessType=DOWNLOAD' -o '%sward.csv'" % self.DATA_PATH) os.system("curl 'https://data.baltimorecity.gov/api/views/i49u-94ea/rows.csv?accessType=DOWNLOAD' -o '%sBNIA_neighborhood.csv'" % self.DATA_PATH) os.system("curl 'https://data.baltimorecity.gov/api/views/h3fx-54q3/rows.csv?accessType=DOWNLOAD' -o '%sneighborhood.csv'" % self.DATA_PATH) return self def get_community_name(self, df): df = self._get_area_name(df, 'community', 'Community Area') df['Community Area Number'] = df['Community Area'] return df def get_ward_name(self, df): df = self._get_area_name(df, 'ward', 'Ward') return df def get_district_name(self, df): df = self._get_area_name(df, 'district', 'DIST_NUM') return df def _get_area_name(self, df, meta_key, col): area_data = self.meta[meta_key].copy() area_data = self.geom_to_list(area_data) for c in area_data.columns: if re.match('the_geom.*', c): self.meta[meta_key]['path'] = area_data[c].map(lambda x: Path(x)) df[col] = df.index.map(lambda x: self._match_neighborhood(x, df, meta_key, col)) df[col] = df[col].map(lambda x: x[0] if len(x)>0 else np.nan) df = df.merge(self.meta[meta_key], how='left', on=col, suffixes=('_%s' % meta_key, '')) df.rename(columns={'the_geom': 'the_geom_%s' % meta_key}, inplace=True) return df[df[col].notnull()] def _match_neighborhood(self, x, df, meta_key, col): lat = float(df.ix[x]['Latitude']) lng = float(df.ix[x]['Longitude']) area_data = self.meta[meta_key].copy() if meta_key=='community': area_data['use_flag'] = area_data['COMMUNITY'].map(lambda x: 1 if not re.match('park-cemetery-etc.*|airport', x.lower()) else 0) area_data = area_data[area_data.use_flag==1] return [row[col] for i, row in area_data.iterrows() if row['path'].contains_point([lat, lng])] def read_census_extended(self, values=None): census_extended = self._read_census() census_extended['COMMUNITY AREA NAME'] = census_extended['COMMUNITY AREA NAME'].map(lambda x: x.upper()) return census_extended @classmethod def geom_to_list(cls, df): for c in df.columns: if re.match('the_geom.*', c): df[c] = df[c].map(lambda x: cls._parse_geom(x)) return df @staticmethod def _parse_geom(coords): if isinstance(coords, basestring): if str(coords) != '0': coord_sets = re.match("MULTIPOLYGON \(\(\((.*)\)\)\)", coords).group(1) coord_strings = [re.sub("\(|\)", "", c).split(" ") for c in coord_sets.split(", ")] coord_list = tuple([(float(c[1]), float(c[0])) for c in coord_strings]) else: coord_list = tuple([]) elif isinstance(coords, (list, tuple)): coord_list = tuple(coords) return coord_list def communities(self, df): community = dict() census = self._read_census() if set(['the_geom_community', 'Community Area']) < set(df.columns): for index1, row1 in df.iterrows(): for index2, row2 in df.iterrows(): community.setdefault(row1['Community Area'], {}) community.setdefault(row2['Community Area'], {}) if index1 > index2: geom1 = row1['the_geom_community'] geom2 = row2['the_geom_community'] boundary_intersect = set(geom1) & set(geom2) if len(boundary_intersect) > 0: community[row1['Community Area']].setdefault('adj_list', []).append(row2['Community Area']) community[row2['Community Area']].setdefault('adj_list', []).append(row1['Community Area']) community = pd.DataFrame(community).T numeric_cols = census.columns.difference(['COMMUNITY AREA NAME']) census[numeric_cols] = census[numeric_cols].fillna(0).applymap(lambda x: self._parse_pct(x)) census.index = census['COMMUNITY AREA NAME'] return pd.DataFrame(community).join(census).fillna(-1) @staticmethod def _parse_pct(x): if isinstance(x, basestring): x = re.match('.*(\d+).*', x) if x: if x[-1]=='%': return float(x.group(1))/100. else: return float(x.group(1)) else: return 0 else: return float(x) @staticmethod def _set_list(f): if not isinstance(f, list): if isinstance(f, (basestring, numbers.Integral)): return [f] else: return list(f) else: return f def _model(self, X, y): model = OLS(y, X) result = model.fit() print result.summary() return result def _apply_weapons_flag(self): indexes = [] self.df['WEAPON_FLAG'] = 0 for i, row in self.df.iterrows(): if row['Description']: if 'FIREARM' in str(row['Description']) or 'FIREARM' in str(row['Primary Type']): indexes.append(i) self.df.loc[indexes, 'WEAPON_FLAG'] = 1 return self class PivotData(BaltimoreData): def __init__(self, fields, dt_format, *args, **kwargs): BaltimoreData.__init__(self, *args) kwargs.setdefault('repull', False) self.fields = self._set_list(fields) self.dt_format = dt_format if 'csv' in kwargs: self.csv = self.DATA_PATH + kwargs['csv'] else: self.csv = "" if not kwargs['repull'] and os.path.isfile(self.csv): self.initData(**kwargs) self._data = pd.read_csv(self.csv) else: self.initData(**kwargs) self.pivot() def pivot(self): data = self.df.copy() data['Year'] = data['Date'].map(lambda x: datetime.strptime(x, '%m/%d/%Y').year) data = self.filter_df(data) if ('COMMUNITY' in self.fields) or ('Community Area' in self.fields) or ('Community Area Number' in self.fields): data = self.get_community_name(data) if 'Ward' in self.fields: data = self.get_ward_name(data) sep = '---' data['Period'] = data['Date'].map(lambda x: datetime.strptime(x, '%m/%d/%Y').strftime(self.dt_format)) counts = data.fillna(0).groupby(['Period']+self.fields, as_index=False).count() counts = counts.iloc[:, 0:len(self.fields)+2] counts.columns = ['Period']+self.fields+['count'] for i, f in enumerate(self.fields): field_counts = counts[f].map(lambda x: str(x)) if i==0: counts['fields'] = field_counts else: counts['fields'] += sep+field_counts pivot = counts.pivot('fields', 'Period', 'count') pivot_split = pivot.reset_index().fields.str.split(sep, expand=True) pivot_rename = pivot_split.rename(columns={int(k): v for k, v in enumerate(self.fields)}) self._data = pivot_rename.merge(pivot.reset_index(drop=True), left_index=True, right_index=True) if self.csv: self._data.to_csv(self.csv, index=False) return self def _date_cols(self): return set(self._data.columns) - set(self.fields) def norm_data(self, dt_filter, filter_zero=True): data = self.data.copy() data.loc[:, self.date_list] = data.loc[:, self.date_list].fillna(0) norm = np.linalg.norm(data.loc[:, self.date_list].fillna(0)) data.loc[:, 'fill_opacity'] = data[dt_filter]/norm data.loc[:, 'fill_opacity'] = data.loc[:, 'fill_opacity'] / max(data.loc[:, 'fill_opacity'] ) if filter_zero: data = data[data[dt_filter]>0].reset_index(drop=True) return data def color_data(self, dt_filter, filter_zero=True): h = cm.get_cmap('RdYlGn') data = self.norm_data(dt_filter, filter_zero) data.loc[:, 'fill_color'] = data.loc[:, 'fill_opacity'].map(lambda x: colors.rgb2hex(h(1.0-x)).upper()) return data @property def data(self): return self._data @property def date_list(self): dt_list = list(self._date_cols()) dt_list.sort() return dt_list if __name__=="__main__": # csv = 'community_pivot.csv' # fields = ['Community Area', 'COMMUNITY', 'the_geom_community'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'ward_marker.csv' # fields = ['Latitude', 'Longitude', 'Ward', 'Primary Type'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'community_marker.csv' # fields = ['Latitude', 'Longitude', 'Community Area', 'Primary Type'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'incident_marker.csv' # fields = ['Latitude', 'Longitude', 'Location', 'Primary Type'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'heatmap.csv' # fields = ['Latitude', 'Longitude'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'census_correlation.csv' # fields = ['Community Area', 'COMMUNITY', 'the_geom_community'] # p = PivotData(fields, '%Y', ['WEAPON_FLAG', 1], ['Year', [2010, 2011, 2012, 2013, 2014]], csv=csv, repull=True) # print '%s done' % csv # csv = 'trends.csv' # fields = ['CITY'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv csv = 'crime_location.csv' fields = ['Primary Type', 'Location Description'] p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) print '%s done' % csv # csv = 'district_marker.csv' # fields = ['Latitude', 'Longitude', 'DIST_NUM', 'Primary Type'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'city_marker.csv' # fields = ['Latitude', 'Longitude', 'CITY', 'Primary Type'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv # csv = 'crime_description.csv' # fields = ['Primary Type', 'Description'] # p = PivotData(fields, '%Y-%m', ['WEAPON_FLAG', 1], csv=csv, repull=True) # print '%s done' % csv
afenichel/ENGI4800-CAPSTONE
gunviolence/BaltimoreData.py
Python
apache-2.0
16,690
package com.zyl.melife.ui.view.main.impl; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.zyl.melife.logic.UIHelper; import com.zyl.melife.ui.presenter.main.impl.AppStartPresenterImpl; import com.zyl.melife.ui.view.main.ISplashView; public class AppStart extends AppCompatActivity implements ISplashView { AppStartPresenterImpl mAppStartPresenterImpl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 作用是将xml定义的一个布局找出来并且隐藏起来,并没有显示出来 final View view = new View(this);//R.layout.start_activity setContentView(view); mAppStartPresenterImpl = new AppStartPresenterImpl(); //直接跳转 redirectMain(); } @Override public void redirectMain(){ UIHelper.RedirectToActivity(MainActivity.class,AppStart.this); finish(); } @Override public void redirectIntroduce() { } @Override public Context getContext() { return null; } }
zhuyuliang/MeLife
app/src/main/java/com/zyl/melife/ui/view/main/impl/AppStart.java
Java
apache-2.0
1,163
package com.orionplatform.admin.cryptology.tasks; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import com.orionplatform.core.abstraction.Orion; import com.orionplatform.cryptology.encryption.EncryptionAlgorithm; import com.orionplatform.cryptology.encryption.rsa.RSAEncryptionService; public class DecryptDataTask extends Orion { public static synchronized String run(String data, String decryptionAlgorithm) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException, InvalidKeySpecException, IOException { EncryptionAlgorithm encryptionAlgorithmToUse = EncryptionAlgorithm.getEnumForValue(decryptionAlgorithm); if(encryptionAlgorithmToUse.is(EncryptionAlgorithm.RSA)) { return RSAEncryptionService.decryptFromRSA(data); } else if(encryptionAlgorithmToUse.is(EncryptionAlgorithm.RSANoPadding)) { return RSAEncryptionService.decryptFromRSAWithoutPadding(data); } else { return ""; } } }
orioncode/orionplatform
orion_admin/src/main/java/com/orionplatform/admin/cryptology/tasks/DecryptDataTask.java
Java
apache-2.0
1,370
function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.now(); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); var hours = Math.floor((t / (1000 * 60 * 60)) % 24); var days = Math.floor(t / (1000 * 60 * 60 * 24)); return { 'total': t, 'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds }; } function initializeClock(id, endtime) { var clock = document.getElementById(id); var daysSpan = clock.querySelector('.days'); var hoursSpan = clock.querySelector('.hours'); var minutesSpan = clock.querySelector('.minutes'); var secondsSpan = clock.querySelector('.seconds'); function updateClock() { var t = getTimeRemaining(endtime); daysSpan.innerHTML = t.days; hoursSpan.innerHTML = ('0' + t.hours).slice(-2); minutesSpan.innerHTML = ('0' + t.minutes).slice(-2); secondsSpan.innerHTML = ('0' + t.seconds).slice(-2); if (t.total <= 0) { clearInterval(timeinterval); } } updateClock(); var timeinterval = setInterval(updateClock, 1000); } var deadline = 'December 31 2016 23:59:59 GMT+07:00'; initializeClock('clockdiv', deadline);
maharanidanathallah/athallah-site-ma
newyear2017.js
JavaScript
apache-2.0
1,193
using ChinaUnion_BO; using ChinaUnion_DataAccess; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using Wechat.BO; using Wechat.Util; namespace Wechat { /// <summary> /// Summary description for PerformanceHandler /// </summary> public class PerformanceHandler : IHttpHandler { private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(PerformanceHandler)); /// <summary> /// 处理企业号的信息 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { logger.Info(context.Request.Url.AbsoluteUri); string sToken = "PerformanceHandler"; string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx4fe8b74e01fffcbb"; string sEncodingAESKey = "U7gOrkwP22ND4bIHSxU0WJqIestRcG2QroykyVKDUSG"; // string sToken = Properties.Settings.Default.Wechat_AgentFee_Token;//"AgentFee"; // string sCorpID = Properties.Settings.Default.Wechat_CorpId;// "wx31204de5a3ae758e"; // string sEncodingAESKey = Properties.Settings.Default.Wechat_AgentFee_EncodingAESKey;// "he8dYrZ5gLbDrDhfHVJkea1AfmHgRZQJq47kuKpQrSO"; System.Collections.Specialized.NameValueCollection queryStrings = context.Request.QueryString; Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); context.Request.ContentEncoding = Encoding.UTF8; string sReqMsgSig = queryStrings["msg_signature"]; string sReqTimeStamp = queryStrings["timestamp"]; string sReqNonce = queryStrings["nonce"]; // 获取Post请求的密文数据 StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.GetEncoding("UTF-8")); string sReqData = reader.ReadToEnd(); reader.Close(); string sMsg = ""; // 解析之后的明文 int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { logger.Info("ERR: Decrypt Fail, ret: " + ret); System.Console.WriteLine("ERR: Decrypt Fail, ret: " + ret); return; } // ret==0表示解密成功,sMsg表示解密之后的明文xml串 XmlDocument doc = new XmlDocument(); doc.LoadXml(sMsg); WechatMessage wechatMessage = new WechatMessage(doc.DocumentElement); // 需要发送的明文 String actionType = wechatMessage.EventKey; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<xml>"); sb.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", wechatMessage.FromUserName); sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wechatMessage.ToUserName); sb.AppendFormat("<CreateTime>{0}</CreateTime>", wechatMessage.CreateTime); // string sRespData = "<MsgId>1234567890123456</MsgId>"; logger.Info("EventKey: " + wechatMessage.EventKey); AgentWechatAccountDao agentWechatAccountDao = new AgentWechatAccountDao(); AgentWechatAccount agentWechatAccount = agentWechatAccountDao.Get(wechatMessage.FromUserName); if (agentWechatAccount != null && wechatMessage != null && !String.IsNullOrEmpty(wechatMessage.Event) && wechatMessage.Event.Equals("enter_agent")) { WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Performance; wechatQueryLog.subSystem = "业绩查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = "成员进入应用"; wechatQueryLog.wechatId = agentWechatAccount.contactId; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } } if (agentWechatAccount != null && !String.IsNullOrEmpty(agentWechatAccount.status) && !agentWechatAccount.status.Equals("Y")) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "对不起,你的账号已被停用,请联系联通工作人员!\n\n"); } else if (agentWechatAccount == null) { sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "用户不存在,请联系联通工作人员!\n\n"); } else { String agentNo = agentWechatAccount.branchNo; if (String.IsNullOrEmpty(agentNo)) { agentNo = agentWechatAccount.agentNo; } String agentType = agentWechatAccount.type; AgentMonthPerformanceDao agentMonthPerformanceDao = new ChinaUnion_DataAccess.AgentMonthPerformanceDao(); AgentDailyPerformanceDao agentDailyPerformanceDao = new ChinaUnion_DataAccess.AgentDailyPerformanceDao(); AgentStarDao agentStarDao = new AgentStarDao(); IList<AgentStar> agentStarList = null; AgentScoreDao agentScoreDao = new AgentScoreDao(); IList<AgentScore> agentScoreList = null; String dateTime = ""; DateTime dt = DateTime.Now.AddMonths(-3); //当前时间 DateTime startQuarter = dt.AddMonths(0 - (dt.Month - 1) % 3).AddDays(1 - dt.Day); //本季度初 if (startQuarter.Month >= 1 && startQuarter.Month <= 3) { dateTime = startQuarter.Year + "年第一季度"; } if (startQuarter.Month >= 4 && startQuarter.Month <= 6) { dateTime = startQuarter.Year + "年第二季度"; } if (startQuarter.Month >= 7 && startQuarter.Month <= 9) { dateTime = startQuarter.Year + "年第三季度"; } if (startQuarter.Month >= 10 && startQuarter.Month <= 12) { dateTime = startQuarter.Year + "年第四季度"; } logger.Info("agentNo: " + agentNo); logger.Info("agentType: " + agentType); switch (actionType) { case "curQuaterStar": case "HistoryQuaterStar": if (actionType.Equals("curQuaterStar")) { agentStarList = agentStarDao.GetLatestByKeyword(agentNo, dateTime); } if (actionType.Equals("HistoryQuaterStar")) { agentStarList = agentStarDao.GetListByKeyword(agentNo); } if (agentStarList != null && agentStarList.Count > 0) { logger.Info("Exist Record: " + agentStarList.Count); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); StringBuilder sbContent = new StringBuilder(); sbContent.AppendFormat("星级查询详情").Append("\n"); for (int i = 0; i < agentStarList.Count;i++ ) { AgentStar agentStar = agentStarList[i]; sbContent.AppendFormat("\n时间:{0}", agentStar.dateTime).Append("\n"); // sbContent.AppendFormat("代理商编号:{0}", agentStar.agentNo).Append("\n"); //sbContent.AppendFormat("代理商名称:{0}", agentStar.agentName).Append("\n"); if (!String.IsNullOrEmpty(agentStar.branchNo)) { sbContent.AppendFormat("渠道编码:{0}", agentStar.branchNo).Append("\n"); sbContent.AppendFormat("渠道名称:{0}", agentStar.branchName).Append("\n"); } sbContent.AppendFormat("星级:{0}", agentStar.star).Append("\n"); } sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", sbContent.ToString()); // sb.Append(sbContent.ToString()); // sb.Append(this.createNewsMessages(feeDate, wechatMessage.FromUserName, agentDailyPerformance)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "本期无星级或尚未发布,请耐心等候\n\n"); } WechatQueryLog wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Performance; wechatQueryLog.subSystem = "星级查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = dateTime; wechatQueryLog.wechatId = agentNo; WechatQueryLogDao wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } break; case "curScore": case "HistoryScore": String month = DateTime.Now.AddMonths(-1).ToString("yyyyMM"); if (actionType.Equals("curScore")) { agentScoreList = agentScoreDao.GetLatestByKeyword(agentNo, month); } if (actionType.Equals("HistoryScore")) { agentScoreList = agentScoreDao.GetListByKeyword(agentNo); } if (agentScoreList != null && agentScoreList.Count > 0) { logger.Info("Exist Record: " + agentScoreList.Count); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); StringBuilder sbContent = new StringBuilder(); sbContent.AppendFormat("积分查询详情").Append("\n"); for (int i = 0; i < agentScoreList.Count; i++) { AgentScore agentScore = agentScoreList[i]; sbContent.AppendFormat("\n时间:{0}", agentScore.dateTime).Append("\n"); if (!String.IsNullOrEmpty(agentScore.agentNo)) { sbContent.AppendFormat("代理商编号:{0}", agentScore.agentNo).Append("\n"); sbContent.AppendFormat("代理商名称:{0}", agentScore.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentScore.branchNo)) { sbContent.AppendFormat("渠道编码:{0}", agentScore.branchNo).Append("\n"); sbContent.AppendFormat("渠道名称:{0}", agentScore.branchName).Append("\n"); } sbContent.AppendFormat("渠道积分:{0}", agentScore.score).Append("\n"); sbContent.AppendFormat("本月得分:{0}", agentScore.standardScore).Append("\n"); } sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", sbContent.ToString()); // sb.Append(sbContent.ToString()); // sb.Append(this.createNewsMessages(feeDate, wechatMessage.FromUserName, agentDailyPerformance)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "本期无积分或尚未发布,请耐心等候\n\n"); } wechatQueryLog = new ChinaUnion_BO.WechatQueryLog(); wechatQueryLog.agentName = ""; wechatQueryLog.module = Util.MyConstant.module_Performance; wechatQueryLog.subSystem = "积分查询"; wechatQueryLog.queryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); wechatQueryLog.queryString = month; wechatQueryLog.wechatId = agentNo; wechatQueryLogDao = new WechatQueryLogDao(); try { wechatQueryLogDao.Add(wechatQueryLog); } catch { } break; case "YesterdayPerformance": String feeDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); AgentDailyPerformance agentDailyPerformance = new AgentDailyPerformance(); agentDailyPerformance = agentDailyPerformanceDao.GetSummary(agentNo, feeDate,agentType); if (agentDailyPerformance != null) { logger.Info("Exist Record: " + agentNo); sb.Append(this.createNewsMessages(feeDate, agentNo, agentDailyPerformance, agentType)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", DateTime.Now.AddDays(-1).ToString("yyyy年MM月dd日") + "无业绩或者业绩尚未发布\n\n"); } break; case "HistoryDayPerformance": String date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd"); IList<AgentDailyPerformance> agentDailyPerformanceList = agentDailyPerformanceDao.GetAllListDate(agentNo, agentType,date); if (agentDailyPerformanceList == null || agentDailyPerformanceList.Count == 0) { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "近期无业绩或者业绩尚未发布!\n\n"); } else { sb.Append(this.createNewsMessages(agentNo, agentDailyPerformanceList, agentType)); } break; case "LastMonthPerformance": // case "YesterdayPerformance": String feeMonth = DateTime.Now.AddMonths(-1).ToString("yyyy-MM"); AgentMonthPerformance agentMonthPerformance = new AgentMonthPerformance(); agentMonthPerformance = agentMonthPerformanceDao.GetSummary(agentNo, feeMonth, agentType); if (agentMonthPerformance != null) { logger.Info("Exist Record: " + agentMonthPerformance.agentName); sb.Append(this.createNewsMessages(feeMonth, agentNo, agentMonthPerformance, agentType)); } else { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", feeMonth.Substring(0,4)+"年"+feeMonth.Substring(5,2)+ "月" + "业绩尚未发布,请耐心等待!\n\n"); } break; case "HistoryMonthPerformance": IList<AgentMonthPerformance> agentMonthPerformanceList = agentMonthPerformanceDao.GetAllListMonth(agentNo,agentType); if (agentMonthPerformanceList == null || agentMonthPerformanceList.Count == 0) { logger.Info("is not Existed Record: "); sb.AppendFormat("<MsgType><![CDATA[text]]></MsgType>"); sb.AppendFormat("<Content><![CDATA[{0}]]></Content>", "近期业绩尚未发布,请耐心等待!\n\n"); } else { sb.Append(this.createNewsMessages(agentNo, agentMonthPerformanceList, agentType)); } break; } } // sb.AppendFormat("<AgentID>{0}</AgentID>", textMessage.AgentID); sb.AppendFormat("</xml>"); string sRespData = sb.ToString(); string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); logger.Info("sRespData=" + sRespData); logger.Info("ret=" + ret); if (ret != 0) { System.Console.WriteLine("ERR: EncryptMsg Fail, ret: " + ret); return; } context.Response.Write(sEncryptMsg); } public bool IsReusable { get { return false; } } private StringBuilder createNewsMessages(String agentNo, IList<AgentDailyPerformance> agentPerformanceList, String type) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>"); sb.AppendFormat("<ArticleCount>{0}</ArticleCount>", agentPerformanceList.Count > 10 ? 10 : agentPerformanceList.Count); sb.AppendFormat("<Articles>"); for (int month = 0; month < 10 && month < agentPerformanceList.Count; month++) { AgentDailyPerformance agentPerformance = agentPerformanceList[month]; sb.AppendFormat("<item>"); sb.Append("<Title>").AppendFormat("{0}日业绩", agentPerformance.date).Append("</Title>"); StringBuilder sbDesc = new StringBuilder(); if (month == 0) { AgentDailyPerformanceDao agentPerformanceDao = new ChinaUnion_DataAccess.AgentDailyPerformanceDao(); agentPerformance = agentPerformanceDao.GetSummary(agentNo, agentPerformance.date, type); if (!String.IsNullOrEmpty(agentPerformance.agentNo)) { sbDesc.AppendFormat("代理商编号:" + agentPerformance.agentNo + "\n代理商名称:" + agentPerformance.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentPerformance.branchNo)) { sbDesc.AppendFormat("渠道编号:" + agentPerformance.branchNo + "\n渠道名称:" + agentPerformance.branchName).Append("\n"); } sbDesc.AppendLine().AppendFormat("\n业绩汇总明细:\n"); int i = 1; for (int j = 1; j <= 100; j++) { FieldInfo feeNameField = agentPerformance.GetType().GetField("feeName" + j); FieldInfo feeField = agentPerformance.GetType().GetField("fee" + j); if (feeNameField != null && feeField != null) { String feeNameFieldValue = feeNameField.GetValue(agentPerformance) == null ? null : feeNameField.GetValue(agentPerformance).ToString(); String feeFieldValue = feeField.GetValue(agentPerformance) == null ? null : feeField.GetValue(agentPerformance).ToString(); if (!String.IsNullOrEmpty(feeFieldValue) && !String.IsNullOrWhiteSpace(feeFieldValue)) { if (feeNameFieldValue.Contains("后付费发展数") || feeNameFieldValue.Contains("预付费发展数") || feeNameFieldValue.Contains("总计")) { sbDesc.Append(" ").AppendFormat("{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } else { sbDesc.Append(" ").AppendFormat(" {0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } } } } } sbDesc.AppendFormat("\n查询时间:{0}\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.Append("<Description>").AppendFormat("<![CDATA[{0}]]>", sbDesc.ToString()).Append("</Description>"); sb.Append("<PicUrl>").AppendFormat("<![CDATA[]]>").Append("</PicUrl>"); String tempType = System.Web.HttpUtility.UrlEncode(type); String url1 = String.Format("http://{0}/Wechat/PerformanceDailySummaryQuery.aspx?agentNo={1}&feeDate={2}&type={3}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(agentPerformance.date, QueryStringEncryption.key), QueryStringEncryption.Encode(tempType, QueryStringEncryption.key)); logger.Info(url1); sb.Append("<Url>").AppendFormat("<![CDATA[{0}]]>", url1).Append("</Url>"); sb.AppendFormat("</item>"); } sb.AppendFormat("</Articles>"); return sb; } private StringBuilder createNewsMessages(String feeDate, String agentNo, AgentDailyPerformance agentDailyPerformance, String type) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>"); sb.AppendFormat("<ArticleCount>1</ArticleCount>"); sb.AppendFormat("<Articles>"); sb.AppendFormat("<item>"); sb.Append("<Title>").AppendFormat("{0}日业绩详情", feeDate).Append("</Title>"); StringBuilder sbDesc = new StringBuilder(); //sbDesc.AppendFormat("本月佣金告知单({0})", feeMonth); // sbDesc.AppendFormat("总共处理了:{0}次发票信息\n", agentMonthPerformanceList.Count); if (!String.IsNullOrEmpty(agentDailyPerformance.agentNo)) { sbDesc.AppendFormat("代理商编号:" + agentDailyPerformance.agentNo + "\n代理商名称:" + agentDailyPerformance.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentDailyPerformance.branchNo)) { sbDesc.AppendFormat("渠道编号:" + agentDailyPerformance.branchNo + "\n渠道名称:" + agentDailyPerformance.branchName).Append("\n"); } sbDesc.AppendLine().AppendFormat("\n业绩汇总明细:\n"); int i = 1; for (int j = 1; j <= 100; j++) { FieldInfo feeNameField = agentDailyPerformance.GetType().GetField("feeName" + j); FieldInfo feeField = agentDailyPerformance.GetType().GetField("fee" + j); if (feeNameField != null && feeField != null) { String feeNameFieldValue = feeNameField.GetValue(agentDailyPerformance) == null ? null : feeNameField.GetValue(agentDailyPerformance).ToString(); String feeFieldValue = feeField.GetValue(agentDailyPerformance) == null ? null : feeField.GetValue(agentDailyPerformance).ToString(); if (!String.IsNullOrEmpty(feeFieldValue) && !String.IsNullOrWhiteSpace(feeFieldValue)) { // sbDesc.Append(" ").Append(i++).AppendFormat(".{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); if (feeNameFieldValue.Contains("后付费发展数") || feeNameFieldValue.Contains("预付费发展数") || feeNameFieldValue.Contains("总计")) { sbDesc.Append(" ").AppendFormat("{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } else { sbDesc.Append(" ").AppendFormat(" {0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } } } } sbDesc.AppendFormat("\n查询时间:{0}\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.Append("<Description>").AppendFormat("<![CDATA[{0}]]>", sbDesc.ToString()).Append("</Description>"); String tempType = System.Web.HttpUtility.UrlEncode(type); String url1 = String.Format("http://{0}/Wechat/PerformanceDailySummaryQuery.aspx?agentNo={1}&feeDate={2}&type={3}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(feeDate, QueryStringEncryption.key), QueryStringEncryption.Encode(tempType, QueryStringEncryption.key)); logger.Info(url1); sb.Append("<Url>").AppendFormat("<![CDATA[{0}]]>", url1).Append("</Url>"); sb.AppendFormat("</item>"); sb.AppendFormat("</Articles>"); return sb; } private StringBuilder createNewsMessages(String agentNo, IList<AgentMonthPerformance> agentMonthPerformanceList, String type) { //type = UrlEncode StringBuilder sb = new StringBuilder(); sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>"); sb.AppendFormat("<ArticleCount>{0}</ArticleCount>", agentMonthPerformanceList.Count > 10 ? 10 : agentMonthPerformanceList.Count); sb.AppendFormat("<Articles>"); for (int month = 0; month < 10 && month < agentMonthPerformanceList.Count; month++) { AgentMonthPerformance agentMonthPerformance = agentMonthPerformanceList[month]; sb.AppendFormat("<item>"); sb.Append("<Title>").AppendFormat("{0}月业绩", agentMonthPerformance.month).Append("</Title>"); StringBuilder sbDesc = new StringBuilder(); if (month == 0) { AgentMonthPerformanceDao agentMonthPerformanceDao = new ChinaUnion_DataAccess.AgentMonthPerformanceDao(); agentMonthPerformance = agentMonthPerformanceDao.GetSummary(agentNo, agentMonthPerformance.month,type); if (!String.IsNullOrEmpty(agentMonthPerformance.agentNo)) { sbDesc.AppendFormat("代理商编号:" + agentMonthPerformance.agentNo + "\n代理商名称:" + agentMonthPerformance.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentMonthPerformance.branchNo)) { sbDesc.AppendFormat("渠道编号:" + agentMonthPerformance.branchNo + "\n渠道名称:" + agentMonthPerformance.branchName).Append("\n"); } sbDesc.AppendLine().AppendFormat("\n业绩汇总明细:\n"); //int i = 1; for (int j = 1; j <= 100; j++) { FieldInfo feeNameField = agentMonthPerformance.GetType().GetField("feeName" + j); FieldInfo feeField = agentMonthPerformance.GetType().GetField("fee" + j); if (feeNameField != null && feeField != null) { String feeNameFieldValue = feeNameField.GetValue(agentMonthPerformance) == null ? null : feeNameField.GetValue(agentMonthPerformance).ToString(); String feeFieldValue = feeField.GetValue(agentMonthPerformance) == null ? null : feeField.GetValue(agentMonthPerformance).ToString(); if (!String.IsNullOrEmpty(feeFieldValue) && !String.IsNullOrWhiteSpace(feeFieldValue)) { // sbDesc.Append(" ").Append(i++).AppendFormat(".{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); if (feeNameFieldValue.Contains("后付费发展数") || feeNameFieldValue.Contains("预付费发展数") || feeNameFieldValue.Contains("总计")) { sbDesc.Append(" ").AppendFormat("{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } else { sbDesc.Append(" ").AppendFormat(" {0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } } } } sbDesc.AppendFormat("\n查询时间:{0}\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.Append("<Description>").AppendFormat("<![CDATA[{0}]]>", sbDesc.ToString()).Append("</Description>"); } sb.Append("<PicUrl>").AppendFormat("<![CDATA[]]>").Append("</PicUrl>"); String tempType = System.Web.HttpUtility.UrlEncode(type); String url1 = String.Format("http://{0}/Wechat/PerformanceMonthSummaryQuery.aspx?agentNo={1}&feeMonth={2}&type={3}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(agentMonthPerformance.month, QueryStringEncryption.key), QueryStringEncryption.Encode(tempType, QueryStringEncryption.key)); logger.Info(url1); sb.Append("<Url>").AppendFormat("<![CDATA[{0}]]>", url1).Append("</Url>"); sb.AppendFormat("</item>"); } sb.AppendFormat("</Articles>"); return sb; } private StringBuilder createNewsMessages(String feeMonth, String agentNo, AgentMonthPerformance agentMonthPerformance, String type) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>"); sb.AppendFormat("<ArticleCount>1</ArticleCount>"); sb.AppendFormat("<Articles>"); sb.AppendFormat("<item>"); sb.Append("<Title>").AppendFormat("{0}月业绩详情", feeMonth).Append("</Title>"); StringBuilder sbDesc = new StringBuilder(); //sbDesc.AppendFormat("本月佣金告知单({0})", feeMonth); // sbDesc.AppendFormat("总共处理了:{0}次发票信息\n", agentMonthPerformanceList.Count); if (!String.IsNullOrEmpty(agentMonthPerformance.agentNo)) { sbDesc.AppendFormat("代理商编号:" + agentMonthPerformance.agentNo + "\n代理商名称:" + agentMonthPerformance.agentName).Append("\n"); } if (!String.IsNullOrEmpty(agentMonthPerformance.branchNo)) { sbDesc.AppendFormat("渠道编号:" + agentMonthPerformance.branchNo + "\n渠道名称:" + agentMonthPerformance.branchName).Append("\n"); } sbDesc.AppendLine().AppendFormat("\n业绩汇总明细:\n"); for (int j = 1; j <= 100; j++) { FieldInfo feeNameField = agentMonthPerformance.GetType().GetField("feeName" + j); FieldInfo feeField = agentMonthPerformance.GetType().GetField("fee" + j); if (feeNameField != null && feeField != null) { String feeNameFieldValue = feeNameField.GetValue(agentMonthPerformance) == null ? null : feeNameField.GetValue(agentMonthPerformance).ToString(); String feeFieldValue = feeField.GetValue(agentMonthPerformance) == null ? null : feeField.GetValue(agentMonthPerformance).ToString(); if (!String.IsNullOrEmpty(feeFieldValue) && !String.IsNullOrWhiteSpace(feeFieldValue)) { // sbDesc.Append(" ").Append(i++).AppendFormat(".{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); if (feeNameFieldValue.Contains("后付费发展数") || feeNameFieldValue.Contains("预付费发展数") || feeNameFieldValue.Contains("总计")) { sbDesc.Append(" ").AppendFormat("{0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } else { sbDesc.Append(" ").AppendFormat(" {0}", feeNameFieldValue).Append(" ").AppendFormat("{0}\n", feeFieldValue); } } } } sbDesc.AppendFormat("\n查询时间:{0}\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.Append("<Description>").AppendFormat("<![CDATA[{0}]]>", sbDesc.ToString()).Append("</Description>"); String tempType = System.Web.HttpUtility.UrlEncode(type); String url1 = String.Format("http://{0}/Wechat/PerformanceMonthSummaryQuery.aspx?agentNo={1}&feeMonth={2}&type={3}", Properties.Settings.Default.Host, QueryStringEncryption.Encode(agentNo, QueryStringEncryption.key), QueryStringEncryption.Encode(feeMonth, QueryStringEncryption.key), QueryStringEncryption.Encode(tempType, QueryStringEncryption.key)); logger.Info(url1); sb.Append("<Url>").AppendFormat("<![CDATA[{0}]]>", url1).Append("</Url>"); sb.AppendFormat("</item>"); sb.AppendFormat("</Articles>"); return sb; } } }
ZhouAnPing/Mail
Mail/Wechat/PerformanceHandler.ashx.cs
C#
apache-2.0
36,843
/*jshint strict: false, maxlen: 500 */ /*global require, assertEqual */ //////////////////////////////////////////////////////////////////////////////// /// @brief tests for query language, functions /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var internal = require("internal"); var errors = internal.errors; var jsunity = require("jsunity"); var helper = require("org/arangodb/aql-helper"); var getQueryResults = helper.getQueryResults; var assertQueryError = helper.assertQueryError; var assertQueryWarningAndNull = helper.assertQueryWarningAndNull; //////////////////////////////////////////////////////////////////////////////// /// @brief test suite //////////////////////////////////////////////////////////////////////////////// function ahuacatlDateFunctionsTestSuite () { return { //////////////////////////////////////////////////////////////////////////////// /// @brief test date_now function //////////////////////////////////////////////////////////////////////////////// testDateNowInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_NOW(1)"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_NOW(1, 1)"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_now function //////////////////////////////////////////////////////////////////////////////// testDateNow : function () { var actual = getQueryResults("RETURN IS_NUMBER(DATE_NOW())")[0]; assertEqual(true, actual); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_dayofweek function //////////////////////////////////////////////////////////////////////////////// testDateDayOfWeekInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAYOFWEEK()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAYOFWEEK(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_dayofweek function //////////////////////////////////////////////////////////////////////////////// testDateDayOfWeek : function () { var values = [ [ "2000-04-29", 6 ], [ "2000-04-29Z", 6 ], [ "2012-02-12 13:24:12", 0 ], [ "2012-02-12 13:24:12Z", 0 ], [ "2012-02-12 23:59:59.991", 0 ], [ "2012-02-12 23:59:59.991Z", 0 ], [ "2012-02-12", 0 ], [ "2012-02-12Z", 0 ], [ "2012-02-12T13:24:12Z", 0 ], [ "2012-02-12Z", 0 ], [ "2012-2-12Z", 0 ], [ "1910-01-02T03:04:05Z", 0 ], [ "1910-01-02 03:04:05Z", 0 ], [ "1910-01-02", 0 ], [ "1910-01-02Z", 0 ], [ "1970-01-01T01:05:27", 4 ], [ "1970-01-01T01:05:27Z", 4 ], [ "1970-01-01 01:05:27Z", 4 ], [ "1970-1-1Z", 4 ], [ "1221-02-28T23:59:59Z", 0 ], [ "1221-02-28 23:59:59Z", 0 ], [ "1221-02-28Z", 0 ], [ "1221-2-28Z", 0 ], [ "1000-12-24T04:12:00Z", 3 ], [ "1000-12-24Z", 3 ], [ "1000-12-24 04:12:00Z", 3 ], [ "6789-12-31T23:59:58.99Z", 0 ], [ "6789-12-31Z", 0 ], [ "9999-12-31T23:59:59.999Z", 5 ], [ "9999-12-31Z", 5 ], [ "9999-12-31z", 5 ], [ "9999-12-31", 5 ], [ "2012Z", 0 ], [ "2012z", 0 ], [ "2012", 0 ], [ "2012-1Z", 0 ], [ "2012-1z", 0 ], [ "2012-1-1z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-01Z", 0 ], [ " 2012-01-01Z", 0 ], [ " 2012-01-01z", 0 ], [ 1399395674000, 2 ], [ 60123, 4 ], [ 1, 4 ], [ 0, 4 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_DAYOFWEEK(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_year function //////////////////////////////////////////////////////////////////////////////// testDateYearInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_YEAR()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_YEAR(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_year function //////////////////////////////////////////////////////////////////////////////// testDateYear : function () { var values = [ [ "2000-04-29Z", 2000 ], [ "2012-02-12 13:24:12Z", 2012 ], [ "2012-02-12 23:59:59.991Z", 2012 ], [ "2012-02-12Z", 2012 ], [ "2012-02-12T13:24:12Z", 2012 ], [ "2012-02-12Z", 2012 ], [ "2012-2-12Z", 2012 ], [ "1910-01-02T03:04:05Z", 1910 ], [ "1910-01-02 03:04:05Z", 1910 ], [ "1910-01-02Z", 1910 ], [ "1970-01-01T01:05:27Z", 1970 ], [ "1970-01-01 01:05:27Z", 1970 ], [ "1970-1-1Z", 1970 ], [ "1221-02-28T23:59:59Z", 1221 ], [ "1221-02-28 23:59:59Z", 1221 ], [ "1221-02-28Z", 1221 ], [ "1221-2-28Z", 1221 ], [ "1000-12-24T04:12:00Z", 1000 ], [ "1000-12-24Z", 1000 ], [ "1000-12-24 04:12:00Z", 1000 ], [ "6789-12-31T23:59:58.99Z", 6789 ], [ "6789-12-31Z", 6789 ], [ "9999-12-31T23:59:59.999Z", 9999 ], [ "9999-12-31Z", 9999 ], [ "9999-12-31z", 9999 ], [ "9999-12-31", 9999 ], [ "2012Z", 2012 ], [ "2012z", 2012 ], [ "2012", 2012 ], [ "2012-1Z", 2012 ], [ "2012-1z", 2012 ], [ "2012-1-1z", 2012 ], [ "2012-01-01Z", 2012 ], [ "2012-01-01Z", 2012 ], [ " 2012-01-01Z", 2012 ], [ " 2012-01-01z", 2012 ], [ 1399395674000, 2014 ], [ 60123, 1970 ], [ 1, 1970 ], [ 0, 1970 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_YEAR(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_month function //////////////////////////////////////////////////////////////////////////////// testDateMonthInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MONTH()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MONTH(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_month function //////////////////////////////////////////////////////////////////////////////// testDateMonth : function () { var values = [ [ "2000-04-29Z", 4 ], [ "2012-02-12 13:24:12Z", 2 ], [ "2012-02-12 23:59:59.991Z", 2 ], [ "2012-02-12Z", 2 ], [ "2012-02-12T13:24:12Z", 2 ], [ "2012-02-12Z", 2 ], [ "2012-2-12Z", 2 ], [ "1910-01-02T03:04:05Z", 1 ], [ "1910-01-02 03:04:05Z", 1 ], [ "1910-01-02Z", 1 ], [ "1970-01-01T01:05:27Z", 1 ], [ "1970-01-01 01:05:27Z", 1 ], [ "1970-1-1Z", 1 ], [ "1221-02-28T23:59:59Z", 2 ], [ "1221-02-28 23:59:59Z", 2 ], [ "1221-02-28Z", 2 ], [ "1221-2-28Z", 2 ], [ "1000-12-24T04:12:00Z", 12 ], [ "1000-12-24Z", 12 ], [ "1000-12-24 04:12:00Z", 12 ], [ "6789-12-31T23:59:58.99Z", 12 ], [ "6789-12-31Z", 12 ], [ "9999-12-31T23:59:59.999Z", 12 ], [ "9999-12-31Z", 12 ], [ "9999-12-31z", 12 ], [ "9999-12-31", 12 ], [ "2012Z", 1 ], [ "2012z", 1 ], [ "2012", 1 ], [ "2012-2Z", 2 ], [ "2012-1Z", 1 ], [ "2012-1z", 1 ], [ "2012-1-1z", 1 ], [ "2012-01-01Z", 1 ], [ "2012-01-01Z", 1 ], [ " 2012-01-01Z", 1 ], [ " 2012-01-01z", 1 ], [ 1399395674000, 5 ], [ 60123, 1 ], [ 1, 1 ], [ 0, 1 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_MONTH(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_day function //////////////////////////////////////////////////////////////////////////////// testDateDayInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAY()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAY(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_day function //////////////////////////////////////////////////////////////////////////////// testDateDay : function () { var values = [ [ "2000-04-29Z", 29 ], [ "2012-02-12 13:24:12Z", 12 ], [ "2012-02-12 23:59:59.991Z", 12 ], [ "2012-02-12Z", 12 ], [ "2012-02-12T13:24:12Z", 12 ], [ "2012-02-12Z", 12 ], [ "2012-2-12Z", 12 ], [ "1910-01-02T03:04:05Z", 2 ], [ "1910-01-02 03:04:05Z", 2 ], [ "1910-01-02Z", 2 ], [ "1970-01-01T01:05:27Z", 1 ], [ "1970-01-01 01:05:27Z", 1 ], [ "1970-1-1Z", 1 ], [ "1221-02-28T23:59:59Z", 28 ], [ "1221-02-28 23:59:59Z", 28 ], [ "1221-02-28Z", 28 ], [ "1221-2-28Z", 28 ], [ "1000-12-24T04:12:00Z", 24 ], [ "1000-12-24Z", 24 ], [ "1000-12-24 04:12:00Z", 24 ], [ "6789-12-31T23:59:58.99Z", 31 ], [ "6789-12-31Z", 31 ], [ "9999-12-31T23:59:59.999Z", 31 ], [ "9999-12-31Z", 31 ], [ "9999-12-31z", 31 ], [ "9999-12-31", 31 ], [ "2012Z", 1 ], [ "2012z", 1 ], [ "2012", 1 ], [ "2012-2Z", 1 ], [ "2012-1Z", 1 ], [ "2012-1z", 1 ], [ "2012-1-1z", 1 ], [ "2012-01-01Z", 1 ], [ "2012-01-01Z", 1 ], [ "2012-01-02Z", 2 ], [ "2012-01-2Z", 2 ], [ " 2012-01-01Z", 1 ], [ " 2012-01-01z", 1 ], [ 1399395674000, 6 ], [ 60123, 1 ], [ 1, 1 ], [ 0, 1 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_DAY(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_hour function //////////////////////////////////////////////////////////////////////////////// testDateHourInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_HOUR()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_HOUR(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_hour function //////////////////////////////////////////////////////////////////////////////// testDateHour : function () { var values = [ [ "2000-04-29", 0 ], [ "2000-04-29Z", 0 ], [ "2012-02-12 13:24:12", 13 ], [ "2012-02-12 13:24:12Z", 13 ], [ "2012-02-12 23:59:59.991Z", 23 ], [ "2012-02-12", 0 ], [ "2012-02-12Z", 0 ], [ "2012-02-12T13:24:12", 13 ], [ "2012-02-12T13:24:12Z", 13 ], [ "2012-02-12", 0 ], [ "2012-02-12Z", 0 ], [ "2012-2-12Z", 0 ], [ "1910-01-02T03:04:05", 3 ], [ "1910-01-02T03:04:05Z", 3 ], [ "1910-01-02 03:04:05Z", 3 ], [ "1910-01-02Z", 0 ], [ "1970-01-01T01:05:27Z", 1 ], [ "1970-01-01 01:05:27Z", 1 ], [ "1970-01-01T12:05:27Z", 12 ], [ "1970-01-01 12:05:27Z", 12 ], [ "1970-1-1Z", 0 ], [ "1221-02-28T23:59:59Z", 23 ], [ "1221-02-28 23:59:59Z", 23 ], [ "1221-02-28Z", 0 ], [ "1221-2-28Z", 0 ], [ "1000-12-24T04:12:00Z", 4 ], [ "1000-12-24Z", 0 ], [ "1000-12-24 04:12:00Z", 4 ], [ "6789-12-31T23:59:58.99Z", 23 ], [ "6789-12-31Z", 0 ], [ "9999-12-31T23:59:59.999Z", 23 ], [ "9999-12-31Z", 0 ], [ "9999-12-31z", 0 ], [ "9999-12-31", 0 ], [ "2012Z", 0 ], [ "2012z", 0 ], [ "2012", 0 ], [ "2012-2Z", 0 ], [ "2012-1Z", 0 ], [ "2012-1z", 0 ], [ "2012-1-1z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-02Z", 0 ], [ "2012-01-2Z", 0 ], [ " 2012-01-01Z", 0 ], [ " 2012-01-01z", 0 ], [ 1399395674000, 17 ], [ 3600000, 1 ], [ 7200000, 2 ], [ 8200000, 2 ], [ 60123, 0 ], [ 1, 0 ], [ 0, 0 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_HOUR(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_minute function //////////////////////////////////////////////////////////////////////////////// testDateMinuteInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MINUTE()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MINUTE(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_minute function //////////////////////////////////////////////////////////////////////////////// testDateMinute : function () { var values = [ [ "2000-04-29Z", 0 ], [ "2012-02-12 13:24:12Z", 24 ], [ "2012-02-12 23:59:59.991Z", 59 ], [ "2012-02-12Z", 0 ], [ "2012-02-12T13:24:12Z", 24 ], [ "2012-02-12Z", 0 ], [ "2012-2-12Z", 0 ], [ "1910-01-02T03:04:05Z", 4 ], [ "1910-01-02 03:04:05Z", 4 ], [ "1910-01-02Z", 0 ], [ "1970-01-01T01:05:27Z", 5 ], [ "1970-01-01 01:05:27Z", 5 ], [ "1970-01-01T12:05:27Z", 5 ], [ "1970-01-01 12:05:27Z", 5 ], [ "1970-1-1Z", 0 ], [ "1221-02-28T23:59:59Z", 59 ], [ "1221-02-28 23:59:59Z", 59 ], [ "1221-02-28Z", 0 ], [ "1221-2-28Z", 0 ], [ "1000-12-24T04:12:00Z", 12 ], [ "1000-12-24Z", 0 ], [ "1000-12-24 04:12:00Z", 12 ], [ "6789-12-31T23:59:58.99Z", 59 ], [ "6789-12-31Z", 0 ], [ "9999-12-31T23:59:59.999Z", 59 ], [ "9999-12-31Z", 0 ], [ "9999-12-31z", 0 ], [ "9999-12-31", 0 ], [ "2012Z", 0 ], [ "2012z", 0 ], [ "2012", 0 ], [ "2012-2Z", 0 ], [ "2012-1Z", 0 ], [ "2012-1z", 0 ], [ "2012-1-1z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-02Z", 0 ], [ "2012-01-2Z", 0 ], [ " 2012-01-01Z", 0 ], [ " 2012-01-01z", 0 ], [ 1399395674000, 1 ], [ 3600000, 0 ], [ 7200000, 0 ], [ 8200000, 16 ], [ 60123, 1 ], [ 1, 0 ], [ 0, 0 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_MINUTE(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_second function //////////////////////////////////////////////////////////////////////////////// testDateSecondInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_SECOND()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_SECOND(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_second function //////////////////////////////////////////////////////////////////////////////// testDateSecond : function () { var values = [ [ "2000-04-29Z", 0 ], [ "2012-02-12 13:24:12Z", 12 ], [ "2012-02-12 23:59:59.991Z", 59 ], [ "2012-02-12Z", 0 ], [ "2012-02-12T13:24:12Z", 12 ], [ "2012-02-12Z", 0 ], [ "2012-2-12Z", 0 ], [ "1910-01-02T03:04:05Z", 5 ], [ "1910-01-02 03:04:05Z", 5 ], [ "1910-01-02Z", 0 ], [ "1970-01-01T01:05:27Z", 27 ], [ "1970-01-01 01:05:27Z", 27 ], [ "1970-01-01T12:05:27Z", 27 ], [ "1970-01-01 12:05:27Z", 27 ], [ "1970-1-1Z", 0 ], [ "1221-02-28T23:59:59Z", 59 ], [ "1221-02-28 23:59:59Z", 59 ], [ "1221-02-28Z", 0 ], [ "1221-2-28Z", 0 ], [ "1000-12-24T04:12:00Z", 0 ], [ "1000-12-24Z", 0 ], [ "1000-12-24 04:12:00Z", 0 ], [ "6789-12-31T23:59:58.99Z", 58 ], [ "6789-12-31Z", 0 ], [ "9999-12-31T23:59:59.999Z", 59 ], [ "9999-12-31Z", 0 ], [ "9999-12-31z", 0 ], [ "9999-12-31", 0 ], [ "2012Z", 0 ], [ "2012z", 0 ], [ "2012", 0 ], [ "2012-2Z", 0 ], [ "2012-1Z", 0 ], [ "2012-1z", 0 ], [ "2012-1-1z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-02Z", 0 ], [ "2012-01-2Z", 0 ], [ " 2012-01-01Z", 0 ], [ " 2012-01-01z", 0 ], [ 1399395674000, 14 ], [ 3600000, 0 ], [ 7200000, 0 ], [ 8200000, 40 ], [ 61123, 1 ], [ 60123, 0 ], [ 2001, 2 ], [ 2000, 2 ], [ 1000, 1 ], [ 1, 0 ], [ 0, 0 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_SECOND(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_millisecond function //////////////////////////////////////////////////////////////////////////////// testDateMillisecondInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MILLISECOND()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MILLISECOND(1, 1)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND(null)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND(false)"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND([])"); assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND({})"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_millisecond function //////////////////////////////////////////////////////////////////////////////// testDateMillisecond : function () { var values = [ [ "2000-04-29Z", 0 ], [ "2012-02-12 13:24:12Z", 0 ], [ "2012-02-12 23:59:59.991Z", 991 ], [ "2012-02-12Z", 0 ], [ "2012-02-12T13:24:12Z", 0 ], [ "2012-02-12Z", 0 ], [ "2012-2-12Z", 0 ], [ "1910-01-02T03:04:05Z", 0 ], [ "1910-01-02 03:04:05Z", 0 ], [ "1910-01-02Z", 0 ], [ "1970-01-01T01:05:27Z", 0 ], [ "1970-01-01 01:05:27Z", 0 ], [ "1970-01-01T12:05:27Z", 0 ], [ "1970-01-01 12:05:27Z", 0 ], [ "1970-1-1Z", 0 ], [ "1221-02-28T23:59:59Z", 0 ], [ "1221-02-28 23:59:59Z", 0 ], [ "1221-02-28Z", 0 ], [ "1221-2-28Z", 0 ], [ "1000-12-24T04:12:00Z", 0 ], [ "1000-12-24Z", 0 ], [ "1000-12-24 04:12:00Z", 0 ], [ "6789-12-31T23:59:58.99Z", 990 ], [ "6789-12-31Z", 0 ], [ "9999-12-31T23:59:59.999Z", 999 ], [ "9999-12-31Z", 0 ], [ "9999-12-31z", 0 ], [ "9999-12-31", 0 ], [ "2012Z", 0 ], [ "2012z", 0 ], [ "2012", 0 ], [ "2012-2Z", 0 ], [ "2012-1Z", 0 ], [ "2012-1z", 0 ], [ "2012-1-1z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-01Z", 0 ], [ "2012-01-02Z", 0 ], [ "2012-01-2Z", 0 ], [ " 2012-01-01Z", 0 ], [ " 2012-01-01z", 0 ], [ 1399395674000, 0 ], [ 1399395674123, 123 ], [ 3600000, 0 ], [ 7200000, 0 ], [ 8200000, 0 ], [ 8200040, 40 ], [ 61123, 123 ], [ 60123, 123 ], [ 2001, 1 ], [ 2000, 0 ], [ 1000, 0 ], [ 753, 753 ], [ 53, 53 ], [ 1, 1 ], [ 0, 0 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_MILLISECOND(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_timestamp function //////////////////////////////////////////////////////////////////////////////// testDateTimestampInvalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_TIMESTAMP()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_TIMESTAMP(1, 1, 1, 1, 1, 1, 1, 1)"); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_timestamp function //////////////////////////////////////////////////////////////////////////////// testDateTimestamp : function () { var values = [ [ "2000-04-29", 956966400000 ], [ "2000-04-29Z", 956966400000 ], [ "2012-02-12 13:24:12", 1329053052000 ], [ "2012-02-12 13:24:12Z", 1329053052000 ], [ "2012-02-12 23:59:59.991", 1329091199991 ], [ "2012-02-12 23:59:59.991Z", 1329091199991 ], [ "2012-02-12", 1329004800000 ], [ "2012-02-12Z", 1329004800000 ], [ "2012-02-12T13:24:12", 1329053052000 ], [ "2012-02-12T13:24:12Z", 1329053052000 ], [ "2012-02-12Z", 1329004800000 ], [ "2012-2-12Z", 1329004800000 ], [ "1910-01-02T03:04:05", -1893358555000 ], [ "1910-01-02T03:04:05Z", -1893358555000 ], [ "1910-01-02 03:04:05Z", -1893358555000 ], [ "1910-01-02", -1893369600000 ], [ "1910-01-02Z", -1893369600000 ], [ "1970-01-01T01:05:27Z", 3927000 ], [ "1970-01-01 01:05:27Z", 3927000 ], [ "1970-01-01T12:05:27Z", 43527000 ], [ "1970-01-01 12:05:27Z", 43527000 ], [ "1970-1-1Z", 0 ], [ "1221-02-28T23:59:59Z", -23631004801000 ], [ "1221-02-28 23:59:59Z", -23631004801000 ], [ "1221-02-28Z", -23631091200000 ], [ "1221-2-28Z", -23631091200000 ], [ "1000-12-24T04:12:00Z", -30579364080000 ], [ "1000-12-24Z", -30579379200000 ], [ "1000-12-24 04:12:00Z", -30579364080000 ], [ "6789-12-31T23:59:58.99Z", 152104521598990 ], [ "6789-12-31Z", 152104435200000 ], [ "9999-12-31T23:59:59.999Z", 253402300799999 ], [ "9999-12-31Z", 253402214400000 ], [ "9999-12-31z", 253402214400000 ], [ "9999-12-31", 253402214400000 ], [ "2012Z", 1325376000000 ], [ "2012z", 1325376000000 ], [ "2012", 1325376000000 ], [ "2012-2Z", 1328054400000 ], [ "2012-1Z", 1325376000000 ], [ "2012-1z", 1325376000000 ], [ "2012-1-1z", 1325376000000 ], [ "2012-01-01Z", 1325376000000 ], [ "2012-01-01Z", 1325376000000 ], [ "2012-01-02Z", 1325462400000 ], [ "2012-01-2Z", 1325462400000 ], [ " 2012-01-01Z", 1325376000000 ], [ " 2012-01-01z", 1325376000000 ], [ 1399395674000, 1399395674000 ], [ 3600000, 3600000 ], [ 7200000, 7200000 ], [ 8200000, 8200000 ], [ 61123, 61123 ], [ 60123, 60123 ], [ 2001, 2001 ], [ 2000, 2000 ], [ 1000, 1000 ], [ 121, 121 ], [ 1, 1 ], [ 0, 0 ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_TIMESTAMP(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_iso8601 function //////////////////////////////////////////////////////////////////////////////// testDateIso8601Invalid : function () { assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_ISO8601()"); assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_ISO8601(1, 1, 1, 1, 1, 1, 1, 1)"); var values = [ "foobar", "2012fjh", " 2012tjjgg", "", " ", "abc2012-01-01", "2000-00-00", "2001-02-11 24:00:00", "2001-02-11 24:01:01", "2001-02-11 25:01:01", "2001-02-11 23:60:00", "2001-02-11 23:01:60", "2001-02-11 23:01:99", "2001-00-11", "2001-0-11", "2001-13-11", "2001-13-32", "2001-01-0", "2001-01-00", "2001-01-32", "2001-1-32" ]; values.forEach(function(value) { assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_ISO8601(@value)", { value: value }); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_iso8601 function //////////////////////////////////////////////////////////////////////////////// testDateIso8601 : function () { var values = [ [ "2000-04-29", "2000-04-29T00:00:00.000Z" ], [ "2000-04-29Z", "2000-04-29T00:00:00.000Z" ], [ "2012-02-12 13:24:12", "2012-02-12T13:24:12.000Z" ], [ "2012-02-12 13:24:12Z", "2012-02-12T13:24:12.000Z" ], [ "2012-02-12 23:59:59.991", "2012-02-12T23:59:59.991Z" ], [ "2012-02-12 23:59:59.991Z", "2012-02-12T23:59:59.991Z" ], [ "2012-02-12", "2012-02-12T00:00:00.000Z" ], [ "2012-02-12Z", "2012-02-12T00:00:00.000Z" ], [ "2012-02-12T13:24:12", "2012-02-12T13:24:12.000Z" ], [ "2012-02-12T13:24:12Z", "2012-02-12T13:24:12.000Z" ], [ "2012-02-12Z", "2012-02-12T00:00:00.000Z" ], [ "2012-2-12Z", "2012-02-12T00:00:00.000Z" ], [ "1910-01-02T03:04:05", "1910-01-02T03:04:05.000Z" ], [ "1910-01-02T03:04:05Z", "1910-01-02T03:04:05.000Z" ], [ "1910-01-02 03:04:05", "1910-01-02T03:04:05.000Z" ], [ "1910-01-02 03:04:05Z", "1910-01-02T03:04:05.000Z" ], [ "1910-01-02", "1910-01-02T00:00:00.000Z" ], [ "1910-01-02Z", "1910-01-02T00:00:00.000Z" ], [ "1970-01-01T01:05:27+01:00", "1970-01-01T00:05:27.000Z" ], [ "1970-01-01T01:05:27-01:00", "1970-01-01T02:05:27.000Z" ], [ "1970-01-01T01:05:27", "1970-01-01T01:05:27.000Z" ], [ "1970-01-01T01:05:27Z", "1970-01-01T01:05:27.000Z" ], [ "1970-01-01 01:05:27Z", "1970-01-01T01:05:27.000Z" ], [ "1970-01-01T12:05:27Z", "1970-01-01T12:05:27.000Z" ], [ "1970-01-01 12:05:27Z", "1970-01-01T12:05:27.000Z" ], [ "1970-1-1Z", "1970-01-01T00:00:00.000Z" ], [ "1221-02-28T23:59:59", "1221-02-28T23:59:59.000Z" ], [ "1221-02-28T23:59:59Z", "1221-02-28T23:59:59.000Z" ], [ "1221-02-28 23:59:59Z", "1221-02-28T23:59:59.000Z" ], [ "1221-02-28", "1221-02-28T00:00:00.000Z" ], [ "1221-02-28Z", "1221-02-28T00:00:00.000Z" ], [ "1221-2-28Z", "1221-02-28T00:00:00.000Z" ], [ "1000-12-24T04:12:00Z", "1000-12-24T04:12:00.000Z" ], [ "1000-12-24Z", "1000-12-24T00:00:00.000Z" ], [ "1000-12-24 04:12:00Z", "1000-12-24T04:12:00.000Z" ], [ "6789-12-31T23:59:58.99Z", "6789-12-31T23:59:58.990Z" ], [ "6789-12-31Z", "6789-12-31T00:00:00.000Z" ], [ "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z" ], [ "9999-12-31Z", "9999-12-31T00:00:00.000Z" ], [ "9999-12-31z", "9999-12-31T00:00:00.000Z" ], [ "9999-12-31", "9999-12-31T00:00:00.000Z" ], [ "2012Z", "2012-01-01T00:00:00.000Z" ], [ "2012z", "2012-01-01T00:00:00.000Z" ], [ "2012", "2012-01-01T00:00:00.000Z" ], [ "2012-2Z", "2012-02-01T00:00:00.000Z" ], [ "2012-1Z", "2012-01-01T00:00:00.000Z" ], [ "2012-1z", "2012-01-01T00:00:00.000Z" ], [ "2012-1-1z", "2012-01-01T00:00:00.000Z" ], [ "2012-01-01", "2012-01-01T00:00:00.000Z" ], [ "2012-01-01Z", "2012-01-01T00:00:00.000Z" ], [ "2012-01-01Z", "2012-01-01T00:00:00.000Z" ], [ "2012-01-02Z", "2012-01-02T00:00:00.000Z" ], [ "2012-01-2Z", "2012-01-02T00:00:00.000Z" ], [ " 2012-01-01Z", "2012-01-01T00:00:00.000Z" ], [ " 2012-01-01z", "2012-01-01T00:00:00.000Z" ], [ 1399395674000, "2014-05-06T17:01:14.000Z" ], [ 3600000, "1970-01-01T01:00:00.000Z" ], [ 7200000, "1970-01-01T02:00:00.000Z" ], [ 8200000, "1970-01-01T02:16:40.000Z" ], [ 61123, "1970-01-01T00:01:01.123Z" ], [ 60123, "1970-01-01T00:01:00.123Z" ], [ 2001, "1970-01-01T00:00:02.001Z" ], [ 2000, "1970-01-01T00:00:02.000Z" ], [ 1000, "1970-01-01T00:00:01.000Z" ], [ 121, "1970-01-01T00:00:00.121Z" ], [ 1, "1970-01-01T00:00:00.001Z" ], [ 0, "1970-01-01T00:00:00.000Z" ] ]; values.forEach(function (value) { var actual = getQueryResults("RETURN DATE_ISO8601(@value)", { value: value[0] }); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date_iso8601 function //////////////////////////////////////////////////////////////////////////////// testDateIso8601Alternative : function () { var values = [ [ [ 1000, 1, 1, 0, 0, 0, 0 ], "1000-01-01T00:00:00.000Z" ], [ [ 9999, 12, 31, 23, 59, 59, 999 ], "9999-12-31T23:59:59.999Z" ], [ [ 2012, 1, 1, 13, 12, 14, 95 ], "2012-01-01T13:12:14.095Z" ], [ [ 1234, 12, 31, 23, 59, 59, 477 ], "1234-12-31T23:59:59.477Z" ], [ [ 2014, 5, 7, 12, 6 ], "2014-05-07T12:06:00.000Z" ], [ [ 2014, 5, 7, 12 ], "2014-05-07T12:00:00.000Z" ], [ [ 2014, 5, 7 ], "2014-05-07T00:00:00.000Z" ], [ [ 2014, 5, 7 ], "2014-05-07T00:00:00.000Z" ], [ [ 1000, 1, 1 ], "1000-01-01T00:00:00.000Z" ], [ [ "1000", "01", "01", "00", "00", "00", "00" ], "1000-01-01T00:00:00.000Z" ], [ [ "1000", "1", "1", "0", "0", "0", "0" ], "1000-01-01T00:00:00.000Z" ], [ [ "9999", "12", "31", "23", "59", "59", "999" ], "9999-12-31T23:59:59.999Z" ], [ [ "2012", "1", "1", "13", "12", "14", "95" ], "2012-01-01T13:12:14.095Z" ], [ [ "1234", "12", "31", "23", "59", "59", "477" ], "1234-12-31T23:59:59.477Z" ], [ [ "2014", "05", "07", "12", "06" ], "2014-05-07T12:06:00.000Z" ], [ [ "2014", "5", "7", "12", "6" ], "2014-05-07T12:06:00.000Z" ], [ [ "2014", "5", "7", "12" ], "2014-05-07T12:00:00.000Z" ], [ [ "2014", "5", "7" ], "2014-05-07T00:00:00.000Z" ], [ [ "2014", "5", "7" ], "2014-05-07T00:00:00.000Z" ], [ [ "1000", "01", "01" ], "1000-01-01T00:00:00.000Z" ], [ [ "1000", "1", "1" ], "1000-01-01T00:00:00.000Z" ], ]; values.forEach(function (value) { var query = "RETURN DATE_ISO8601(" + value[0].map(function(v) { return JSON.stringify(v); }).join(", ") + ")"; var actual = getQueryResults(query); assertEqual([ value[1] ], actual); }); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date transformations //////////////////////////////////////////////////////////////////////////////// testDateTransformations1 : function () { var dt = "2014-05-07T15:23:21.446"; var actual; actual = getQueryResults("RETURN DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value))", { value: dt }); assertEqual([ new Date(dt).getTime() ], actual); actual = getQueryResults("RETURN DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value))", { value: dt + "Z" }); assertEqual([ new Date(dt).getTime() ], actual); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test date transformations //////////////////////////////////////////////////////////////////////////////// testDateTransformations2 : function () { var dt = "2014-05-07T15:23:21.446"; var actual; actual = getQueryResults("RETURN DATE_ISO8601(DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value)))", { value: dt }); assertEqual([ dt + "Z" ], actual); actual = getQueryResults("RETURN DATE_ISO8601(DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value)))", { value: dt + "Z" }); assertEqual([ dt + "Z" ], actual); } }; } //////////////////////////////////////////////////////////////////////////////// /// @brief executes the test suite //////////////////////////////////////////////////////////////////////////////// jsunity.run(ahuacatlDateFunctionsTestSuite); return jsunity.done(); // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)" // End:
morsdatum/ArangoDB
js/server/tests/aql-functions-date.js
JavaScript
apache-2.0
38,362
// (c) Copyright 2015 Cloudera, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.director.spi.v2.model; /** * Represents a configuration property. Used to simplify enum-based configuration property * implementations. */ public interface ConfigurationPropertyToken { /** * Returns the configuration property. * * @return the configuration property */ ConfigurationProperty unwrap(); }
cloudera/director-spi
src/main/java/com/cloudera/director/spi/v2/model/ConfigurationPropertyToken.java
Java
apache-2.0
939
/* * Copyright 2003 - 2014 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ /** * The FormPage and its related Markup File. */ package org.efaps.ui.wicket.pages.content.form;
eFaps/eFaps-WebApp
src/main/java/org/efaps/ui/wicket/pages/content/form/package-info.java
Java
apache-2.0
792
/* * Copyright 2014 Nassau authors * * 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.paritytrading.nassau.util; import static com.paritytrading.nassau.soupbintcp.SoupBinTCP.*; import com.paritytrading.nassau.MessageListener; import com.paritytrading.nassau.soupbintcp.SoupBinTCPClient; import com.paritytrading.nassau.soupbintcp.SoupBinTCPClientStatusListener; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; /** * Utility methods for working with the SoupBinTCP 3.00 protocol. */ public class SoupBinTCP { private static final int TIMEOUT_MILLIS = 1000; private SoupBinTCP() { } /** * Receive messages. Invoke the message listener on each message. Continue * until an End of Session packet is received or the end-of-stream is * reached. * * @param address the address * @param username the username * @param password the password * @param listener a message listener * @throws IOException if an I/O error occurs */ public static void receive(InetSocketAddress address, String username, String password, MessageListener listener) throws IOException { SocketChannel channel = SocketChannel.open(); channel.connect(address); channel.configureBlocking(false); StatusListener statusListener = new StatusListener(); try (Selector selector = Selector.open(); SoupBinTCPClient client = new SoupBinTCPClient(channel, listener, statusListener)) { channel.register(selector, SelectionKey.OP_READ); LoginRequest message = new LoginRequest(); message.setUsername(username); message.setPassword(password); message.setRequestedSession(""); message.setRequestedSequenceNumber(1); client.login(message); while (statusListener.receive) { int numKeys = selector.select(TIMEOUT_MILLIS); if (numKeys > 0) { if (client.receive() < 0) break; selector.selectedKeys().clear(); } client.keepAlive(); } } } private static class StatusListener implements SoupBinTCPClientStatusListener { boolean receive = true; @Override public void heartbeatTimeout(SoupBinTCPClient session) throws IOException { throw new IOException("Heartbeat timeout"); } @Override public void loginAccepted(SoupBinTCPClient session, LoginAccepted payload) { } @Override public void loginRejected(SoupBinTCPClient session, LoginRejected payload) throws IOException { throw new IOException("Login rejected"); } @Override public void endOfSession(SoupBinTCPClient session) { receive = false; } } }
paritytrading/nassau
libraries/util/src/main/java/com/paritytrading/nassau/util/SoupBinTCP.java
Java
apache-2.0
3,555
<?php /** * File for Options class */ namespace Cayman\Manager\FilterManager; /** * Class for Option * */ abstract class Option { public $filterName; public $errorMessage = 'Invalid input'; public $params = []; function __construct($filterName, $errorMessage, $params = []) { $this->filterName = $filterName; $this->errorMessage = $errorMessage; $this->params = $params; } }
CaymanParrot/Cayman
src/Cayman/Manager/FilterManager/Option.php
PHP
apache-2.0
458
package ru.skorikov; import java.util.Arrays; /** * Created with IntelliJ IDEA. * * @ author: Alex Skorikov. * @ date: 17.07.17 * @ version Stady_2. */ public class MenuTracker { /** * interface Input. */ private Input input; /** * New instance of the class Tracker. */ private Tracker tracker; /** * Размер массива внутренних классов. */ static final int RAZMER = 6; /** * New instance of the class UserAction. */ private UserAction[] actions = new UserAction[RAZMER]; /** * Конструктор класса. * * @param atInput ввод * @param atTracker трекер */ public MenuTracker(Input atInput, Tracker atTracker) { this.input = atInput; this.tracker = atTracker; } /** * Меню из массива внутренних классов. */ public void fillActions() { this.actions[0] = new AddItem(); this.actions[1] = new ShowAllItems(); this.actions[2] = new EditItem(); this.actions[3] = new DeleteItem(); this.actions[4] = new FindById(); this.actions[5] = new FindByName(); } /** * Выбор элемента меню. * * @param key ключ */ public void select(int key) { this.actions[key].execute(this.input, this.tracker); } /** * Отображение меню. */ public void show() { for (UserAction action : this.actions) { System.out.println(action.info()); } } /** * 0. Внутренний класс - добавить заявку. */ private class AddItem implements UserAction { /** * Если выбран ключ 0. * * @return 0 */ public int key() { return 0; } /** * Метод класса. * * @param atInput ввод * @param atTracker трекер */ public void execute(Input atInput, Tracker atTracker) { String name = input.ask("Enter Item name:"); String description = input.ask("Enter Item description:"); if (tracker.getPosition() < 10) { Item item = new Item(name, description); tracker.add(item); } else { System.out.println("Нет места."); System.out.println("Удалите одну или несколько заявок."); } } /** * 1-й элемент меню на экране. * * @return строка. */ public String info() { return String.format("%s. %s", this.key(), "Add new Item."); } } /** * 1. Класс Показать все заявки. */ private class ShowAllItems implements UserAction { /** * Если выбран ключ 1. * * @return 1 */ public int key() { return 1; } /** * Метод класса. * * @param atInput ввод. * @param atTracker трекер. */ public void execute(Input atInput, Tracker atTracker) { System.out.println(Arrays.asList(tracker.findAll())); } /** * 2-й элемент меню на экране. * * @return строка */ public String info() { return String.format("%s. %s", this.key(), "Show all Items."); } } /** * 2. Класс Редактировать заявку. */ private class EditItem implements UserAction { /** * Если выбран ключ 2. * * @return 2 */ public int key() { return 2; } /** * Метод класса. * * @param atInput ввод * @param atTracker трекер */ public void execute(Input atInput, Tracker atTracker) { String idItem = input.ask("Enter ID item:"); if (tracker.findeById(idItem) != null) { String newName = input.ask("Enter new name:"); String newDescription = input.ask("Enter new description"); Item editItem = new Item(newName, newDescription); tracker.update(idItem, editItem); System.out.println("Item changed."); } else { System.out.println("Item not found."); } } /** * 3-й элемент меню на экране. * * @return строка */ public String info() { return String.format("%s. %s", this.key(), "Edit Item."); } } /** * 3. Класс удалить заявку. */ private class DeleteItem implements UserAction { /** * Если выбран ключ 3. * * @return 3 */ public int key() { return 3; } /** * Метод класса. * * @param atInput ввод * @param atTracker трекер */ public void execute(Input atInput, Tracker atTracker) { String findIdItem = input.ask("Enter ID item:"); Item findItem = tracker.findeById(findIdItem); if (findItem == null) { System.out.println("Item not found."); } else { tracker.delete(findItem); System.out.println("Item deleted."); } } /** * 4-й элемент меню н экране. * * @return строка */ public String info() { return String.format("%s. %s", this.key(), "Delete Item."); } } /** * 4. Класс Поиск по номеру. */ private class FindById implements UserAction { /** * Если выбран ключ 4. * * @return 4 */ public int key() { return 4; } /** * Метод класса. * * @param atInput ввод * @param atTracker трекер */ public void execute(Input atInput, Tracker atTracker) { String findItemById = input.ask("Enter ID item:"); if (tracker.findeById(findItemById) != null) { tracker.findeById(findItemById); System.out.println(findItemById); } else { System.out.println("Item not found."); } } /** * 5-й элемент меню на экране. * * @return строка */ public String info() { return String.format("%s. %s", this.key(), "Find Item by Id."); } } /** * 5. Класс Поиск по имени. */ private class FindByName implements UserAction { /** * если выбран ключ 5. * * @return 5 */ public int key() { return 5; } /** * Метод класса. * * @param atInput ввод * @param atTracker трекер */ public void execute(Input atInput, Tracker atTracker) { String findItemByName = input.ask("Enter Name item:"); if (tracker.findeByName(findItemByName) != null) { tracker.findeByName(findItemByName); System.out.println(findItemByName); } else { System.out.println("Item not found."); } } /** * 6-й пункт меню. * * @return строка */ public String info() { return String.format("%s. %s", this.key(), "Find Item by Name."); } } }
KayzerSoze/java_kurs
chapter_002/part_008/src/main/java/ru/skorikov/MenuTracker.java
Java
apache-2.0
8,179
DEBUG = True SECRET_KEY = 'this is a not very secret key' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'rdmo', 'USER': 'root', 'PASSWORD': '', 'TEST': { 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', }, 'OPTIONS': { 'init_command': "SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));" } } }
DMPwerkzeug/DMPwerkzeug
testing/config/settings/mysql.py
Python
apache-2.0
456
/* ### * IP: GHIDRA * REVIEWED: YES * * 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 ghidra.program.model.listing; import ghidra.framework.model.ChangeSet; /** * Interface for a Program Tree Change set. Objects that implements this interface track * various change information on a program tree manager. */ public interface ProgramTreeChangeSet extends ChangeSet { // // Program Tree // /** * adds the program tree id to the list of trees that have changed. */ void programTreeChanged(long id); /** * adds the program tree id to the list of trees that have been added. */ void programTreeAdded(long id); /** * returns the list of program tree IDs that have changed. */ long[] getProgramTreeChanges(); /** * returns the list of program tree IDs that have been added. */ long[] getProgramTreeAdditions(); }
NationalSecurityAgency/ghidra
Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/ProgramTreeChangeSet.java
Java
apache-2.0
1,373
// SPDX-License-Identifier: Apache-2.0 // Copyright 2017-2020 Authors of Cilium package cmd import ( "encoding/gob" "errors" "fmt" "io" "net" "os" "os/signal" "strings" "time" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/cilium/cilium/api/v1/models" "github.com/cilium/cilium/pkg/defaults" "github.com/cilium/cilium/pkg/monitor" "github.com/cilium/cilium/pkg/monitor/agent/listener" "github.com/cilium/cilium/pkg/monitor/format" "github.com/cilium/cilium/pkg/monitor/payload" ) const ( connTimeout = 12 * time.Second ) // monitorCmd represents the monitor command var ( monitorCmd = &cobra.Command{ Use: "monitor", Short: "Display BPF program events", Long: `The monitor displays notifications and events emitted by the BPF programs attached to endpoints and devices. This includes: * Dropped packet notifications * Captured packet traces * Policy verdict notifications * Debugging information`, Run: func(cmd *cobra.Command, args []string) { runMonitor(args) }, } printer = format.NewMonitorFormatter(format.INFO) socketPath = "" verbosity = []bool{} ) func init() { rootCmd.AddCommand(monitorCmd) monitorCmd.Flags().BoolVar(&printer.Hex, "hex", false, "Do not dissect, print payload in HEX") monitorCmd.Flags().VarP(&printer.EventTypes, "type", "t", fmt.Sprintf("Filter by event types %v", monitor.GetAllTypes())) monitorCmd.Flags().Var(&printer.FromSource, "from", "Filter by source endpoint id") monitorCmd.Flags().Var(&printer.ToDst, "to", "Filter by destination endpoint id") monitorCmd.Flags().Var(&printer.Related, "related-to", "Filter by either source or destination endpoint id") monitorCmd.Flags().BoolSliceVarP(&verbosity, "verbose", "v", nil, "Enable verbose output (-v, -vv)") monitorCmd.Flags().Lookup("verbose").NoOptDefVal = "false" monitorCmd.Flags().BoolVarP(&printer.JSONOutput, "json", "j", false, "Enable json output. Shadows -v flag") monitorCmd.Flags().BoolVarP(&printer.Numeric, "numeric", "n", false, "Display all security identities as numeric values") monitorCmd.Flags().StringVar(&socketPath, "monitor-socket", "", "Configure monitor socket path") viper.BindEnv("monitor-socket", "CILIUM_MONITOR_SOCK") viper.BindPFlags(monitorCmd.Flags()) } func setVerbosity() { if printer.JSONOutput { printer.Verbosity = format.JSON } else { switch len(verbosity) { case 1: printer.Verbosity = format.DEBUG case 2: printer.Verbosity = format.VERBOSE default: printer.Verbosity = format.INFO } } } func setupSigHandler() { signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, os.Interrupt) go func() { for range signalChan { fmt.Fprintf(os.Stderr, "\nReceived an interrupt, disconnecting from monitor...\n\n") os.Exit(0) } }() } // openMonitorSock attempts to open a version specific monitor socket It // returns a connection, with a version, or an error. func openMonitorSock(path string) (conn net.Conn, version listener.Version, err error) { errors := make([]string, 0) // try the user-provided socket if path != "" { conn, err = net.Dial("unix", path) if err == nil { version = listener.Version1_2 return conn, version, nil } errors = append(errors, path+": "+err.Error()) } // try the 1.2 socket conn, err = net.Dial("unix", defaults.MonitorSockPath1_2) if err == nil { return conn, listener.Version1_2, nil } errors = append(errors, defaults.MonitorSockPath1_2+": "+err.Error()) return nil, listener.VersionUnsupported, fmt.Errorf("Cannot find or open a supported node-monitor socket. %s", strings.Join(errors, ",")) } // consumeMonitorEvents handles and prints events on a monitor connection. It // calls getMonitorParsed to construct a monitor-version appropriate parser. // It closes conn on return, and returns on error, including io.EOF func consumeMonitorEvents(conn net.Conn, version listener.Version) error { defer conn.Close() getParsedPayload, err := getMonitorParser(conn, version) if err != nil { return err } for { pl, err := getParsedPayload() if err != nil { return err } if !printer.FormatEvent(pl) { // earlier code used an else to handle this case, along with pl.Type == // payload.RecordLost above. It should be safe to call lostEvent to match // the earlier behaviour, despite it not being wholly correct. log.WithError(err).WithField("type", pl.Type).Warn("Unknown payload type") format.LostEvent(pl.Lost, pl.CPU) } } } // eventParseFunc is a convenience function type used as a version-specific // parser of monitor events type eventParserFunc func() (*payload.Payload, error) // getMonitorParser constructs and returns an eventParserFunc. It is // appropriate for the monitor API version passed in. func getMonitorParser(conn net.Conn, version listener.Version) (parser eventParserFunc, err error) { switch version { case listener.Version1_2: var ( pl payload.Payload dec = gob.NewDecoder(conn) ) // This implemenents the newer 1.2 API. Each listener maintains its own gob // session, and type information is only ever sent once. return func() (*payload.Payload, error) { if err := pl.DecodeBinary(dec); err != nil { return nil, err } return &pl, nil }, nil default: return nil, fmt.Errorf("unsupported version %s", version) } } func endpointsExist(endpoints format.Uint16Flags, existingEndpoints []*models.Endpoint) bool { endpointsFound := format.Uint16Flags{} for _, ep := range existingEndpoints { if endpoints.Has(uint16(ep.ID)) { endpointsFound = append(endpointsFound, uint16(ep.ID)) } } if len(endpointsFound) < len(endpoints) { for _, endpoint := range endpoints { if !endpointsFound.Has(endpoint) { fmt.Fprintf(os.Stderr, "endpoint %d not found\n", endpoint) } } } return len(endpointsFound) > 0 } func validateEndpointsFilters() { if !(len(printer.FromSource) > 0) || !(len(printer.ToDst) > 0) || !(len(printer.Related) > 0) { return } existingEndpoints, err := client.EndpointList() if err != nil { Fatalf("cannot get endpoint list: %s\n", err) } validFilter := false if len(printer.FromSource) > 0 { if endpointsExist(printer.FromSource, existingEndpoints) { validFilter = true } } if len(printer.ToDst) > 0 { if endpointsExist(printer.ToDst, existingEndpoints) { validFilter = true } } if len(printer.Related) > 0 { if endpointsExist(printer.Related, existingEndpoints) { validFilter = true } } // exit if all filters are not not found if !validFilter { os.Exit(1) } } func runMonitor(args []string) { if len(args) > 0 { fmt.Fprintln(os.Stderr, "Error: arguments not recognized") os.Exit(1) } validateEndpointsFilters() setVerbosity() setupSigHandler() if resp, err := client.Daemon.GetHealthz(nil); err == nil { if nm := resp.Payload.NodeMonitor; nm != nil { fmt.Fprintf(os.Stderr, "Listening for events on %d CPUs with %dx%d of shared memory\n", nm.Cpus, nm.Npages, nm.Pagesize) } } fmt.Fprintf(os.Stderr, "Press Ctrl-C to quit\n") // On EOF, retry // On other errors, exit // always wait connTimeout when retrying for ; ; time.Sleep(connTimeout) { conn, version, err := openMonitorSock(viper.GetString("monitor-socket")) if err != nil { log.WithError(err).Error("Cannot open monitor socket") return } err = consumeMonitorEvents(conn, version) switch { case err == nil: // no-op case err == io.EOF, errors.Is(err, io.ErrUnexpectedEOF): log.WithError(err).Warn("connection closed") continue default: log.WithError(err).Fatal("decoding error") } } }
michi-covalent/cilium
cilium/cmd/monitor.go
GO
apache-2.0
7,607
package com.ss.editor.ui.control.tree; import static com.ss.editor.ui.util.UiUtils.findItem; import static com.ss.editor.ui.util.UiUtils.findItemForValue; import static com.ss.rlib.common.util.ClassUtils.unsafeCast; import static com.ss.rlib.common.util.ObjectUtils.notNull; import com.ss.editor.annotation.FxThread; import com.ss.editor.manager.ExecutorManager; import com.ss.editor.model.undo.editor.ChangeConsumer; import com.ss.editor.ui.Icons; import com.ss.editor.ui.control.tree.node.HideableNode; import com.ss.editor.ui.control.tree.node.TreeNode; import com.ss.editor.ui.css.CssClasses; import com.ss.editor.ui.util.DynamicIconSupport; import com.ss.editor.ui.util.UiUtils; import com.ss.rlib.fx.util.FXUtils; import com.ss.rlib.common.util.StringUtils; import javafx.beans.property.BooleanProperty; import javafx.beans.property.BooleanPropertyBase; import javafx.css.PseudoClass; import javafx.geometry.Side; import javafx.scene.Cursor; import javafx.scene.control.*; import javafx.scene.control.cell.TextFieldTreeCell; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.layout.HBox; import javafx.util.StringConverter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; /** * The implementation of {@link TreeCell} to show tree nodes. * * @param <C> the type of a {@link ChangeConsumer} * @param <M> the type parameter * @author JavaSaBr */ public class NodeTreeCell<C extends ChangeConsumer, M extends NodeTree<C>> extends TextFieldTreeCell<TreeNode<?>> { @NotNull public static final DataFormat DATA_FORMAT = new DataFormat(NodeTreeCell.class.getName()); @NotNull private static final PseudoClass DROP_AVAILABLE_PSEUDO_CLASS = PseudoClass.getPseudoClass("drop-available"); @NotNull private static final PseudoClass DRAGGED_PSEUDO_CLASS = PseudoClass.getPseudoClass("dragged"); @NotNull private static final PseudoClass EDITING_PSEUDO_CLASS = PseudoClass.getPseudoClass("editing"); @NotNull private static final ExecutorManager EXECUTOR_MANAGER = ExecutorManager.getInstance(); @NotNull private final StringConverter<TreeNode<?>> stringConverter = new StringConverter<TreeNode<?>>() { @Override public String toString(@Nullable final TreeNode<?> object) { return object == null ? "" : object.getName(); } @Override public TreeNode<?> fromString(@NotNull final String string) { final TreeNode<?> item = getItem(); if (item == null) { return null; } item.changeName(getNodeTree(), string); return item; } }; /** * The dragged state. */ @NotNull private final BooleanProperty dragged = new BooleanPropertyBase(false) { public void invalidated() { pseudoClassStateChanged(DRAGGED_PSEUDO_CLASS, get()); } @Override public Object getBean() { return NodeTreeCell.this; } @Override public String getName() { return "dragged"; } }; /** * The drop available state. */ @NotNull private final BooleanProperty dropAvailable = new BooleanPropertyBase(false) { public void invalidated() { pseudoClassStateChanged(DROP_AVAILABLE_PSEUDO_CLASS, get()); } @Override public Object getBean() { return NodeTreeCell.this; } @Override public String getName() { return "drop available"; } }; /** * The editing state. */ @NotNull private final BooleanProperty editing = new BooleanPropertyBase(false) { public void invalidated() { pseudoClassStateChanged(EDITING_PSEUDO_CLASS, get()); } @Override public Object getBean() { return NodeTreeCell.this; } @Override public String getName() { return "editing"; } }; /** * The tree. */ @NotNull private final M nodeTree; /** * The icon of node. */ @NotNull private final ImageView icon; /** * The content box. */ @NotNull private final HBox content; /** * The label of this cell. */ @NotNull private final Label text; /** * The visible icon. */ @NotNull private final ImageView visibleIcon; /** * The flag of ignoring updates. */ private boolean ignoreUpdate; public NodeTreeCell(@NotNull final M nodeTree) { this.nodeTree = nodeTree; this.icon = new ImageView(); this.content = new HBox(); this.text = new Label(); this.visibleIcon = new ImageView(); this.visibleIcon.addEventFilter(MouseEvent.MOUSE_RELEASED, this::processHide); this.visibleIcon.setOnMouseReleased(this::processHide); this.visibleIcon.setPickOnBounds(true); setOnMouseClicked(this::processClick); setOnDragDetected(this::startDrag); setOnDragDone(this::stopDrag); setOnDragOver(this::dragOver); setOnDragDropped(this::dragDropped); setOnDragExited(this::dragExited); setOnKeyReleased(event -> { if (isEditing()) event.consume(); }); FXUtils.addToPane(icon, content); FXUtils.addToPane(visibleIcon, content); FXUtils.addToPane(text, content); setConverter(stringConverter); FXUtils.addClassTo(content, CssClasses.DEF_HBOX); FXUtils.addClassTo(this, CssClasses.ABSTRACT_NODE_TREE_CELL); } /** * Update hide status. */ @FxThread private void processHide(@NotNull final MouseEvent event) { event.consume(); if (event.getButton() != MouseButton.PRIMARY) { return; } final TreeNode<?> item = getItem(); if (!(item instanceof HideableNode)) return; final HideableNode<C> hideable = unsafeCast(item); if (hideable.isHided()) { hideable.show(getNodeTree()); } else { hideable.hide(getNodeTree()); } } @Override @FxThread public void startEdit() { if (!isEditable()) { return; } final TreeItem<TreeNode<?>> treeItem = getTreeItem(); if (treeItem != null) { treeItem.setGraphic(null); } setIgnoreUpdate(true); try { super.startEdit(); } finally { setIgnoreUpdate(false); } UiUtils.updateEditedCell(this); editing.setValue(true); } /** * @return true if need to ignore update. */ @FxThread private boolean isIgnoreUpdate() { return ignoreUpdate; } /** * @param ignoreUpdate the flag of ignoring updates. */ @FxThread private void setIgnoreUpdate(final boolean ignoreUpdate) { this.ignoreUpdate = ignoreUpdate; } @Override @FxThread public void cancelEdit() { super.cancelEdit(); editing.setValue(false); final TreeItem<TreeNode<?>> treeItem = getTreeItem(); if (treeItem != null) { treeItem.setGraphic(content); } setText(StringUtils.EMPTY); } @Override @FxThread public void commitEdit(@NotNull final TreeNode<?> newValue) { super.commitEdit(newValue); editing.setValue(false); final TreeItem<TreeNode<?>> treeItem = getTreeItem(); if (treeItem != null) { treeItem.setGraphic(content); } setText(StringUtils.EMPTY); } /** * Get the icon. * * @return the icon. */ @FxThread private @NotNull ImageView getIcon() { return icon; } @Override @FxThread public void updateItem(@Nullable final TreeNode<?> item, final boolean empty) { super.updateItem(item, empty); if (isIgnoreUpdate()) { return; } final ImageView icon = getIcon(); if (item == null) { final TreeItem<TreeNode<?>> treeItem = getTreeItem(); if (treeItem != null) treeItem.setGraphic(null); setText(StringUtils.EMPTY); setEditable(false); return; } icon.setImage(item.getIcon()); DynamicIconSupport.updateListener(this, icon, selectedProperty()); final TreeItem<TreeNode<?>> treeItem = getTreeItem(); if (treeItem != null) treeItem.setGraphic(content); HideableNode hideable = null; if (item instanceof HideableNode) { hideable = (HideableNode) item; } if (hideable != null) { visibleIcon.setVisible(true); visibleIcon.setManaged(true); visibleIcon.setImage(hideable.isHided() ? Icons.INVISIBLE_16 : Icons.VISIBLE_16); visibleIcon.setOpacity(hideable.isHided() ? 0.5D : 1D); DynamicIconSupport.updateListener2(this, visibleIcon, selectedProperty()); } else { visibleIcon.setVisible(false); visibleIcon.setManaged(false); } text.setText(item.getName()); setText(StringUtils.EMPTY); setEditable(item.canEditName()); } /** * Get the node tree. * * @return the node tree. */ @FxThread protected @NotNull M getNodeTree() { return nodeTree; } /** * Handle a mouse click. */ @FxThread private void processClick(@NotNull final MouseEvent event) { final TreeNode<?> item = getItem(); if (item == null) { return; } final MouseButton button = event.getButton(); if (button != MouseButton.SECONDARY) { return; } final M nodeTree = getNodeTree(); final ContextMenu contextMenu = nodeTree.getContextMenu(item); if (contextMenu == null) { return; } EXECUTOR_MANAGER.addFxTask(() -> contextMenu.show(this, Side.BOTTOM, 0, 0)); } /** * Handle stopping dragging. */ @FxThread private void stopDrag(@NotNull final DragEvent event) { dragged.setValue(false); setCursor(Cursor.DEFAULT); event.consume(); } /** * Handle starting dragging. */ @FxThread private void startDrag(@NotNull final MouseEvent mouseEvent) { final TreeNode<?> item = getItem(); if (item == null) { return; } final TreeView<TreeNode<?>> treeView = getTreeView(); final TreeItem<TreeNode<?>> treeItem = findItemForValue(treeView, item); if (treeView.getRoot() == treeItem) { return; } TransferMode transferMode = item.canMove() ? TransferMode.MOVE : null; transferMode = item.canCopy() && mouseEvent.isControlDown() ? TransferMode.COPY : transferMode; if (transferMode == null) { return; } final Dragboard dragBoard = startDragAndDrop(transferMode); final ClipboardContent content = new ClipboardContent(); content.put(DATA_FORMAT, item.getObjectId()); dragBoard.setContent(content); dragged.setValue(true); setCursor(Cursor.MOVE); mouseEvent.consume(); } /** * Handle dropping a dragged element. */ @FxThread private void dragDropped(@NotNull final DragEvent dragEvent) { final TreeNode<?> item = getItem(); if (item == null) { return; } final Dragboard dragboard = dragEvent.getDragboard(); final Long objectId = (Long) dragboard.getContent(DATA_FORMAT); final Set<TransferMode> transferModes = dragboard.getTransferModes(); final boolean isCopy = transferModes.contains(TransferMode.COPY); final M nodeTree = getNodeTree(); final ChangeConsumer changeConsumer = notNull(nodeTree.getChangeConsumer()); if (objectId != null) { final TreeView<TreeNode<?>> treeView = getTreeView(); final TreeItem<TreeNode<?>> dragTreeItem = findItem(treeView, objectId); final TreeNode<?> dragItem = dragTreeItem == null ? null : dragTreeItem.getValue(); if (dragItem == null || !item.canAccept(dragItem, isCopy)) { return; } final TreeItem<TreeNode<?>> newParentItem = findItemForValue(treeView, item); if (newParentItem == null) { return; } item.accept(changeConsumer, dragItem.getElement(), isCopy); } else if (item.canAcceptExternal(dragboard)) { item.acceptExternal(dragboard, changeConsumer); } dragEvent.consume(); } /** * Handle entering a dragged element. */ @FxThread private void dragOver(@NotNull final DragEvent dragEvent) { final TreeNode<?> item = getItem(); if (item == null) { return; } final Dragboard dragboard = dragEvent.getDragboard(); final Long objectId = (Long) dragboard.getContent(DATA_FORMAT); final Set<TransferMode> transferModes = dragboard.getTransferModes(); final boolean isCopy = transferModes.contains(TransferMode.COPY); if (objectId != null) { final TreeView<TreeNode<?>> treeView = getTreeView(); final TreeItem<TreeNode<?>> dragTreeItem = findItem(treeView, objectId); final TreeNode<?> dragItem = dragTreeItem == null ? null : dragTreeItem.getValue(); if (dragItem == null || !item.canAccept(dragItem, isCopy)) return; } else if (!item.canAcceptExternal(dragboard)) { return; } dragEvent.acceptTransferModes(isCopy ? TransferMode.COPY : TransferMode.MOVE); dragEvent.consume(); dropAvailable.setValue(true); } /** * Handle exiting a dragged element. */ @FxThread private void dragExited(@NotNull final DragEvent dragEvent) { dropAvailable.setValue(false); } }
JavaSaBr/jME3-SpaceShift-Editor
src/main/java/com/ss/editor/ui/control/tree/NodeTreeCell.java
Java
apache-2.0
14,235
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* Primitive-type-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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 it.unimi.dsi.fastutil.objects; import it.unimi.dsi.fastutil.Hash; import it.unimi.dsi.fastutil.HashCommon; import it.unimi.dsi.fastutil.booleans.BooleanArrays; import static it.unimi.dsi.fastutil.HashCommon.arraySize; import static it.unimi.dsi.fastutil.HashCommon.maxFill; import java.util.Map; import java.util.NoSuchElementException; import it.unimi.dsi.fastutil.shorts.ShortCollection; import it.unimi.dsi.fastutil.shorts.AbstractShortCollection; import it.unimi.dsi.fastutil.shorts.ShortIterator; import it.unimi.dsi.fastutil.objects.ObjectArrays; import java.util.Comparator; import it.unimi.dsi.fastutil.shorts.ShortListIterator; import it.unimi.dsi.fastutil.objects.AbstractObjectSortedSet; import it.unimi.dsi.fastutil.objects.ObjectListIterator; import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; import it.unimi.dsi.fastutil.objects.ObjectSortedSet; /** A type-specific linked hash map with with a fast, small-footprint implementation. * * <P>Instances of this class use a hash table to represent a map. The table is * enlarged as needed by doubling its size when new entries are created, but it is <em>never</em> made * smaller (even on a {@link #clear()}). A family of {@linkplain #trim() trimming * methods} lets you control the size of the table; this is particularly useful * if you reuse instances of this class. * * <P>Iterators generated by this map will enumerate pairs in the same order in which they * have been added to the map (addition of pairs whose key is already present * in the set does not change the iteration order). Note that this order has nothing in common with the natural * order of the keys. The order is kept by means of a doubly linked list, represented * <i>via</i> an array of longs parallel to the table. * * <P>This class implements the interface of a sorted map, so to allow easy * access of the iteration order: for instance, you can get the first key * in iteration order with {@link #firstKey()} without having to create an * iterator; however, this class partially violates the {@link java.util.SortedMap} * contract because all submap methods throw an exception and {@link * #comparator()} returns always <code>null</code>. * * <p>Additional methods, such as <code>getAndMoveToFirst()</code>, make it easy * to use instances of this class as a cache (e.g., with LRU policy). * * <P>The iterators provided by the views of this class using are type-specific * {@linkplain java.util.ListIterator list iterators}, and can be started at any * element <em>which is a key of the map</em>, or * a {@link NoSuchElementException} exception will be thrown. * If, however, the provided element is not the first or last key in the * set, the first access to the list index will require linear time, as in the worst case * the entire key set must be scanned in iteration order to retrieve the positional * index of the starting key. If you use just the methods of a type-specific {@link it.unimi.dsi.fastutil.BidirectionalIterator}, * however, all operations will be performed in constant time. * * @see Hash * @see HashCommon */ public class Object2ShortLinkedOpenCustomHashMap <K> extends AbstractObject2ShortSortedMap <K> implements java.io.Serializable, Cloneable, Hash { private static final long serialVersionUID = 0L; private static final boolean ASSERTS = false; /** The array of keys. */ protected transient K key[]; /** The array of values. */ protected transient short value[]; /** The array telling whether a position is used. */ protected transient boolean used[]; /** The acceptable load factor. */ protected final float f; /** The current table size. */ protected transient int n; /** Threshold after which we rehash. It must be the table size times {@link #f}. */ protected transient int maxFill; /** The mask for wrapping a position counter. */ protected transient int mask; /** Number of entries in the set. */ protected int size; /** Cached set of entries. */ protected transient volatile FastSortedEntrySet <K> entries; /** Cached set of keys. */ protected transient volatile ObjectSortedSet <K> keys; /** Cached collection of values. */ protected transient volatile ShortCollection values; /** The index of the first entry in iteration order. It is valid iff {@link #size} is nonzero; otherwise, it contains -1. */ protected transient int first = -1; /** The index of the last entry in iteration order. It is valid iff {@link #size} is nonzero; otherwise, it contains -1. */ protected transient int last = -1; /** For each entry, the next and the previous entry in iteration order, * stored as <code>((prev & 0xFFFFFFFFL) << 32) | (next & 0xFFFFFFFFL)</code>. * The first entry contains predecessor -1, and the last entry * contains successor -1. */ protected transient long link[]; /* Macros for transforming the bi-directional long link. Return values are 32-bit int indexes. * SET_UPPER and SET_LOWER do a masked assignment as described at * http://www-graphics.stanford.edu/~seander/bithacks.html#MaskedMerge */ /** The hash strategy of this custom map. */ protected Strategy <K> strategy; /** Creates a new hash map. * * <p>The actual table size will be the least power of two greater than <code>expected</code>/<code>f</code>. * * @param expected the expected number of elements in the hash set. * @param f the load factor. * @param strategy the strategy. */ @SuppressWarnings("unchecked") public Object2ShortLinkedOpenCustomHashMap( final int expected, final float f, final Strategy <K> strategy ) { this.strategy = strategy; if ( f <= 0 || f > 1 ) throw new IllegalArgumentException( "Load factor must be greater than 0 and smaller than or equal to 1" ); if ( expected < 0 ) throw new IllegalArgumentException( "The expected number of elements must be nonnegative" ); this.f = f; n = arraySize( expected, f ); mask = n - 1; maxFill = maxFill( n, f ); key = (K[]) new Object[ n ]; value = new short[ n ]; used = new boolean[ n ]; link = new long[ n ]; } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. * * @param expected the expected number of elements in the hash map. * @param strategy the strategy. */ public Object2ShortLinkedOpenCustomHashMap( final int expected, final Strategy <K> strategy ) { this( expected, DEFAULT_LOAD_FACTOR, strategy ); } /** Creates a new hash map with initial expected {@link Hash#DEFAULT_INITIAL_SIZE} entries * and {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. * @param strategy the strategy. */ public Object2ShortLinkedOpenCustomHashMap( final Strategy <K> strategy ) { this( DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy ); } /** Creates a new hash map copying a given one. * * @param m a {@link Map} to be copied into the new hash map. * @param f the load factor. * @param strategy the strategy. */ public Object2ShortLinkedOpenCustomHashMap( final Map<? extends K, ? extends Short> m, final float f, final Strategy <K> strategy ) { this( m.size(), f, strategy ); putAll( m ); } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given one. * * @param m a {@link Map} to be copied into the new hash map. * @param strategy the strategy. */ public Object2ShortLinkedOpenCustomHashMap( final Map<? extends K, ? extends Short> m, final Strategy <K> strategy ) { this( m, DEFAULT_LOAD_FACTOR, strategy ); } /** Creates a new hash map copying a given type-specific one. * * @param m a type-specific map to be copied into the new hash map. * @param f the load factor. * @param strategy the strategy. */ public Object2ShortLinkedOpenCustomHashMap( final Object2ShortMap <K> m, final float f, final Strategy <K> strategy ) { this( m.size(), f, strategy ); putAll( m ); } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given type-specific one. * * @param m a type-specific map to be copied into the new hash map. * @param strategy the strategy. */ public Object2ShortLinkedOpenCustomHashMap( final Object2ShortMap <K> m, final Strategy <K> strategy ) { this( m, DEFAULT_LOAD_FACTOR, strategy ); } /** Creates a new hash map using the elements of two parallel arrays. * * @param k the array of keys of the new hash map. * @param v the array of corresponding values in the new hash map. * @param f the load factor. * @param strategy the strategy. * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths. */ public Object2ShortLinkedOpenCustomHashMap( final K[] k, final short v[], final float f, final Strategy <K> strategy ) { this( k.length, f, strategy ); if ( k.length != v.length ) throw new IllegalArgumentException( "The key array and the value array have different lengths (" + k.length + " and " + v.length + ")" ); for( int i = 0; i < k.length; i++ ) this.put( k[ i ], v[ i ] ); } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor using the elements of two parallel arrays. * * @param k the array of keys of the new hash map. * @param v the array of corresponding values in the new hash map. * @param strategy the strategy. * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths. */ public Object2ShortLinkedOpenCustomHashMap( final K[] k, final short v[], final Strategy <K> strategy ) { this( k, v, DEFAULT_LOAD_FACTOR, strategy ); } /** Returns the hashing strategy. * * @return the hashing strategy of this custom hash map. */ public Strategy <K> strategy() { return strategy; } /* * The following methods implements some basic building blocks used by * all accessors. They are (and should be maintained) identical to those used in OpenHashSet.drv. */ public short put(final K k, final short v) { // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) { final short oldValue = value[ pos ]; value[ pos ] = v; return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } public Short put( final K ok, final Short ov ) { final short v = ((ov).shortValue()); final K k = (ok); // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) { final Short oldValue = (Short.valueOf(value[ pos ])); value[ pos ] = v; return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) ); if ( ASSERTS ) checkTable(); return (null); } /** Adds an increment to value currently associated with a key. * * @param k the key. * @param incr the increment. * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. * @deprecated use <code>addTo()</code> instead; having the same name of a {@link java.util.Set} method turned out to be a recipe for disaster. */ @Deprecated public short add(final K k, final short incr) { return addTo( k, incr ); } /** Adds an increment to value currently associated with a key. * * <P>Note that this method respects the {@linkplain #defaultReturnValue() default return value} semantics: when * called with a key that does not currently appears in the map, the key * will be associated with the default return value plus * the given increment. * * @param k the key. * @param incr the increment. * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public short addTo(final K k, final short incr) { // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) { final short oldValue = value[ pos ]; value[ pos ] += incr; return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = (short)(defRetValue + incr); if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } /** Shifts left entries with the specified hash code, starting at the specified position, * and empties the resulting free entry. * * @param pos a starting position. * @return the position cleared by the shifting process. */ protected final int shiftKeys( int pos ) { // Shift entries with the same hash. int last, slot; for(;;) { pos = ( ( last = pos ) + 1 ) & mask; while( used[ pos ] ) { slot = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (key[ pos ])) ) ) & mask; if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break; pos = ( pos + 1 ) & mask; } if ( ! used[ pos ] ) break; key[ last ] = key[ pos ]; value[ last ] = value[ pos ]; fixPointers( pos, last ); } used[ last ] = false; key[ last ] = null; return last; } @SuppressWarnings("unchecked") public short removeShort( final Object k ) { // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) { size--; fixPointers( pos ); final short v = value[ pos ]; shiftKeys( pos ); return v; } pos = ( pos + 1 ) & mask; } return defRetValue; } @SuppressWarnings("unchecked") public Short remove( final Object ok ) { final K k = (K) (ok); // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) { size--; fixPointers( pos ); final short v = value[ pos ]; shiftKeys( pos ); return (Short.valueOf(v)); } pos = ( pos + 1 ) & mask; } return (null); } /** Removes the mapping associated with the first key in iteration order. * @return the value previously associated with the first key in iteration order. * @throws NoSuchElementException is this map is empty. */ public short removeFirstShort() { if ( size == 0 ) throw new NoSuchElementException(); --size; final int pos = first; // Abbreviated version of fixPointers(pos) first = (int) link[ pos ]; if ( 0 <= first ) { // Special case of SET_PREV( link[ first ], -1 ) link[ first ] |= (-1 & 0xFFFFFFFFL) << 32; } final short v = value[ pos ]; shiftKeys( pos ); return v; } /** Removes the mapping associated with the last key in iteration order. * @return the value previously associated with the last key in iteration order. * @throws NoSuchElementException is this map is empty. */ public short removeLastShort() { if ( size == 0 ) throw new NoSuchElementException(); --size; final int pos = last; // Abbreviated version of fixPointers(pos) last = (int) ( link[ pos ] >>> 32 ); if ( 0 <= last ) { // Special case of SET_NEXT( link[ last ], -1 ) link[ last ] |= -1 & 0xFFFFFFFFL; } final short v = value[ pos ]; shiftKeys( pos ); return v; } private void moveIndexToFirst( final int i ) { if ( size == 1 || first == i ) return; if ( last == i ) { last = (int) ( link[ i ] >>> 32 ); // Special case of SET_NEXT( link[ last ], -1 ); link[ last ] |= -1 & 0xFFFFFFFFL; } else { final long linki = link[ i ]; final int prev = (int) ( linki >>> 32 ); final int next = (int) linki; link[ prev ] ^= ( ( link[ prev ] ^ ( linki & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( linki & 0xFFFFFFFF00000000L ) ) & 0xFFFFFFFF00000000L ); } link[ first ] ^= ( ( link[ first ] ^ ( ( i & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ i ] = ( ( -1 & 0xFFFFFFFFL ) << 32 ) | ( first & 0xFFFFFFFFL ); first = i; } private void moveIndexToLast( final int i ) { if ( size == 1 || last == i ) return; if ( first == i ) { first = (int) link[ i ]; // Special case of SET_PREV( link[ first ], -1 ); link[ first ] |= (-1 & 0xFFFFFFFFL) << 32; } else { final long linki = link[ i ]; final int prev = (int) ( linki >>> 32 ); final int next = (int) linki; link[ prev ] ^= ( ( link[ prev ] ^ ( linki & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( linki & 0xFFFFFFFF00000000L ) ) & 0xFFFFFFFF00000000L ); } link[ last ] ^= ( ( link[ last ] ^ ( i & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ i ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = i; } /** Returns the value to which the given key is mapped; if the key is present, it is moved to the first position of the iteration order. * * @param k the key. * @return the corresponding value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public short getAndMoveToFirst( final K k ) { final K key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if( ( strategy.equals( (k), (K) (key[ pos ]) ) ) ) { moveIndexToFirst( pos ); return value[ pos ]; } pos = ( pos + 1 ) & mask; } return defRetValue; } /** Returns the value to which the given key is mapped; if the key is present, it is moved to the last position of the iteration order. * * @param k the key. * @return the corresponding value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public short getAndMoveToLast( final K k ) { final K key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if( ( strategy.equals( (k), (K) (key[ pos ]) ) ) ) { moveIndexToLast( pos ); return value[ pos ]; } pos = ( pos + 1 ) & mask; } return defRetValue; } /** Adds a pair to the map; if the key is already present, it is moved to the first position of the iteration order. * * @param k the key. * @param v the value. * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public short putAndMoveToFirst( final K k, final short v ) { final K key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (k), (K) (key[ pos ]) ) ) ) { final short oldValue = value[ pos ]; value[ pos ] = v; moveIndexToFirst( pos ); return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ first ] ^= ( ( link[ first ] ^ ( ( pos & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ pos ] = ( ( -1 & 0xFFFFFFFFL ) << 32 ) | ( first & 0xFFFFFFFFL ); first = pos; } if ( ++size >= maxFill ) rehash( arraySize( size, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } /** Adds a pair to the map; if the key is already present, it is moved to the last position of the iteration order. * * @param k the key. * @param v the value. * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public short putAndMoveToLast( final K k, final short v ) { final K key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (k), (K) (key[ pos ]) ) ) ) { final short oldValue = value[ pos ]; value[ pos ] = v; moveIndexToLast( pos ); return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } @SuppressWarnings("unchecked") public short getShort( final Object k ) { // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) return value[ pos ]; pos = ( pos + 1 ) & mask; } return defRetValue; } @SuppressWarnings("unchecked") public boolean containsKey( final Object k ) { // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) return true; pos = ( pos + 1 ) & mask; } return false; } public boolean containsValue( final short v ) { final short value[] = this.value; final boolean used[] = this.used; for( int i = n; i-- != 0; ) if ( used[ i ] && ( (value[ i ]) == (v) ) ) return true; return false; } /* Removes all elements from this map. * * <P>To increase object reuse, this method does not change the table size. * If you want to reduce the table size, you must use {@link #trim()}. * */ public void clear() { if ( size == 0 ) return; size = 0; BooleanArrays.fill( used, false ); // We null all object entries so that the garbage collector can do its work. ObjectArrays.fill( key, null ); first = last = -1; } public int size() { return size; } public boolean isEmpty() { return size == 0; } /** A no-op for backward compatibility. * * @param growthFactor unused. * @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full. */ @Deprecated public void growthFactor( int growthFactor ) {} /** Gets the growth factor (2). * * @return the growth factor of this set, which is fixed (2). * @see #growthFactor(int) * @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full. */ @Deprecated public int growthFactor() { return 16; } /** The entry class for a hash map does not record key and value, but * rather the position in the hash table of the corresponding entry. This * is necessary so that calls to {@link java.util.Map.Entry#setValue(Object)} are reflected in * the map */ private final class MapEntry implements Object2ShortMap.Entry <K>, Map.Entry<K, Short> { // The table index this entry refers to, or -1 if this entry has been deleted. private int index; MapEntry( final int index ) { this.index = index; } public K getKey() { return (key[ index ]); } public Short getValue() { return (Short.valueOf(value[ index ])); } public short getShortValue() { return value[ index ]; } public short setValue( final short v ) { final short oldValue = value[ index ]; value[ index ] = v; return oldValue; } public Short setValue( final Short v ) { return (Short.valueOf(setValue( ((v).shortValue()) ))); } @SuppressWarnings("unchecked") public boolean equals( final Object o ) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K, Short> e = (Map.Entry<K, Short>)o; return ( strategy.equals( (key[ index ]), (K) ((e.getKey())) ) ) && ( (value[ index ]) == (((e.getValue()).shortValue())) ); } public int hashCode() { return ( strategy.hashCode( (K) (key[ index ])) ) ^ (value[ index ]); } public String toString() { return key[ index ] + "=>" + value[ index ]; } } /** Modifies the {@link #link} vector so that the given entry is removed. * * <P>If the given entry is the first or the last one, this method will complete * in constant time; otherwise, it will have to search for the given entry. * * @param i the index of an entry. */ protected void fixPointers( final int i ) { if ( size == 0 ) { first = last = -1; return; } if ( first == i ) { first = (int) link[ i ]; if (0 <= first) { // Special case of SET_PREV( link[ first ], -1 ) link[ first ] |= (-1 & 0xFFFFFFFFL) << 32; } return; } if ( last == i ) { last = (int) ( link[ i ] >>> 32 ); if (0 <= last) { // Special case of SET_NEXT( link[ last ], -1 ) link[ last ] |= -1 & 0xFFFFFFFFL; } return; } final long linki = link[ i ]; final int prev = (int) ( linki >>> 32 ); final int next = (int) linki; link[ prev ] ^= ( ( link[ prev ] ^ ( linki & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( linki & 0xFFFFFFFF00000000L ) ) & 0xFFFFFFFF00000000L ); } /** Modifies the {@link #link} vector for a shift from s to d. * * <P>If the given entry is the first or the last one, this method will complete * in constant time; otherwise, it will have to search for the given entry. * * @param s the source position. * @param d the destination position. */ protected void fixPointers( int s, int d ) { if ( size == 1 ) { first = last = d; // Special case of SET_UPPER_LOWER( link[ d ], -1, -1 ) link[ d ] = -1L; return; } if ( first == s ) { first = d; link[ (int) link[ s ] ] ^= ( ( link[ (int) link[ s ] ] ^ ( ( d & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ d ] = link[ s ]; return; } if ( last == s ) { last = d; link[ (int) ( link[ s ] >>> 32 )] ^= ( ( link[ (int) ( link[ s ] >>> 32 )] ^ ( d & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ d ] = link[ s ]; return; } final long links = link[ s ]; final int prev = (int) ( links >>> 32 ); final int next = (int) links; link[ prev ] ^= ( ( link[ prev ] ^ ( d & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( ( d & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ d ] = links; } /** Returns the first key of this map in iteration order. * * @return the first key in iteration order. */ public K firstKey() { if ( size == 0 ) throw new NoSuchElementException(); return key[ first ]; } /** Returns the last key of this map in iteration order. * * @return the last key in iteration order. */ public K lastKey() { if ( size == 0 ) throw new NoSuchElementException(); return key[ last ]; } public Comparator <? super K> comparator() { return null; } public Object2ShortSortedMap <K> tailMap( K from ) { throw new UnsupportedOperationException(); } public Object2ShortSortedMap <K> headMap( K to ) { throw new UnsupportedOperationException(); } public Object2ShortSortedMap <K> subMap( K from, K to ) { throw new UnsupportedOperationException(); } /** A list iterator over a linked map. * * <P>This class provides a list iterator over a linked hash map. The empty constructor runs in * constant time. The one-argument constructor needs to search for the given key, but it is * optimized for the case of {@link java.util.SortedMap#lastKey()}, in which case runs in constant time, too. */ private class MapIterator { /** The entry that will be returned by the next call to {@link java.util.ListIterator#previous()} (or <code>null</code> if no previous entry exists). */ int prev = -1; /** The entry that will be returned by the next call to {@link java.util.ListIterator#next()} (or <code>null</code> if no next entry exists). */ int next = -1; /** The last entry that was returned (or -1 if we did not iterate or used {@link java.util.Iterator#remove()}). */ int curr = -1; /** The current index (in the sense of a {@link java.util.ListIterator}). Note that this value is not meaningful when this iterator has been created using the nonempty constructor.*/ int index = -1; private MapIterator() { next = first; index = 0; } private MapIterator( final K from ) { if ( ( strategy.equals( (key[ last ]), (K) (from) ) ) ) { prev = last; index = size; } else { // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (from)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (from) ) ) ) { // Note: no valid index known. next = (int) link[ pos ]; prev = pos; return; } pos = ( pos + 1 ) & mask; } throw new NoSuchElementException( "The key " + from + " does not belong to this map." ); } } public boolean hasNext() { return next != -1; } public boolean hasPrevious() { return prev != -1; } private final void ensureIndexKnown() { if ( index >= 0 ) return; if ( prev == -1 ) { index = 0; return; } if ( next == -1 ) { index = size; return; } int pos = first; index = 1; while( pos != prev ) { pos = (int) link[ pos ]; index++; } } public int nextIndex() { ensureIndexKnown(); return index; } public int previousIndex() { ensureIndexKnown(); return index - 1; } public int nextEntry() { if ( ! hasNext() ) return size(); curr = next; next = (int) link[ curr ]; prev = curr; if ( index >= 0 ) index++; return curr; } public int previousEntry() { if ( ! hasPrevious() ) return -1; curr = prev; prev = (int) ( link[ curr ] >>> 32 ); next = curr; if ( index >= 0 ) index--; return curr; } @SuppressWarnings("unchecked") public void remove() { ensureIndexKnown(); if ( curr == -1 ) throw new IllegalStateException(); if ( curr == prev ) { /* If the last operation was a next(), we are removing an entry that preceeds the current index, and thus we must decrement it. */ index--; prev = (int) ( link[ curr ] >>> 32 ); } else next = (int) link[ curr ]; size--; /* Now we manually fix the pointers. Because of our knowledge of next and prev, this is going to be faster than calling fixPointers(). */ if ( prev == -1 ) first = next; else link[ prev ] ^= ( ( link[ prev ] ^ ( next & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); if ( next == -1 ) last = prev; else link[ next ] ^= ( ( link[ next ] ^ ( ( prev & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); int last, slot, pos = curr; // We have to horribly duplicate the shiftKeys() code because we need to update next/prev. for(;;) { pos = ( ( last = pos ) + 1 ) & mask; while( used[ pos ] ) { slot = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (key[ pos ])) ) ) & mask; if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break; pos = ( pos + 1 ) & mask; } if ( ! used[ pos ] ) break; key[ last ] = key[ pos ]; value[ last ] = value[ pos ]; if ( next == pos ) next = last; if ( prev == pos ) prev = last; fixPointers( pos, last ); } used[ last ] = false; key[ last ] = null; curr = -1; } public int skip( final int n ) { int i = n; while( i-- != 0 && hasNext() ) nextEntry(); return n - i - 1; } public int back( final int n ) { int i = n; while( i-- != 0 && hasPrevious() ) previousEntry(); return n - i - 1; } } private class EntryIterator extends MapIterator implements ObjectListIterator<Object2ShortMap.Entry <K> > { private MapEntry entry; public EntryIterator() {} public EntryIterator( K from ) { super( from ); } public MapEntry next() { return entry = new MapEntry( nextEntry() ); } public MapEntry previous() { return entry = new MapEntry( previousEntry() ); } @Override public void remove() { super.remove(); entry.index = -1; // You cannot use a deleted entry. } public void set( Object2ShortMap.Entry <K> ok ) { throw new UnsupportedOperationException(); } public void add( Object2ShortMap.Entry <K> ok ) { throw new UnsupportedOperationException(); } } private class FastEntryIterator extends MapIterator implements ObjectListIterator<Object2ShortMap.Entry <K> > { final BasicEntry <K> entry = new BasicEntry <K> ( (null), ((short)0) ); public FastEntryIterator() {} public FastEntryIterator( K from ) { super( from ); } public BasicEntry <K> next() { final int e = nextEntry(); entry.key = key[ e ]; entry.value = value[ e ]; return entry; } public BasicEntry <K> previous() { final int e = previousEntry(); entry.key = key[ e ]; entry.value = value[ e ]; return entry; } public void set( Object2ShortMap.Entry <K> ok ) { throw new UnsupportedOperationException(); } public void add( Object2ShortMap.Entry <K> ok ) { throw new UnsupportedOperationException(); } } private final class MapEntrySet extends AbstractObjectSortedSet<Object2ShortMap.Entry <K> > implements FastSortedEntrySet <K> { public ObjectBidirectionalIterator<Object2ShortMap.Entry <K> > iterator() { return new EntryIterator(); } public Comparator<? super Object2ShortMap.Entry <K> > comparator() { return null; } public ObjectSortedSet<Object2ShortMap.Entry <K> > subSet( Object2ShortMap.Entry <K> fromElement, Object2ShortMap.Entry <K> toElement) { throw new UnsupportedOperationException(); } public ObjectSortedSet<Object2ShortMap.Entry <K> > headSet( Object2ShortMap.Entry <K> toElement ) { throw new UnsupportedOperationException(); } public ObjectSortedSet<Object2ShortMap.Entry <K> > tailSet( Object2ShortMap.Entry <K> fromElement ) { throw new UnsupportedOperationException(); } public Object2ShortMap.Entry <K> first() { if ( size == 0 ) throw new NoSuchElementException(); return new MapEntry( Object2ShortLinkedOpenCustomHashMap.this.first ); } public Object2ShortMap.Entry <K> last() { if ( size == 0 ) throw new NoSuchElementException(); return new MapEntry( Object2ShortLinkedOpenCustomHashMap.this.last ); } @SuppressWarnings("unchecked") public boolean contains( final Object o ) { if ( !( o instanceof Map.Entry ) ) return false; final Map.Entry<K, Short> e = (Map.Entry<K, Short>)o; final K k = (e.getKey()); // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) return ( (value[ pos ]) == (((e.getValue()).shortValue())) ); pos = ( pos + 1 ) & mask; } return false; } @SuppressWarnings("unchecked") public boolean remove( final Object o ) { if ( !( o instanceof Map.Entry ) ) return false; final Map.Entry<K, Short> e = (Map.Entry<K, Short>)o; final K k = (e.getKey()); // The starting point. int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( strategy.equals( (key[ pos ]), (K) (k) ) ) ) { Object2ShortLinkedOpenCustomHashMap.this.remove( e.getKey() ); return true; } pos = ( pos + 1 ) & mask; } return false; } public int size() { return size; } public void clear() { Object2ShortLinkedOpenCustomHashMap.this.clear(); } public ObjectBidirectionalIterator<Object2ShortMap.Entry <K> > iterator( final Object2ShortMap.Entry <K> from ) { return new EntryIterator( (from.getKey()) ); } public ObjectBidirectionalIterator<Object2ShortMap.Entry <K> > fastIterator() { return new FastEntryIterator(); } public ObjectBidirectionalIterator<Object2ShortMap.Entry <K> > fastIterator( final Object2ShortMap.Entry <K> from ) { return new FastEntryIterator( (from.getKey()) ); } } public FastSortedEntrySet <K> object2ShortEntrySet() { if ( entries == null ) entries = new MapEntrySet(); return entries; } /** An iterator on keys. * * <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods * (and possibly their type-specific counterparts) so that they return keys * instead of entries. */ private final class KeyIterator extends MapIterator implements ObjectListIterator <K> { public KeyIterator( final K k ) { super( k ); } public K previous() { return key[ previousEntry() ]; } public void set( K k ) { throw new UnsupportedOperationException(); } public void add( K k ) { throw new UnsupportedOperationException(); } public KeyIterator() { super(); } public K next() { return key[ nextEntry() ]; } } private final class KeySet extends AbstractObjectSortedSet <K> { public ObjectListIterator <K> iterator( final K from ) { return new KeyIterator( from ); } public ObjectListIterator <K> iterator() { return new KeyIterator(); } public int size() { return size; } public boolean contains( Object k ) { return containsKey( k ); } public boolean remove( Object k ) { final int oldSize = size; Object2ShortLinkedOpenCustomHashMap.this.remove( k ); return size != oldSize; } public void clear() { Object2ShortLinkedOpenCustomHashMap.this.clear(); } public K first() { if ( size == 0 ) throw new NoSuchElementException(); return key[ first ]; } public K last() { if ( size == 0 ) throw new NoSuchElementException(); return key[ last ]; } public Comparator <? super K> comparator() { return null; } final public ObjectSortedSet <K> tailSet( K from ) { throw new UnsupportedOperationException(); } final public ObjectSortedSet <K> headSet( K to ) { throw new UnsupportedOperationException(); } final public ObjectSortedSet <K> subSet( K from, K to ) { throw new UnsupportedOperationException(); } } public ObjectSortedSet <K> keySet() { if ( keys == null ) keys = new KeySet(); return keys; } /** An iterator on values. * * <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods * (and possibly their type-specific counterparts) so that they return values * instead of entries. */ private final class ValueIterator extends MapIterator implements ShortListIterator { public short previousShort() { return value[ previousEntry() ]; } public Short previous() { return (Short.valueOf(value[ previousEntry() ])); } public void set( Short ok ) { throw new UnsupportedOperationException(); } public void add( Short ok ) { throw new UnsupportedOperationException(); } public void set( short v ) { throw new UnsupportedOperationException(); } public void add( short v ) { throw new UnsupportedOperationException(); } public ValueIterator() { super(); } public short nextShort() { return value[ nextEntry() ]; } public Short next() { return (Short.valueOf(value[ nextEntry() ])); } } public ShortCollection values() { if ( values == null ) values = new AbstractShortCollection () { public ShortIterator iterator() { return new ValueIterator(); } public int size() { return size; } public boolean contains( short v ) { return containsValue( v ); } public void clear() { Object2ShortLinkedOpenCustomHashMap.this.clear(); } }; return values; } /** A no-op for backward compatibility. The kind of tables implemented by * this class never need rehashing. * * <P>If you need to reduce the table size to fit exactly * this set, use {@link #trim()}. * * @return true. * @see #trim() * @deprecated A no-op. */ @Deprecated public boolean rehash() { return true; } /** Rehashes the map, making the table as small as possible. * * <P>This method rehashes the table to the smallest size satisfying the * load factor. It can be used when the set will not be changed anymore, so * to optimize access speed and size. * * <P>If the table size is already the minimum possible, this method * does nothing. * * @return true if there was enough memory to trim the map. * @see #trim(int) */ public boolean trim() { final int l = arraySize( size, f ); if ( l >= n ) return true; try { rehash( l ); } catch(OutOfMemoryError cantDoIt) { return false; } return true; } /** Rehashes this map if the table is too large. * * <P>Let <var>N</var> be the smallest table size that can hold * <code>max(n,{@link #size()})</code> entries, still satisfying the load factor. If the current * table size is smaller than or equal to <var>N</var>, this method does * nothing. Otherwise, it rehashes this map in a table of size * <var>N</var>. * * <P>This method is useful when reusing maps. {@linkplain #clear() Clearing a * map} leaves the table size untouched. If you are reusing a map * many times, you can call this method with a typical * size to avoid keeping around a very large table just * because of a few large transient maps. * * @param n the threshold for the trimming. * @return true if there was enough memory to trim the map. * @see #trim() */ public boolean trim( final int n ) { final int l = HashCommon.nextPowerOfTwo( (int)Math.ceil( n / f ) ); if ( this.n <= l ) return true; try { rehash( l ); } catch( OutOfMemoryError cantDoIt ) { return false; } return true; } /** Resizes the map. * * <P>This method implements the basic rehashing strategy, and may be * overriden by subclasses implementing different rehashing strategies (e.g., * disk-based rehashing). However, you should not override this method * unless you understand the internal workings of this class. * * @param newN the new size */ @SuppressWarnings("unchecked") protected void rehash( final int newN ) { int i = first, prev = -1, newPrev = -1, t, pos; K k; final K key[] = this.key; final short value[] = this.value; final int newMask = newN - 1; final K newKey[] = (K[]) new Object[ newN ]; final short newValue[] = new short[newN]; final boolean newUsed[] = new boolean[ newN ]; final long link[] = this.link; final long newLink[] = new long[ newN ]; first = -1; for( int j = size; j-- != 0; ) { k = key[ i ]; pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & newMask; while ( newUsed[ pos ] ) pos = ( pos + 1 ) & newMask; newUsed[ pos ] = true; newKey[ pos ] = k; newValue[ pos ] = value[ i ]; if ( prev != -1 ) { newLink[ newPrev ] ^= ( ( newLink[ newPrev ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); newLink[ pos ] ^= ( ( newLink[ pos ] ^ ( ( newPrev & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); newPrev = pos; } else { newPrev = first = pos; // Special case of SET(newLink[ pos ], -1, -1); newLink[ pos ] = -1L; } t = i; i = (int) link[ i ]; prev = t; } n = newN; mask = newMask; maxFill = maxFill( n, f ); this.key = newKey; this.value = newValue; this.used = newUsed; this.link = newLink; this.last = newPrev; if ( newPrev != -1 ) // Special case of SET_NEXT( newLink[ newPrev ], -1 ); newLink[ newPrev ] |= -1 & 0xFFFFFFFFL; } /** Returns a deep copy of this map. * * <P>This method performs a deep copy of this hash map; the data stored in the * map, however, is not cloned. Note that this makes a difference only for object keys. * * @return a deep copy of this map. */ @SuppressWarnings("unchecked") public Object2ShortLinkedOpenCustomHashMap <K> clone() { Object2ShortLinkedOpenCustomHashMap <K> c; try { c = (Object2ShortLinkedOpenCustomHashMap <K>)super.clone(); } catch(CloneNotSupportedException cantHappen) { throw new InternalError(); } c.keys = null; c.values = null; c.entries = null; c.key = key.clone(); c.value = value.clone(); c.used = used.clone(); c.link = link.clone(); c.strategy = strategy; return c; } /** Returns a hash code for this map. * * This method overrides the generic method provided by the superclass. * Since <code>equals()</code> is not overriden, it is important * that the value returned by this method is the same value as * the one returned by the overriden method. * * @return a hash code for this map. */ public int hashCode() { int h = 0; for( int j = size, i = 0, t = 0; j-- != 0; ) { while( ! used[ i ] ) i++; if ( this != key[ i ] ) t = ( strategy.hashCode( (K) (key[ i ])) ); t ^= (value[ i ]); h += t; i++; } return h; } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { final K key[] = this.key; final short value[] = this.value; final MapIterator i = new MapIterator(); s.defaultWriteObject(); for( int j = size, e; j-- != 0; ) { e = i.nextEntry(); s.writeObject( key[ e ] ); s.writeShort( value[ e ] ); } } @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); n = arraySize( size, f ); maxFill = maxFill( n, f ); mask = n - 1; final K key[] = this.key = (K[]) new Object[ n ]; final short value[] = this.value = new short[ n ]; final boolean used[] = this.used = new boolean[ n ]; final long link[] = this.link = new long[ n ]; int prev = -1; first = last = -1; K k; short v; for( int i = size, pos = 0; i-- != 0; ) { k = (K) s.readObject(); v = s.readShort(); pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( (K) (k)) ) ) & mask; while ( used[ pos ] ) pos = ( pos + 1 ) & mask; used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( first != -1 ) { link[ prev ] ^= ( ( link[ prev ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] ^= ( ( link[ pos ] ^ ( ( prev & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); prev = pos; } else { prev = first = pos; // Special case of SET_PREV( newLink[ pos ], -1 ); link[ pos ] |= (-1L & 0xFFFFFFFFL) << 32; } } last = prev; if ( prev != -1 ) // Special case of SET_NEXT( link[ prev ], -1 ); link[ prev ] |= -1 & 0xFFFFFFFFL; if ( ASSERTS ) checkTable(); } private void checkTable() {} }
karussell/fastutil
src/it/unimi/dsi/fastutil/objects/Object2ShortLinkedOpenCustomHashMap.java
Java
apache-2.0
49,769
import json from django.http import JsonResponse from .lib.scheduler import sch from .lib.sun import * from .lib.context import Context from .lib.execution_element import ExecutionElement def get_data(): return { 'ExecutionElements': json.loads(str(sch.context)), 'Now': Sun.Now().strftime('%H:%M:%S'), 'IsDay': sch.IsDay, 'Dawn': Sun.Dawn().strftime('%H:%M:%S'), 'Sunrise': Sun.Sunrise().strftime('%H:%M:%S'), 'Noon': Sun.Noon().strftime('%H:%M:%S'), 'Sunset': Sun.Sunset().strftime('%H:%M:%S'), 'Dusk' : Sun.Dusk().strftime('%H:%M:%S') } def status(request): return JsonResponse(get_data(), safe=False) def isday(request): return JsonResponse(sch.IsDay, safe=False) def set_execution_element(request, id, value): Id = int(id) if Id == 0: set_all_execution_elements(request, value) else: Value = int(value) sch.Context[Id].Overriden = True sch.Context[Id].OverridenValue = Value return JsonResponse(get_data(), safe=False) def set_execution_element_auto(request, id): Id = int(id) if Id == 0: set_all_execution_elements_auto(request) else: sch.Context[Id].Overriden = False return JsonResponse(get_data(), safe=False) def set_all_execution_elements(request, value): Value = int(value) for executionElement in sch.Context.ExecutionElements: executionElement.Overriden = True executionElement.OverridenValue = Value def set_all_execution_elements_auto(request): for executionElement in sch.Context.ExecutionElements: executionElement.Overriden = False
marians20/Aquarium
automation/ajax.py
Python
apache-2.0
1,657
package org.apereo.cas.web.flow.actions; import org.apereo.cas.web.flow.CasWebflowConstants; import org.apereo.cas.web.support.WebUtils; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; /** * Action that is responsible for determing if this MFA provider for the current subflow can * be bypassed for the user attempting to login into the service. * * @author Travis Schmidt * @since 5.3.4 */ @Slf4j public class MultifactorAuthenticationBypassAction extends AbstractMultifactorAuthenticationAction { @Override protected Event doExecute(final RequestContext requestContext) throws Exception { val authentication = WebUtils.getAuthentication(requestContext); val service = WebUtils.getRegisteredService(requestContext); val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(); val bypass = provider.getBypassEvaluator(); if (requestContext.getCurrentTransition().getId().equals(CasWebflowConstants.TRANSITION_ID_BYPASS)) { LOGGER.debug("Bypass triggered by MFA webflow for MFA for user [{}] for provider [{}]", authentication.getPrincipal().getId(), provider.getId()); bypass.updateAuthenticationToRememberBypass(authentication, provider); LOGGER.debug("Authentication updated to remember bypass for user [{}] for provider [{}]", authentication.getPrincipal().getId(), provider.getId()); return yes(); } if (bypass.shouldMultifactorAuthenticationProviderExecute(authentication, service, provider, request)) { LOGGER.debug("Bypass rules determined MFA should execute for user [{}] for provider [{}]", authentication.getPrincipal().getId(), provider.getId()); bypass.updateAuthenticationToForgetBypass(authentication); LOGGER.debug("Authentication updated to forget any existing bypass for user [{}] for provider [{}]", authentication.getPrincipal().getId(), provider.getId()); return no(); } LOGGER.debug("Bypass rules determined MFA should NOT execute for user [{}] for provider [{}]", authentication.getPrincipal().getId(), provider.getId()); bypass.updateAuthenticationToRememberBypass(authentication, provider); LOGGER.debug("Authentication updated to remember bypass for user [{}] for provider [{}]", authentication.getPrincipal().getId(), provider.getId()); return yes(); } }
frett/cas
core/cas-server-core-webflow-mfa-api/src/main/java/org/apereo/cas/web/flow/actions/MultifactorAuthenticationBypassAction.java
Java
apache-2.0
2,643
package org.usc.demo.webservices; import javax.xml.ws.Endpoint; public class Service { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/HelloService", new Hello()); } }
usc/demo
src/main/java/org/usc/demo/webservices/Service.java
Java
apache-2.0
226
package com.redkite.plantcare.common.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum NotificationType { USER_ACTIVATION("activate"), THRESHOLD_EXCEEDED("threshold"); private final String name; NotificationType(String name) { this.name = name; } @JsonValue @Override public String toString() { return name; } /** * Convert String into NotificationType. */ @JsonCreator public NotificationType fromString(String str) { for (NotificationType type : NotificationType.values()) { if (type.name.equals(str)) { return type; } } return null; } public String getName() { return name; } }
Kirill380/PlantCare
common/src/main/java/com/redkite/plantcare/common/dto/NotificationType.java
Java
apache-2.0
741
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.bbg.util; import java.util.HashSet; import java.util.Set; import org.threeten.bp.LocalDate; import org.threeten.bp.LocalDateTime; import org.threeten.bp.LocalTime; import org.threeten.bp.Month; import org.threeten.bp.ZoneOffset; import org.threeten.bp.ZonedDateTime; import com.google.common.collect.ImmutableSet; import com.opengamma.bbg.security.BloombergSecurityProvider; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.core.security.Security; import com.opengamma.financial.security.equity.EquitySecurity; import com.opengamma.financial.security.equity.GICSCode; import com.opengamma.financial.security.future.AgricultureFutureSecurity; import com.opengamma.financial.security.future.BondFutureDeliverable; import com.opengamma.financial.security.future.BondFutureSecurity; import com.opengamma.financial.security.future.EnergyFutureSecurity; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.financial.security.future.FXFutureSecurity; import com.opengamma.financial.security.future.InterestRateFutureSecurity; import com.opengamma.financial.security.future.MetalFutureSecurity; import com.opengamma.financial.security.option.AmericanExerciseType; import com.opengamma.financial.security.option.CommodityFutureOptionSecurity; import com.opengamma.financial.security.option.EquityIndexDividendFutureOptionSecurity; import com.opengamma.financial.security.option.EquityIndexFutureOptionSecurity; import com.opengamma.financial.security.option.EquityIndexOptionSecurity; import com.opengamma.financial.security.option.EquityOptionSecurity; import com.opengamma.financial.security.option.EuropeanExerciseType; import com.opengamma.financial.security.option.FxFutureOptionSecurity; import com.opengamma.financial.security.option.IRFutureOptionSecurity; import com.opengamma.financial.security.option.OptionType; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.util.money.Currency; import com.opengamma.util.time.DateUtils; import com.opengamma.util.time.Expiry; import com.opengamma.util.time.ExpiryAccuracy; /** * Bloomberg Security utility class to aid testing */ public final class BloombergSecurityUtils { /** * USD Currency */ public static final Currency USD = Currency.USD; /** * AUD Currency */ public static final Currency AUD = Currency.AUD; /** * EUR Currency */ public static final Currency EUR = Currency.EUR; /** * GBP Currency */ public static final Currency GBP = Currency.GBP; /** * ATT BUID */ public static final String ATT_BUID = "EQ0010137600001000"; /** * AAPL BUID */ public static final String AAPL_BUID = "EQ0010169500001000"; /** * AAPL OPTION */ public static final String APV_EQUITY_OPTION_TICKER = "APV US 01/16/10 C190 Equity"; // At times Bloomberg has changed this to SPT as the prefix in the past. /** * SPX index option */ public static final String SPX_INDEX_OPTION_TICKER = "SPX US 12/18/10 C1100 Index"; /** * AAPL ticker */ public static final String AAPL_EQUITY_TICKER = "AAPL US Equity"; /** * ATT ticker */ public static final String ATT_EQUITY_TICKER = "T US Equity"; private BloombergSecurityUtils() { } public static EquityFutureSecurity makeEquityFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 17, 21, 15), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final EquityFutureSecurity sec = new EquityFutureSecurity(expiry, "XCME", "XCME", USD, 250, ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 17, 21, 15), ZoneOffset.UTC), ExternalSchemes.bloombergTickerSecurityId("SPX Index"), "Equity"); sec.setName("S&P 500 FUTURE Jun10"); sec.setUnderlyingId(ExternalSchemes.bloombergTickerSecurityId("SPX Index")); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX6835907-0")); identifiers.add(ExternalSchemes.cusipSecurityId("SPM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("SPM10 Index")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); sec.setUniqueId(BloombergSecurityProvider.createUniqueId("IX6835907-0")); return sec; } public static AgricultureFutureSecurity makeAgricultureFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 23, 21, 30), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final AgricultureFutureSecurity sec = new AgricultureFutureSecurity(expiry, "XMTB", "XMTB", USD, 100, "Wheat"); sec.setName("WHEAT FUT (ING) Jun10"); sec.setUnitNumber(100.0); sec.setUnitName("tonnes"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX8114863-0")); identifiers.add(ExternalSchemes.cusipSecurityId("VKM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("VKM10 Comdty")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); sec.setUniqueId(BloombergSecurityProvider.createUniqueId("IX8114863-0")); return sec; } public static FXFutureSecurity makeAUDUSDCurrencyFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDate.of(2010, Month.JUNE, 1).atTime(LocalTime.MIDNIGHT), ZoneOffset.UTC), ExpiryAccuracy.DAY_MONTH_YEAR); final FXFutureSecurity security = new FXFutureSecurity(expiry, "XCME", "XCME", USD, 1000, AUD, USD, "FX"); security.setName("AUD/USD"); return security; } public static BondFutureSecurity makeEuroBundFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 8, 21, 0), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final Set<BondFutureDeliverable> basket = new HashSet<>(); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("COEH8262261")), 0.828936d)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("COEI0354262")), 0.80371d)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("COEI2292098")), 0.777869d)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("COEH6142705")), 0.852328d)); final BondFutureSecurity sec = new BondFutureSecurity(expiry, "XEUR", "XEUR", EUR, 1000, basket, LocalDateTime.of(2010, 6, 10, 0, 0, 0, 0).atZone(ZoneOffset.UTC), LocalDateTime.of(2010, 6, 10, 0, 0, 0, 0).atZone(ZoneOffset.UTC), "BOND"); sec.setName("EURO-BUND FUTURE Jun10"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX9439039-0")); identifiers.add(ExternalSchemes.cusipSecurityId("RXM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("RXM10 Comdty")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); return sec; } public static BondFutureSecurity makeUSBondFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 21, 20, 0), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final Set<BondFutureDeliverable> basket = new HashSet<>(); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810EV6")), 1.0858)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FB9")), 1.0132)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810PX0")), 0.7984)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FG8")), 0.9169)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810QD3")), 0.7771)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FF0")), 0.9174)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810PW2")), 0.7825)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FE3")), 0.9454)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810QH4")), 0.7757)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810PU6")), 0.8675)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810EX2")), 1.0765)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FT0")), 0.8054)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FJ2")), 1.0141)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810PT9")), 0.8352)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810QE1")), 0.8109)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FP8")), 0.9268)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810QA9")), 0.6606)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FM5")), 1.0286)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810EY0")), 1.0513)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810QB7")), 0.7616)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810QC5")), 0.795)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810EZ7")), 1.0649)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810EW4")), 1.0)); basket.add(new BondFutureDeliverable(ExternalIdBundle.of( ExternalSchemes.bloombergBuidSecurityId("GV912810FA1")), 1.0396)); final BondFutureSecurity sec = new BondFutureSecurity(expiry, "XCBT", "XCBT", USD, 100000, basket, LocalDateTime.of(2010, 6, 01, 0, 0, 0, 0).atZone(ZoneOffset.UTC), LocalDateTime.of(2010, 6, 30, 0, 0, 0, 0).atZone(ZoneOffset.UTC), "Bond"); sec.setName("US LONG BOND(CBT) Jun10"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX8530684-0")); identifiers.add(ExternalSchemes.cusipSecurityId("USM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("USM10 Comdty")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); return sec; } public static MetalFutureSecurity makeSilverFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 28, 18, 25), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final MetalFutureSecurity sec = new MetalFutureSecurity(expiry, "XCEC", "XCEC", USD, 5000, "Precious Metal"); sec.setName("SILVER FUTURE Jun10"); sec.setUnitNumber(5000.00); sec.setUnitName("troy oz."); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX10217289-0")); identifiers.add(ExternalSchemes.cusipSecurityId("SIM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("SIM10 Comdty")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); sec.setUniqueId(BloombergSecurityProvider.createUniqueId("IX10217289-0")); return sec; } public static EnergyFutureSecurity makeEthanolFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 3, 19, 15), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final EnergyFutureSecurity sec = new EnergyFutureSecurity(expiry, "XCBT", "XCBT", USD, 29000, "Refined Products"); sec.setName("DENATURED ETHANOL Jun10"); sec.setUnitNumber(29000.00); sec.setUnitName("U.S. Gallons"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX6054783-0")); identifiers.add(ExternalSchemes.cusipSecurityId("DLM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("DLM10 Comdty")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); sec.setUniqueId(BloombergSecurityProvider.createUniqueId("IX6054783-0")); return sec; } public static InterestRateFutureSecurity makeInterestRateFuture() { final Expiry expiry = new Expiry(ZonedDateTime.of(LocalDateTime.of(2010, Month.JUNE, 14, 20, 0), ZoneOffset.UTC), ExpiryAccuracy.MIN_HOUR_DAY_MONTH_YEAR); final InterestRateFutureSecurity sec = new InterestRateFutureSecurity(expiry, "XCME", "XCME", USD, 2500.0, ExternalId.of(ExternalSchemes.BLOOMBERG_TICKER, "US0003M Index"), "Interest Rate"); sec.setName("90DAY EURO$ FUTR Jun10"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX166549-0")); identifiers.add(ExternalSchemes.cusipSecurityId("EDM10")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("EDM10 Comdty")); sec.setExternalIdBundle(ExternalIdBundle.of(identifiers)); sec.setUniqueId(BloombergSecurityProvider.createUniqueId("IX166549-0")); return sec; } public static EquitySecurity makeExpectedATTEquitySecurity() { final EquitySecurity equitySecurity = new EquitySecurity("NEW YORK STOCK EXCHANGE, INC.", "XNYS", "AT&T INC", USD); equitySecurity.addExternalId(ExternalSchemes.bloombergTickerSecurityId(ATT_EQUITY_TICKER)); equitySecurity.addExternalId(ExternalSchemes.bloombergBuidSecurityId(ATT_BUID)); equitySecurity.addExternalId(ExternalSchemes.cusipSecurityId("00206R102")); equitySecurity.addExternalId(ExternalSchemes.isinSecurityId("US00206R1023")); equitySecurity.addExternalId(ExternalSchemes.sedol1SecurityId("2831811")); equitySecurity.setUniqueId(BloombergSecurityProvider.createUniqueId(ATT_BUID)); equitySecurity.setShortName("T"); equitySecurity.setName("AT&T INC"); equitySecurity.setGicsCode(GICSCode.of("50101020")); equitySecurity.setPreferred(false); return equitySecurity; } //note this will roll over on 2010-12-18 and the expected Buid and Expiry // date will change public static EquityIndexOptionSecurity makeSPXIndexOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 1100.0; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2010, 12, 18)); final ExternalId underlyingUniqueID = ExternalSchemes.bloombergBuidSecurityId("EI09SPX"); final EquityIndexOptionSecurity security = new EquityIndexOptionSecurity(optionType, strike, USD, underlyingUniqueID, new EuropeanExerciseType(), expiry, 100.0, "US"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX5801809-0-8980")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId(SPX_INDEX_OPTION_TICKER)); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX5801809-0-8980")); security.setName("SPX 2010-12-18 C 1100.0"); return security; } public static EquityIndexFutureOptionSecurity makeEquityIndexFutureOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 1000.0; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2013, 3, 15)); final ExternalId underlyingUniqueID = ExternalSchemes.bloombergBuidSecurityId("IX14248603-0"); final EquityIndexFutureOptionSecurity security = new EquityIndexFutureOptionSecurity( "CME", expiry, new AmericanExerciseType(), underlyingUniqueID, 50.0, true, USD, strike, optionType); final Set<ExternalId> identifiers = ImmutableSet.of( ExternalSchemes.bloombergBuidSecurityId("IX15354067-0-FD00"), ExternalSchemes.bloombergTickerSecurityId("ESH3C 1000 Index")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX15354067-0-FD00")); security.setName("ESH3C 2013-03-15 C 1000.0"); return security; } public static EquityIndexDividendFutureOptionSecurity makeEquityIndexDividendFutureOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 100.0; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2013, 12, 20)); final ExternalId underlyingUniqueID = ExternalSchemes.bloombergBuidSecurityId("IX6817069-0"); final EquityIndexDividendFutureOptionSecurity security = new EquityIndexDividendFutureOptionSecurity( "EUX", expiry, new EuropeanExerciseType(), underlyingUniqueID, 100.0, true, EUR, strike, optionType); final Set<ExternalId> identifiers = ImmutableSet.of( ExternalSchemes.bloombergBuidSecurityId("IX10363934-0-8C80"), ExternalSchemes.bloombergTickerSecurityId("DEDZ3C 100.00 Index")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX10363934-0-8C80")); security.setName("DEDZ3C 2013-12-20 C 100.0"); return security; } public static EquityOptionSecurity makeAPVLEquityOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 190.0; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2010, 01, 16)); final ExternalId underlyingIdentifier = ExternalSchemes.bloombergTickerSecurityId(AAPL_EQUITY_TICKER); final EquityOptionSecurity security = new EquityOptionSecurity(optionType, strike, USD, underlyingIdentifier, new AmericanExerciseType(), expiry, 100, "US"); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergTickerSecurityId(APV_EQUITY_OPTION_TICKER)); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("EO1016952010010397C00001")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("EO1016952010010397C00001")); security.setName("APV 2010-01-16 C 190.0"); return security; } public static EquitySecurity makeExpectedAAPLEquitySecurity() { final EquitySecurity equitySecurity = new EquitySecurity("NASDAQ/NGS (GLOBAL SELECT MARKET)", "XNGS", "APPLE INC", USD); equitySecurity.addExternalId(ExternalSchemes.bloombergTickerSecurityId(AAPL_EQUITY_TICKER)); equitySecurity.addExternalId(ExternalSchemes.bloombergBuidSecurityId(AAPL_BUID)); equitySecurity.addExternalId(ExternalSchemes.cusipSecurityId("037833100")); equitySecurity.addExternalId(ExternalSchemes.isinSecurityId("US0378331005")); equitySecurity.addExternalId(ExternalSchemes.sedol1SecurityId("2046251")); equitySecurity.setUniqueId(BloombergSecurityProvider.createUniqueId(AAPL_BUID)); equitySecurity.setShortName("AAPL"); equitySecurity.setName("APPLE INC"); equitySecurity.setGicsCode(GICSCode.of("45202030")); equitySecurity.setPreferred(false); return equitySecurity; } public static EquitySecurity makeExchangeTradedFund() { final EquitySecurity equitySecurity = new EquitySecurity("NYSE ARCA", "ARCX", "US NATURAL GAS FUND LP", USD); equitySecurity.addExternalId(ExternalSchemes.bloombergTickerSecurityId("UNG US Equity")); equitySecurity.addExternalId(ExternalSchemes.bloombergBuidSecurityId("EQ0000000003443730")); equitySecurity.addExternalId(ExternalSchemes.cusipSecurityId("912318102")); equitySecurity.addExternalId(ExternalSchemes.isinSecurityId("US9123181029")); equitySecurity.addExternalId(ExternalSchemes.sedol1SecurityId("B1W5XX3")); equitySecurity.setUniqueId(BloombergSecurityProvider.createUniqueId("EQ0000000003443730")); equitySecurity.setShortName("UNG"); equitySecurity.setName("US NATURAL GAS FUND LP"); equitySecurity.setPreferred(false); return equitySecurity; } public static Security makeAmericanGeneralEquity() { final EquitySecurity equitySecurity = new EquitySecurity("LONDON STOCK EXCHANGE", "XLON", "AMERICAN GENERAL CORP", GBP); equitySecurity.setUniqueId(BloombergSecurityProvider.createUniqueId("EQ0010006200001001")); equitySecurity.setName("AMERICAN GENERAL CORP"); equitySecurity.setShortName("EQ0010006200001001"); equitySecurity.addExternalId(ExternalSchemes.bloombergBuidSecurityId("EQ0010006200001001")); equitySecurity.addExternalId(ExternalSchemes.bloombergTickerSecurityId("575258Q LN Equity")); equitySecurity.addExternalId(ExternalSchemes.isinSecurityId("US0263511067")); equitySecurity.addExternalId(ExternalSchemes.cusipSecurityId("026351106")); return equitySecurity; } public static Security makeTHYSSENKRUPPEquity() { final EquitySecurity equitySecurity = new EquitySecurity("LONDON STOCK EXCHANGE", "XLON", "THYSSENKRUPP AEROSPACE UK LT", GBP); equitySecurity.setUniqueId(BloombergSecurityProvider.createUniqueId("EQ0011110200001000")); equitySecurity.setName("THYSSENKRUPP AEROSPACE UK LT"); equitySecurity.setShortName("EQ0011110200001000"); equitySecurity.addExternalId(ExternalSchemes.bloombergBuidSecurityId("EQ0011110200001000")); equitySecurity.addExternalId(ExternalSchemes.bloombergTickerSecurityId("2931300Q LN Equity")); equitySecurity.addExternalId(ExternalSchemes.isinSecurityId("GB0000458744")); equitySecurity.addExternalId(ExternalSchemes.sedol1SecurityId("0045874")); return equitySecurity; } public static Security makePTSEquity() { final EquitySecurity equitySecurity = new EquitySecurity("LONDON STOCK EXCHANGE", "XLON", "PTS GROUP PLC", GBP); equitySecurity.setUniqueId(BloombergSecurityProvider.createUniqueId("EQ0015697400001000")); equitySecurity.setName("PTS GROUP PLC"); equitySecurity.setShortName("EQ0015697400001000"); equitySecurity.addExternalId(ExternalSchemes.bloombergBuidSecurityId("EQ0015697400001000")); equitySecurity.addExternalId(ExternalSchemes.bloombergTickerSecurityId("365092Q LN Equity")); equitySecurity.addExternalId(ExternalSchemes.isinSecurityId("GB0006661457")); equitySecurity.addExternalId(ExternalSchemes.sedol1SecurityId("0666145")); return equitySecurity; } public static ExternalIdBundle makeBloombergTickerIdentifier(final String secDes) { return ExternalIdBundle.of(ExternalSchemes.bloombergTickerSecurityId(secDes)); } public static ExternalIdBundle makeBloombergBuid(final String secDes) { return ExternalIdBundle.of(ExternalSchemes.bloombergBuidSecurityId(secDes)); } public static IRFutureOptionSecurity makeEURODOLLARFutureOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 0.995; final double pointValue = 2500; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2012, 12, 17)); final ExternalId underlyingID = ExternalSchemes.bloombergTickerSecurityId("EDZ2 Comdty"); final String exchange = "CME"; final IRFutureOptionSecurity security = new IRFutureOptionSecurity(exchange, expiry, new AmericanExerciseType(), underlyingID, pointValue, false, USD, strike, optionType); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX11675985-0-8C70")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("EDZ2C 99.500 Comdty")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX11675985-0-8C70")); security.setName("EDZ2C 2012-12-17 C 99.5"); return security; } public static IRFutureOptionSecurity makeLIBORFutureOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 0.91; final double pointValue = 1250.0; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2011, 9, 21)); final ExternalId underlyingID = ExternalSchemes.bloombergTickerSecurityId("L U11 Comdty"); final String exchange = "LIF"; final IRFutureOptionSecurity security = new IRFutureOptionSecurity(exchange, expiry, new AmericanExerciseType(), underlyingID, pointValue, true, GBP, strike, optionType); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX9494155-0-8B60")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("L U1C 91.000 Comdty")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX9494155-0-8B60")); security.setName("L U1C 2011-09-21 C 91.0"); return security; } public static IRFutureOptionSecurity makeEURIBORFutureOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 0.92875; final double pointValue = 2500; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2011, 9, 19)); final ExternalId underlyingID = ExternalSchemes.bloombergTickerSecurityId("FPU11 Comdty"); final String exchange = "EUX"; final IRFutureOptionSecurity security = new IRFutureOptionSecurity( exchange, expiry, new AmericanExerciseType(), underlyingID, pointValue, true, EUR, strike, optionType); final Set<ExternalId> identifiers = new HashSet<>(); identifiers.add(ExternalSchemes.bloombergBuidSecurityId("IX10090132-0-8B9C")); identifiers.add(ExternalSchemes.bloombergTickerSecurityId("FPU1C 92.875 Comdty")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX10090132-0-8B9C")); security.setName("FPU1C 2011-09-19 C 92.875"); return security; } public static CommodityFutureOptionSecurity makeCommodityFutureOptionSecurity() { final OptionType optionType = OptionType.CALL; final double strike = 0.2425; final double pointValue = 1000; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2013, 2, 19)); final ExternalId underlyingID = ExternalSchemes.bloombergTickerSecurityId("CHH3 Comdty"); final String exchange = "NYM"; final CommodityFutureOptionSecurity security = new CommodityFutureOptionSecurity( exchange, exchange, expiry, new AmericanExerciseType(), underlyingID, pointValue, USD, strike, optionType); final Set<ExternalId> identifiers = ImmutableSet.of( ExternalSchemes.bloombergBuidSecurityId("IX12576261-0-8308"), ExternalSchemes.bloombergTickerSecurityId("CHH3C 24.25 Comdty")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX12576261-0-8308")); security.setName("CHH3C 2013-02-19 C 24.25"); return security; } public static FxFutureOptionSecurity makeFxFutureOptionSecurity() { final OptionType optionType = OptionType.PUT; final double strike = 1.05; final double pointValue = 1250; final Expiry expiry = new Expiry(DateUtils.getUTCDate(2013, 3, 8)); final ExternalId underlyingID = ExternalSchemes.bloombergTickerSecurityId("JYH3 Curncy"); final String exchange = "CME"; final FxFutureOptionSecurity security = new FxFutureOptionSecurity( exchange, exchange, expiry, new AmericanExerciseType(), underlyingID, pointValue, USD, strike, optionType); final Set<ExternalId> identifiers = ImmutableSet.of( ExternalSchemes.bloombergBuidSecurityId("IX14844402-0-0D20"), ExternalSchemes.bloombergTickerSecurityId("JYH3P 105.0 Curncy")); security.setExternalIdBundle(ExternalIdBundle.of(identifiers)); security.setUniqueId(BloombergSecurityProvider.createUniqueId("IX14844402-0-0D20")); security.setName("JYH3P 2013-03-08 P 105.0"); return security; } }
McLeodMoores/starling
projects/bloomberg/src/test/java/com/opengamma/bbg/util/BloombergSecurityUtils.java
Java
apache-2.0
29,062
package com.oneminutedistraction.hackersnews; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.database.DataSetObserver; import android.os.Build; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.TextView; import java.util.LinkedList; import java.util.List; /** * Created by cmlee on 19/8/16. */ public class StoryListAdapter implements ListAdapter { private DataSetObserver observer = null; private final Context context; //TODO should think about implementing a sparse list private List<HNStory> storyList = new LinkedList<>(); private class ViewHolder { public TextView tvTitle; public TextView tvBy; public TextView tvNew; } public StoryListAdapter(Context c) { context = c; } @Override public boolean areAllItemsEnabled() { for (HNStory hnStory: storyList) if (Constants.isNull(hnStory.getUrl())) return (false); return (true); } @Override public boolean isEnabled(int i) { return (!Constants.isNull(storyList.get(i).getUrl())); } @Override public void registerDataSetObserver(DataSetObserver dataSetObserver) { observer = dataSetObserver; } @Override public void unregisterDataSetObserver(DataSetObserver dataSetObserver) { if (observer == dataSetObserver) observer = null; } public void notifyModelChanged() { if (null != observer) observer.onChanged(); } public void pushStory(HNStory story, boolean trim) { if (trim) storyList.remove(storyList.size() - 1); storyList.add(0, story); notifyModelChanged(); } public void pushStory(HNStory story) { pushStory(story, false);; } public void addStory(HNStory story, boolean trim) { if (trim) storyList.remove(0); storyList.add(story); notifyModelChanged(); } public void addStory(HNStory story) { addStory(story, false); } public void clear() { storyList.clear(); notifyModelChanged(); } @Override public int getCount() { return (storyList.size()); } @Override public Object getItem(int i) { return (storyList.get(i)); } public HNStory getStory(int i) { return (storyList.get(i)); } @Override public long getItemId(int i) { return (storyList.get(i).getId()); } @Override public boolean hasStableIds() { return (true); } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; HNStory story; if (null == view) { LayoutInflater inflater = LayoutInflater.from(context); view = inflater.inflate(R.layout.story_item, null); holder = new ViewHolder(); holder.tvBy = (TextView)view.findViewById(R.id.tvBy); holder.tvTitle = (TextView)view.findViewById(R.id.tvTitle); holder.tvNew = (TextView) view.findViewById(R.id.tvNew); view.setTag(holder); } story = getStory(i); holder = (ViewHolder)view.getTag(); holder.tvBy.setText(story.getBy()); holder.tvTitle.setText(story.getTitle()); holder.tvNew.setText(story.isNewStory()? "NEW": ""); holder.tvTitle.setTextColor(getTextColor(isEnabled(i))); return (view); } public void markAllAsOld() { for (HNStory s: storyList) s.setNewStory(false); notifyModelChanged(); } private int getTextColor(boolean b) { Resources res = context.getResources(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) return (b? ContextCompat.getColor(context, R.color.colorBlack): ContextCompat.getColor(context, R.color.colorCherry)); return (b? res.getColor(R.color.colorBlack): res.getColor(R.color.colorCherry)); } @Override public int getItemViewType(int i) { return (isEnabled(i)? 1: 0); } @Override public int getViewTypeCount() { return 2; } @Override public boolean isEmpty() { return (storyList.isEmpty()); } }
chukmunnlee/HackersNews
app/src/main/java/com/oneminutedistraction/hackersnews/StoryListAdapter.java
Java
apache-2.0
4,486
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <app/clusters/ota-requestor/OTADownloader.h> #include "OTAImageProcessorImpl.h" #include <ti/common/cc26xx/flash_interface/flash_interface.h> #include <ti/common/cc26xx/oad/ext_flash_layout.h> #include <ti_drivers_config.h> // clang-format off /* driverlib header for resetting the SoC */ #include <ti/devices/DeviceFamily.h> #include DeviceFamily_constructPath(driverlib/sys_ctrl.h) // clang-format on namespace chip { CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() { DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast<intptr_t>(this)); return CHIP_NO_ERROR; } CHIP_ERROR OTAImageProcessorImpl::Finalize() { DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast<intptr_t>(this)); return CHIP_NO_ERROR; } CHIP_ERROR OTAImageProcessorImpl::Apply() { DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast<intptr_t>(this)); return CHIP_NO_ERROR; } CHIP_ERROR OTAImageProcessorImpl::Abort() { DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast<intptr_t>(this)); return CHIP_NO_ERROR; } CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) { if (nullptr == mNvsHandle) { return CHIP_ERROR_INTERNAL; } if ((nullptr == block.data()) || block.empty()) { return CHIP_ERROR_INVALID_ARGUMENT; } // Store block data for HandleProcessBlock to access CHIP_ERROR err = SetBlock(block); if (err != CHIP_NO_ERROR) { ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); } DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast<intptr_t>(this)); return CHIP_NO_ERROR; } /* DESIGN NOTE: The Boot Image Manager will search external flash for an * `ExtImageInfo_t` structure every 4K for 1M. This structure points to where * the executable image is in external flash with a uint32_t. It is possible to * have multiple images ready to be programmed into the internal flash of the * device. This design is only concerned with managing 1 image in external * flash starting at `IMG_START` and being defined by a meta header at address * 0. Future designs may be able to take advantage of other images for rollback * functionality, however this will require a larger external flash chip. */ #define IMG_START (4 * EFL_SIZE_META) static bool readExtFlashImgHeader(NVS_Handle handle, imgFixedHdr_t * header) { int_fast16_t status; status = NVS_read(handle, IMG_START, header, sizeof(header)); return (status == NVS_STATUS_SUCCESS); } static bool eraseExtFlashHeader(NVS_Handle handle) { int_fast16_t status; NVS_Attrs regionAttrs; unsigned int sectors; NVS_getAttrs(handle, &regionAttrs); /* calculate the number of sectors to erase */ sectors = (sizeof(imgFixedHdr_t) + (regionAttrs.sectorSize - 1)) / regionAttrs.sectorSize; status = NVS_erase(handle, IMG_START, sectors * regionAttrs.sectorSize); return (status == NVS_STATUS_SUCCESS); } /* makes room for the new block if needed */ static bool writeExtFlashImgPages(NVS_Handle handle, size_t bytesWritten, MutableByteSpan block) { int_fast16_t status; NVS_Attrs regionAttrs; unsigned int erasedSectors; unsigned int neededSectors; size_t sectorSize; NVS_getAttrs(handle, &regionAttrs); sectorSize = regionAttrs.sectorSize; erasedSectors = (bytesWritten + (sectorSize - 1)) / sectorSize; neededSectors = ((bytesWritten + block.size()) + (sectorSize - 1)) / sectorSize; if (neededSectors != erasedSectors) { status = NVS_erase(handle, IMG_START + (erasedSectors * sectorSize), (neededSectors - erasedSectors) * sectorSize); if (status != NVS_STATUS_SUCCESS) { return false; } } status = NVS_write(handle, IMG_START + bytesWritten, block.data(), block.size(), NVS_WRITE_POST_VERIFY); return (status == NVS_STATUS_SUCCESS); } static bool readExtFlashMetaHeader(NVS_Handle handle, ExtImageInfo_t * header) { int_fast16_t status; status = NVS_read(handle, EFL_ADDR_META, header, sizeof(header)); return (status == NVS_STATUS_SUCCESS); } static bool eraseExtFlashMetaHeader(NVS_Handle handle) { int_fast16_t status; NVS_Attrs regionAttrs; unsigned int sectors; NVS_getAttrs(handle, &regionAttrs); /* calculate the number of sectors to erase */ sectors = (sizeof(ExtImageInfo_t) + (regionAttrs.sectorSize - 1)) / regionAttrs.sectorSize; status = NVS_erase(handle, EFL_ADDR_META, sectors * regionAttrs.sectorSize); return (status == NVS_STATUS_SUCCESS); } static bool writeExtFlashMetaHeader(NVS_Handle handle, ExtImageInfo_t * header) { int_fast16_t status; if (!eraseExtFlashMetaHeader(handle)) { return false; } status = NVS_write(handle, EFL_ADDR_META, header, sizeof(header), NVS_WRITE_POST_VERIFY); return (status == NVS_STATUS_SUCCESS); } /** * Generated on by pycrc v0.9.2, https://pycrc.org using the configuration: * - Width = 32 * - Poly = 0x04c11db7 * - XorIn = 0xffffffff * - ReflectIn = True * - XorOut = 0xffffffff * - ReflectOut = True * - Algorithm = bit-by-bit-fast * * Modified to take uint32_t as the CRC type */ uint32_t crc_reflect(uint32_t data, size_t data_len) { unsigned int i; uint32_t ret; ret = data & 0x01; for (i = 1; i < data_len; i++) { data >>= 1; ret = (ret << 1) | (data & 0x01); } return ret; } uint32_t crc_update(uint32_t crc, const void * data, size_t data_len) { const unsigned char * d = (const unsigned char *) data; unsigned int i; bool bit; unsigned char c; while (data_len--) { c = *d++; for (i = 0x01; i & 0xff; i <<= 1) { bit = crc & 0x80000000; if (c & i) { bit = !bit; } crc <<= 1; if (bit) { crc ^= 0x04c11db7; } } crc &= 0xffffffff; } return crc & 0xffffffff; } static bool validateExtFlashImage(NVS_Handle handle) { uint32_t crc; imgFixedHdr_t header; size_t addr, endAddr; if (!readExtFlashImgHeader(handle, &header)) { return false; } /* CRC is calculated after the CRC element of the image header */ addr = IMG_START + IMG_DATA_OFFSET; endAddr = IMG_START + header.len; crc = 0xFFFFFFFF; while (addr < endAddr) { uint8_t buffer[32]; size_t bytesLeft = endAddr - addr; size_t toRead = (sizeof(buffer) < bytesLeft) ? sizeof(buffer) : bytesLeft; if (NVS_STATUS_SUCCESS != NVS_read(handle, addr, buffer, toRead)) { return false; } crc = crc_update(crc, buffer, toRead); addr += toRead; } crc = crc_reflect(crc, 32) ^ 0xffffffff; return (crc == header.crc32); } void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) { NVS_Params nvsParams; NVS_Handle handle; auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context); if (imageProcessor == nullptr) { ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); return; } else if (imageProcessor->mDownloader == nullptr) { ChipLogError(SoftwareUpdate, "mDownloader is null"); return; } NVS_Params_init(&nvsParams); handle = NVS_open(CONFIG_NVSEXTERNAL, &nvsParams); if (NULL == handle) { imageProcessor->mDownloader->OnPreparedForDownload(CHIP_ERROR_OPEN_FAILED); return; } if (!eraseExtFlashMetaHeader(handle)) { NVS_close(handle); imageProcessor->mDownloader->OnPreparedForDownload(CHIP_ERROR_WRITE_FAILED); return; } imageProcessor->mNvsHandle = handle; imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); } void OTAImageProcessorImpl::HandleFinalize(intptr_t context) { ExtImageInfo_t header; auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context); if (imageProcessor == nullptr) { return; } if (!readExtFlashImgHeader(imageProcessor->mNvsHandle, &(header.fixedHdr))) { return; } header.extFlAddr = IMG_START; header.counter = 0x0; if (validateExtFlashImage(imageProcessor->mNvsHandle)) { // only write the meta header if the crc check passes writeExtFlashMetaHeader(imageProcessor->mNvsHandle, &header); } else { // ensure the external image is not mistaken for a valid image eraseExtFlashMetaHeader(imageProcessor->mNvsHandle); } imageProcessor->ReleaseBlock(); ChipLogProgress(SoftwareUpdate, "OTA image downloaded"); } void OTAImageProcessorImpl::HandleApply(intptr_t context) { ExtImageInfo_t header; auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context); if (imageProcessor == nullptr) { return; } if (!readExtFlashMetaHeader(imageProcessor->mNvsHandle, &header)) { return; } header.fixedHdr.imgCpStat = NEED_COPY; writeExtFlashMetaHeader(imageProcessor->mNvsHandle, &header); // reset SoC to kick BIM SysCtrlSystemReset(); } void OTAImageProcessorImpl::HandleAbort(intptr_t context) { auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context); if (imageProcessor == nullptr) { return; } if (!eraseExtFlashMetaHeader(imageProcessor->mNvsHandle)) { imageProcessor->mDownloader->OnPreparedForDownload(CHIP_ERROR_WRITE_FAILED); } NVS_close(imageProcessor->mNvsHandle); imageProcessor->ReleaseBlock(); } void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) { auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context); if (imageProcessor == nullptr) { ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); return; } else if (imageProcessor->mDownloader == nullptr) { ChipLogError(SoftwareUpdate, "mDownloader is null"); return; } // TODO: Process block header if any if (!writeExtFlashImgPages(imageProcessor->mNvsHandle, imageProcessor->mParams.downloadedBytes, imageProcessor->mBlock)) { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); return; } imageProcessor->mParams.downloadedBytes += imageProcessor->mBlock.size(); imageProcessor->mDownloader->FetchNextData(); } CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) { if (!IsSpanUsable(block)) { ReleaseBlock(); return CHIP_NO_ERROR; } if (mBlock.size() < block.size()) { if (!mBlock.empty()) { ReleaseBlock(); } uint8_t * mBlock_ptr = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(block.size())); if (mBlock_ptr == nullptr) { return CHIP_ERROR_NO_MEMORY; } mBlock = MutableByteSpan(mBlock_ptr, block.size()); } CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); if (err != CHIP_NO_ERROR) { ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); return err; } return CHIP_NO_ERROR; } CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() { if (mBlock.data() != nullptr) { chip::Platform::MemoryFree(mBlock.data()); } mBlock = MutableByteSpan(); return CHIP_NO_ERROR; } } // namespace chip
project-chip/connectedhomeip
src/platform/cc13x2_26x2/OTAImageProcessorImpl.cpp
C++
apache-2.0
12,356
JANOME_VERSION='0.3.9'
nakagami/janome
janome/version.py
Python
apache-2.0
23
package goplaces.apis; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.io.IOException; import java.util.logging.*; import com.google.appengine.api.datastore.*; import com.google.appengine.api.memcache.*; import goplaces.models.Place; import org.json.JSONObject; /** * Mapped to /placesmemcache. * GET, POST and DELETE are supported to manipulate Place objects in the memcache. * * @author Aviral Takkar * * Curl examples: * * GET - curl "http://go-places-ucsb.appspot.com/rest/placesmemcache/{place_id}" * * POST - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data * "{\"name\":\"UCSB\",\"address\":\"At the Pacific shore,California\",\"latitude\":5.6,\"longitude\":6.6, * \"rating\":5.0,\"reviews\":\"its magnificient\",\"googlePlaceId\":\"unknown\"}" http://go-places-ucsb.appspot * .com/rest/placesmemcache * */ @Path("/placesmemcache") public class PlacesMemcacheAPI { @Context UriInfo uriInfo; @Context Request request; DatastoreService datastore; MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String addPlace(Place place, @Context HttpServletResponse servletResponse) throws IOException { try{ syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); Entity entity = new Entity("Place", place.getGooglePlaceId()); entity.setProperty("name", place.getName()); entity.setProperty("address", place.getAddress()); entity.setProperty("latitude", place.getLatitude()); entity.setProperty("longitude", place.getLongitude()); entity.setProperty("rating", place.getRating()); entity.setProperty("reviews", new Text(place.getReviews())); String cacheKey = "place-" + place.getGooglePlaceId(); syncCache.put(cacheKey, entity); return new JSONObject().append("status","OK").append("key", cacheKey).toString(); } catch(Exception e){ return new JSONObject().append("status","fail").append("message", "Google Place ID is required.") .toString(); } } @GET @Path("{place_id}") @Produces(MediaType.APPLICATION_JSON) public String getPlace(@PathParam("place_id") String googlePlaceId) { syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); JSONObject reply = new JSONObject(); try{ Entity result = (Entity)syncCache.get(googlePlaceId); if(result != null) return reply.append("status", "OK").append("message", "Found in memcache.").append("Place Object", result).toString(); return reply.append("status", "fail").append("message", "Not found in memcache.").toString(); } catch(Exception e){ return new JSONObject().append("status", "fail").append("message", e.getMessage()).toString(); } } @DELETE @Path("{place_id}") @Produces(MediaType.APPLICATION_JSON) public String deletePlace(@PathParam("place_id") String googlePlaceId){ syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); JSONObject reply = new JSONObject(); try{ syncCache.delete(googlePlaceId); return reply.append("status", "OK").append("message", "successfully deleted place " + googlePlaceId) .toString(); } catch(Exception e){ return new JSONObject().append("status", "fail").append("message", "Place object with ID " + googlePlaceId + " " + "not " + "found in memcache.").toString(); } } }
aviral26/ucsb-cs-263
goplaces/src/main/java/goplaces/apis/PlacesMemcacheAPI.java
Java
apache-2.0
3,929
var functions_dup = [ [ "_", "functions.html", null ], [ "a", "functions_a.html", null ], [ "b", "functions_b.html", null ], [ "c", "functions_c.html", null ], [ "d", "functions_d.html", null ], [ "e", "functions_e.html", null ], [ "f", "functions_f.html", null ], [ "g", "functions_g.html", null ], [ "h", "functions_h.html", null ], [ "i", "functions_i.html", null ], [ "k", "functions_k.html", null ], [ "l", "functions_l.html", null ], [ "m", "functions_m.html", null ], [ "n", "functions_n.html", null ], [ "o", "functions_o.html", null ], [ "p", "functions_p.html", null ], [ "r", "functions_r.html", null ], [ "s", "functions_s.html", null ], [ "t", "functions_t.html", null ], [ "u", "functions_u.html", null ], [ "v", "functions_v.html", null ], [ "w", "functions_w.html", null ], [ "x", "functions_x.html", null ], [ "z", "functions_z.html", null ] ];
grbd/GBD.Build.BlackJack
docs/doxygen/html/functions_dup.js
JavaScript
apache-2.0
957
/** * Forge SDK * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. * * OpenAPI spec version: 0.1.0 * Contact: forge.help@autodesk.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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. */ module.export = (function() { 'use strict'; var expect = require('expect.js'), ForgeSdk = require('../../src'); describe('JobPayloadInput', function() { it('should create an instance of JobPayloadInput', function() { var instance = new ForgeSdk.JobPayloadInput(); expect(instance).to.be.a(ForgeSdk.JobPayloadInput); }); }); }());
Autodesk-Forge/forge-api-nodejs-client
test/model/JobPayloadInput.spec.js
JavaScript
apache-2.0
1,409
package amazon import ( "encoding/json" "fmt" "io/ioutil" "net/http" "sync" "time" "github.com/cenk/backoff" ) const ( endpointURL string = "https://drive.amazonaws.com/drive/v1/account/endpoint" ) // Endpoint provides the URLs the drive service should talk to. // // It provides threadsafe methods to get the Content and Metadata URLs, to // lookup new ones, and to keep them persistently up to date. type Endpoint struct { sync.RWMutex client *http.Client contentURL string metadataURL string } // NewEndpoint returns an initialized Endpoint, or an error. func NewEndpoint(c *http.Client) (*Endpoint, error) { ep := &Endpoint{client: c} if err := ep.GetEndpoint(); err != nil { return nil, err } go ep.RefreshEndpoint() return ep, nil } type endpointResponse struct { ContentURL string // eg. https://content-na.drive.amazonaws.com/cdproxy/ MetadataURL string // eg. https://cdws.us-east-1.amazonaws.com/drive/v1/" CustomerExists bool } // GetEndpoint requests the URL for this user to send queries to. func (ep *Endpoint) GetEndpoint() error { resp, err := ep.client.Get(endpointURL) if err != nil { return fmt.Errorf("Get(endpointURL): %s", err) } defer resp.Body.Close() // unpack this JSON response endpointJSON, err := ioutil.ReadAll(resp.Body) if err != nil { return err } var epResp endpointResponse if err := json.Unmarshal(endpointJSON, &epResp); err != nil { return fmt.Errorf("json unmarshal error: %s", err) } // update the URLs ep.Lock() defer ep.Unlock() ep.contentURL = epResp.ContentURL ep.metadataURL = epResp.MetadataURL return nil } // refreshEndpoint periodically calls GetEndpoint // This needs to be run every 3-5 days, per: // https://developer.amazon.com/public/apis/experience/cloud-drive/content/account // // TODO(asjoyner): cache this, and save 1 RPC for every invocation of throw func (ep *Endpoint) RefreshEndpoint() { for { if err := backoff.Retry(ep.GetEndpoint, backoff.NewExponentialBackOff()); err != nil { // Failed for 15 minutes, lets sleep for a couple hours and try again. time.Sleep(2 * time.Hour) } else { // Success! Hibernation time... time.Sleep(72 * time.Hour) } } } func (ep *Endpoint) MetadataURL() string { ep.RLock() defer ep.RUnlock() return ep.metadataURL } func (ep *Endpoint) ContentURL() string { ep.RLock() defer ep.RUnlock() return ep.contentURL }
asjoyner/shade
drive/amazon/endpoint.go
GO
apache-2.0
2,404
package itest import ( "github.com/ligato/cn-infra/core" "github.com/ligato/cn-infra/flavors/local" "github.com/onsi/gomega" "testing" ) type suiteFlavorLocal struct { T *testing.T AgentT Given When Then } // TC01 asserts that injection works fine and agent starts & stops func (t *suiteFlavorLocal) TC01StartStop() { flavor := &local.FlavorLocal{} t.Setup(flavor, t.T) defer t.Teardown() gomega.Expect(t.agent).ShouldNot(gomega.BeNil(), "agent is not initialized") } // TC02 check that logger in flavor works func (t *suiteFlavorLocal) TC02Logger() { flavor := &local.FlavorLocal{} t.Setup(flavor, t.T) defer t.Teardown() logger := flavor.LogRegistry().NewLogger("myTest") gomega.Expect(logger).ShouldNot(gomega.BeNil(), "logger is not initialized") logger.Debug("log msg") } // TC03 check that status check in flavor works func (t *suiteFlavorLocal) TC03StatusCheck() { flavor := &local.FlavorLocal{} t.Setup(flavor, t.T) defer t.Teardown() tstPlugin := core.PluginName("tstPlugin") flavor.StatusCheck.Register(tstPlugin, nil) flavor.StatusCheck.ReportStateChange(tstPlugin, "tst", nil) //TODO assert flavor.StatusCheck using IDX map??? }
mpundlik/cn-infra
tests/gotests/itest/local_flavor_tcs.go
GO
apache-2.0
1,176
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MortgageCalculator.Tests { [TestClass] public class MortgageCalculatorTests { [TestMethod] public void TestMethod1() { } } }
coreyhaines/CodeKatas
MortgageCalculator.Tests/MortgageCalculatorTests.cs
C#
apache-2.0
253
# frozen_string_literal: true # Error when revision number is too high (ODK only supports 2 digits) class RevisionTooHighError < StandardError def initialize(msg = "Revision number can't be more than 2 digits") super end end
thecartercenter/elmo
app/models/revision_too_high_error.rb
Ruby
apache-2.0
234
require 'spec_helper' describe Mongo::Operation::Command do let(:selector) { { :ismaster => 1 } } let(:options) { { :limit => -1 } } let(:spec) do { :selector => selector, :options => options, :db_name => TEST_DB } end let(:op) { described_class.new(spec) } describe '#initialize' do it 'sets the spec' do expect(op.spec).to be(spec) end end describe '#==' do context 'when the ops have different specs' do let(:other_selector) { { :ping => 1 } } let(:other_spec) do { :selector => other_selector, :options => {}, :db_name => 'test', } end let(:other) { described_class.new(other_spec) } it 'returns false' do expect(op).not_to eq(other) end end end context '#merge' do let(:other_op) { described_class.new(spec) } it 'raises an exception' do expect{ op.merge(other_op) }.to raise_exception end end context '#merge!' do let(:other_op) { described_class.new(spec) } it 'raises an exception' do expect{ op.merge!(other_op) }.to raise_exception end end describe '#execute' do context 'when the command succeeds' do let(:response) do op.execute(authorized_primary.context) end it 'returns the reponse' do expect(response).to be_successful end end context 'when the command fails' do let(:selector) do { notacommand: 1 } end it 'raises an exception' do expect { op.execute(authorized_primary.context) }.to raise_error(Mongo::Operation::Write::Failure) end end context 'when the command cannot run on a secondary' do context 'when the server is a secondary' do pending 'it re-routes to the primary' end end end end
sferik/mongo-ruby-driver
spec/mongo/operation/command_spec.rb
Ruby
apache-2.0
1,868
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jdisc.core; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Module; import com.yahoo.jdisc.AbstractResource; import com.yahoo.jdisc.application.Application; import com.yahoo.jdisc.application.ApplicationNotReadyException; import com.yahoo.jdisc.application.ContainerActivator; import com.yahoo.jdisc.application.ContainerBuilder; import com.yahoo.jdisc.application.DeactivatedContainer; import com.yahoo.jdisc.application.GuiceRepository; import com.yahoo.jdisc.application.OsgiFramework; import com.yahoo.jdisc.application.OsgiHeader; import com.yahoo.jdisc.service.ContainerNotReadyException; import com.yahoo.jdisc.service.CurrentContainer; import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Simon Thoresen Hult * @author bjorncs */ public class ApplicationLoader implements BootstrapLoader, ContainerActivator, CurrentContainer { private static final Logger log = Logger.getLogger(ApplicationLoader.class.getName()); private final OsgiFramework osgiFramework; private final GuiceRepository guiceModules = new GuiceRepository(); private final AtomicReference<ActiveContainer> containerRef = new AtomicReference<>(); private final Object appLock = new Object(); private final List<Bundle> appBundles = new ArrayList<>(); private final ContainerWatchdog watchdog = new ContainerWatchdog(); private Application application; private ApplicationInUseTracker applicationInUseTracker; public ApplicationLoader(OsgiFramework osgiFramework, Iterable<? extends Module> guiceModules) { this.osgiFramework = osgiFramework; this.guiceModules.install(new ApplicationEnvironmentModule(this)); this.guiceModules.installAll(guiceModules); } @Override public ContainerBuilder newContainerBuilder() { return new ContainerBuilder(guiceModules); } @Override public DeactivatedContainer activateContainer(ContainerBuilder builder) { ActiveContainer next = builder != null ? new ActiveContainer(builder) : null; final ActiveContainer prev; synchronized (appLock) { if (application == null && next != null) { next.release(); throw new ApplicationNotReadyException(); } if (next != null) { next.retainReference(applicationInUseTracker); } watchdog.onContainerActivation(next); prev = containerRef.getAndSet(next); if (prev == null) { return null; } } prev.release(); return prev.shutdown(); } @Override public ContainerSnapshot newReference(URI uri, Object context) { ActiveContainer container = containerRef.get(); if (container == null) { throw new ContainerNotReadyException(); } return container.newReference(uri, context); } @Override public void init(String appLocation, boolean privileged) throws Exception { log.finer("Initializing application loader."); osgiFramework.start(); BundleContext ctx = osgiFramework.bundleContext(); if (ctx != null) { ctx.registerService(CurrentContainer.class.getName(), this, null); } if(appLocation == null) { return; // application class bound by another module } try { Class<Application> appClass = ContainerBuilder.safeClassCast(Application.class, Class.forName(appLocation)); guiceModules.install(new AbstractModule() { @Override public void configure() { bind(Application.class).to(appClass); } }); return; // application class found on class path } catch (ClassNotFoundException e) { // location is not a class name if (log.isLoggable(Level.FINE)) { log.fine("App location is not a class name. Installing bundle"); } } appBundles.addAll(osgiFramework.installBundle(appLocation)); if (OsgiHeader.isSet(appBundles.get(0), OsgiHeader.PRIVILEGED_ACTIVATOR)) { osgiFramework.startBundles(appBundles, privileged); } } @Override public void start() throws Exception { log.finer("Initializing application."); Injector injector = guiceModules.activate(); Application app; if (!appBundles.isEmpty()) { Bundle appBundle = appBundles.get(0); if (!OsgiHeader.isSet(appBundle, OsgiHeader.PRIVILEGED_ACTIVATOR)) { osgiFramework.startBundles(appBundles, false); } List<String> header = OsgiHeader.asList(appBundle, OsgiHeader.APPLICATION); if (header.size() != 1) { throw new IllegalArgumentException("OSGi header '" + OsgiHeader.APPLICATION + "' has " + header.size() + " entries, expected 1."); } String appName = header.get(0); log.finer("Loading application class " + appName + " from bundle '" + appBundle.getSymbolicName() + "'."); Class<Application> appClass = ContainerBuilder.safeClassCast(Application.class, appBundle.loadClass(appName)); app = injector.getInstance(appClass); } else { app = injector.getInstance(Application.class); log.finer("Injecting instance of " + app.getClass().getName() + "."); } try { synchronized (appLock) { application = app; applicationInUseTracker = new ApplicationInUseTracker(); } app.start(); } catch (Exception e) { log.log(Level.WARNING, "Exception thrown while activating application.", e); synchronized (appLock) { application = null; applicationInUseTracker = null; } app.destroy(); throw e; } } @Override public void stop() throws Exception { log.finer("Destroying application."); Application app; ApplicationInUseTracker applicationInUseTracker; synchronized (appLock) { app = application; applicationInUseTracker = this.applicationInUseTracker; } if (app == null || applicationInUseTracker == null) { return; } try { app.stop(); } catch (Exception e) { log.log(Level.WARNING, "Exception thrown while deactivating application.", e); } synchronized (appLock) { application = null; } activateContainer(null); synchronized (appLock) { this.applicationInUseTracker = null; } applicationInUseTracker.release(); applicationInUseTracker.applicationInUseLatch.await(); app.destroy(); } @Override public void destroy() { log.finer("Destroying application loader."); try { watchdog.close(); osgiFramework.stop(); } catch (BundleException | InterruptedException e) { e.printStackTrace(); } } public Application application() { synchronized (appLock) { return application; } } public ContainerWatchdogMetrics getContainerWatchdogMetrics() { return watchdog; } public OsgiFramework osgiFramework() { return osgiFramework; } private static class ApplicationInUseTracker extends AbstractResource { //opened when the application has been stopped and there's no active containers final CountDownLatch applicationInUseLatch = new CountDownLatch(1); @Override protected void destroy() { applicationInUseLatch.countDown(); } } }
vespa-engine/vespa
jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
Java
apache-2.0
8,521
/* * Copyright (c) 2013 Villu Ruusmann */ package org.jpmml.knime; import org.jpmml.evaluator.*; import org.junit.*; import static org.junit.Assert.*; public class ClusteringTest { @Test public void evaluateKmeansIris() throws Exception { Batch batch = new KnimeBatch("KMeans", "Iris"); assertTrue(BatchUtil.evaluate(batch)); } }
jpmml/jpmml
pmml-knime/src/test/java/org/jpmml/knime/ClusteringTest.java
Java
apache-2.0
344
/* * Copyright 2017 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.optaplanner.core.impl.score.buildin.hardmediumsoftbigdecimal; import java.math.BigDecimal; import java.util.Arrays; import org.optaplanner.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore; import org.optaplanner.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScoreHolder; import org.optaplanner.core.impl.score.definition.AbstractFeasibilityScoreDefinition; import org.optaplanner.core.impl.score.trend.InitializingScoreTrend; public class HardMediumSoftBigDecimalScoreDefinition extends AbstractFeasibilityScoreDefinition<HardMediumSoftBigDecimalScore> { public HardMediumSoftBigDecimalScoreDefinition() { super(new String[]{"hard score", "medium score", "soft score"}); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 3; } @Override public int getFeasibleLevelsSize() { return 1; } @Override public Class<HardMediumSoftBigDecimalScore> getScoreClass() { return HardMediumSoftBigDecimalScore.class; } @Override public HardMediumSoftBigDecimalScore parseScore(String scoreString) { return HardMediumSoftBigDecimalScore.parseScore(scoreString); } @Override public HardMediumSoftBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return HardMediumSoftBigDecimalScore.valueOfUninitialized(initScore, (BigDecimal) levelNumbers[0], (BigDecimal) levelNumbers[1], (BigDecimal) levelNumbers[2]); } @Override public HardMediumSoftBigDecimalScoreHolder buildScoreHolder(boolean constraintMatchEnabled) { return new HardMediumSoftBigDecimalScoreHolder(constraintMatchEnabled); } @Override public HardMediumSoftBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardMediumSoftBigDecimalScore score) { // TODO https://issues.jboss.org/browse/PLANNER-232 throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" + " because a BigDecimal cannot represent infinity."); } @Override public HardMediumSoftBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardMediumSoftBigDecimalScore score) { // TODO https://issues.jboss.org/browse/PLANNER-232 throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" + " because a BigDecimal cannot represent infinity."); } }
oskopek/optaplanner
optaplanner-core/src/main/java/org/optaplanner/core/impl/score/buildin/hardmediumsoftbigdecimal/HardMediumSoftBigDecimalScoreDefinition.java
Java
apache-2.0
3,597
import java.awt.Graphics; import java.awt.Image; import javax.swing.JPanel; /** * ´ø±³¾°µÄÃæ°å×é¼þ * * @author ZhongWei Lee */ public class BackgroundPanel extends JPanel { /** * ±³¾°Í¼Æ¬ */ private Image image; /** * ¹¹Ôì·½·¨ */ public BackgroundPanel() { super(); setOpaque(false); setLayout(null); } /** * ÉèÖÃͼƬµÄ·½·¨ */ public void setImage(Image image) { this.image = image; } @Override protected void paintComponent(Graphics g) {// ÖØÐ´»æÖÆ×é¼þÍâ¹Û if (image != null) { g.drawImage(image, 0, 0, this);// »æÖÆÍ¼Æ¬Óë×é¼þ´óСÏàͬ } super.paintComponent(g);// Ö´Ðг¬Àà·½·¨ } }
xingwen93/java-notebook
BackgroundPanel.java
Java
apache-2.0
798
# Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from testrunner.local import commands from testrunner.local import testsuite from testrunner.local import utils from testrunner.objects import testcase class FuzzNativesTestSuite(testsuite.TestSuite): def __init__(self, name, root): super(FuzzNativesTestSuite, self).__init__(name, root) def ListTests(self, context): shell = os.path.abspath(os.path.join(context.shell_dir, self.shell())) if utils.IsWindows(): shell += ".exe" output = commands.Execute( context.command_prefix + [shell, "--allow-natives-syntax", "-e", "try { var natives = %ListNatives();" " for (var n in natives) { print(natives[n]); }" "} catch(e) {}"] + context.extra_flags) if output.exit_code != 0: print output.stdout print output.stderr assert False, "Failed to get natives list." tests = [] for line in output.stdout.strip().split(): (name, argc) = line.split(",") flags = ["--allow-natives-syntax", "-e", "var NAME = '%s', ARGC = %s;" % (name, argc)] test = testcase.TestCase(self, name, flags) tests.append(test) return tests def GetFlagsForTestCase(self, testcase, context): name = testcase.path basefile = os.path.join(self.root, "base.js") return testcase.flags + [basefile] + context.mode_flags def GetSuite(name, root): return FuzzNativesTestSuite(name, root)
nextsmsversion/macchina.io
platform/JS/V8/v8-3.28.4/test/fuzz-natives/testcfg.py
Python
apache-2.0
1,591
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.04.10 at 02:30:20 PM IST // package org.or5e.itunes.jxb; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse" }) @XmlRootElement(name = "plist") public class Plist { @XmlAttribute(name = "version") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected java.lang.String version; @XmlElements({ @XmlElement(name = "array", required = true, type = Array.class), @XmlElement(name = "data", required = true, type = Data.class), @XmlElement(name = "date", required = true, type = Date.class), @XmlElement(name = "dict", required = true, type = Dict.class), @XmlElement(name = "real", required = true, type = Real.class), @XmlElement(name = "integer", required = true, type = Integer.class), @XmlElement(name = "string", required = true, type = org.or5e.itunes.jxb.String.class), @XmlElement(name = "true", required = true, type = True.class), @XmlElement(name = "false", required = true, type = False.class) }) protected List<Object> arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse; /** * Gets the value of the version property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getVersion() { if (version == null) { return "1.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setVersion(java.lang.String value) { this.version = value; } /** * Gets the value of the arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse property. * * <p> * For example, to add a new item, do as follows: * <pre> * getArrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Array } * {@link Data } * {@link Date } * {@link Dict } * {@link Real } * {@link Integer } * {@link org.or5e.itunes.jxb.String } * {@link True } * {@link False } * * */ public List<Object> getArrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse() { if (arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse == null) { arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse = new ArrayList<Object>(); } return this.arrayOrDataOrDateOrDictOrRealOrIntegerOrStringOrTrueOrFalse; } }
mylifeponraj/or5e-labs
media-player/src/main/java/org/or5e/itunes/jxb/Plist.java
Java
apache-2.0
4,070
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws.kinesis; import com.amazonaws.services.kinesis.AmazonKinesis; import com.amazonaws.services.kinesis.model.ShardIteratorType; import org.apache.camel.CamelContext; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.SimpleRegistry; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(MockitoJUnitRunner.class) public class KinesisEndpointTest { @Mock private AmazonKinesis amazonKinesisClient; private CamelContext camelContext; @Before public void setup() throws Exception { SimpleRegistry registry = new SimpleRegistry(); registry.put("kinesisClient", amazonKinesisClient); camelContext = new DefaultCamelContext(registry); } @Test public void allTheEndpointParams() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint("aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient" + "&maxResultsPerRequest=101" + "&iteratorType=latest" + "&shardId=abc" + "&sequenceNumber=123" ); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.LATEST)); assertThat(endpoint.getMaxResultsPerRequest(), is(101)); assertThat(endpoint.getSequenceNumber(), is("123")); assertThat(endpoint.getShardId(), is("abc")); } @Test public void onlyRequiredEndpointParams() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint("aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient" ); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.TRIM_HORIZON)); assertThat(endpoint.getMaxResultsPerRequest(), is(1)); } @Test public void afterSequenceNumberRequiresSequenceNumber() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint("aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient" + "&iteratorType=AFTER_SEQUENCE_NUMBER" + "&shardId=abc" + "&sequenceNumber=123" ); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.AFTER_SEQUENCE_NUMBER)); assertThat(endpoint.getShardId(), is("abc")); assertThat(endpoint.getSequenceNumber(), is("123")); } @Test public void atSequenceNumberRequiresSequenceNumber() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint("aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient" + "&iteratorType=AT_SEQUENCE_NUMBER" + "&shardId=abc" + "&sequenceNumber=123" ); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.AT_SEQUENCE_NUMBER)); assertThat(endpoint.getShardId(), is("abc")); assertThat(endpoint.getSequenceNumber(), is("123")); } }
isavin/camel
components/camel-aws/src/test/java/org/apache/camel/component/aws/kinesis/KinesisEndpointTest.java
Java
apache-2.0
4,589
<?php namespace Topxia\WebBundle\Util; use Topxia\Service\Common\ServiceKernel; class AvatarAlert { public static function alertJoinCourse($user) { $setting = self::getSettingService()->get('user_partner'); if (empty($setting['avatar_alert'])) { return false; } if ($setting['avatar_alert'] == 'open' && $user['mediumAvatar'] == '') { return true; } return false; } public static function alertInMyCenter($user) { $setting = self::getSettingService()->get('user_partner'); if (empty($setting['avatar_alert'])) { return false; } if ($user['mediumAvatar'] == '') { return true; } return false; } protected static function getSettingService() { return ServiceKernel::instance()->createService('System.SettingService'); } }
18826252059/im
src/Topxia/WebBundle/Util/AvatarAlert.php
PHP
apache-2.0
919
///* // * To change this license header, choose License Headers in Project Properties. // * To change this template file, choose Tools | Templates // * and open the template in the editor. // */ //package me.jittagornp.profile; // //import java.io.IOException; //import java.util.Date; //import java.util.UUID; //import javax.servlet.Filter; //import javax.servlet.FilterChain; //import javax.servlet.FilterConfig; //import javax.servlet.ServletException; //import javax.servlet.ServletRequest; //import javax.servlet.ServletResponse; //import javax.servlet.annotation.WebFilter; //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; // ///** // * // * @author jittagornp // */ //@WebFilter("/*") //public class CacheFilter implements Filter { // // private String etag; // private long lastModified; // private long expires = 0; // private final int maxAge = 1000 * 60 * 30; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // } // // private void resetExpires() { // long current = System.currentTimeMillis(); // if (current > expires) { // etag = UUID.randomUUID().toString(); // lastModified = current; // expires = current + maxAge; // } // } // // @Override // public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) resp; // // resetExpires(); // // response.addHeader("etag", etag); // response.addDateHeader("last-modified", lastModified); // response.addDateHeader("expires", expires); // response.addHeader("cache-control", "public, max-age=" + maxAge); // // chain.doFilter(request, response); // // } // // @Override // public void destroy() { // // } // //}
jittagornp/jittagornp.me
src/main/java/me/jittagornp/profile/CacheFilter.java
Java
apache-2.0
1,995
/* * Copyright(c) DBFlute TestCo.,TestLtd. All Rights Reserved. */ package org.docksidestage.derby.dbflute.cbean; import org.docksidestage.derby.dbflute.cbean.bs.BsMemberServiceCB; /** * The condition-bean of MEMBER_SERVICE. * <p> * You can implement your original methods here. * This class remains when re-generating. * </p> * @author DBFlute(AutoGenerator) */ public class MemberServiceCB extends BsMemberServiceCB { }
dbflute-test/dbflute-test-dbms-derby
src/main/java/org/docksidestage/derby/dbflute/cbean/MemberServiceCB.java
Java
apache-2.0
450
/* * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface PatchRegionHealthCheckRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.PatchRegionHealthCheckRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Name of the HealthCheck resource to patch. * </pre> * * <code>string health_check = 308876645 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The healthCheck. */ java.lang.String getHealthCheck(); /** * * * <pre> * Name of the HealthCheck resource to patch. * </pre> * * <code>string health_check = 308876645 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for healthCheck. */ com.google.protobuf.ByteString getHealthCheckBytes(); /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.HealthCheck health_check_resource = 201925032 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the healthCheckResource field is set. */ boolean hasHealthCheckResource(); /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.HealthCheck health_check_resource = 201925032 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The healthCheckResource. */ com.google.cloud.compute.v1.HealthCheck getHealthCheckResource(); /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.HealthCheck health_check_resource = 201925032 [(.google.api.field_behavior) = REQUIRED]; * </code> */ com.google.cloud.compute.v1.HealthCheckOrBuilder getHealthCheckResourceOrBuilder(); /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The project. */ java.lang.String getProject(); /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The bytes for project. */ com.google.protobuf.ByteString getProjectBytes(); /** * * * <pre> * Name of the region scoping this request. * </pre> * * <code> * string region = 138946292 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "region"]; * </code> * * @return The region. */ java.lang.String getRegion(); /** * * * <pre> * Name of the region scoping this request. * </pre> * * <code> * string region = 138946292 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "region"]; * </code> * * @return The bytes for region. */ com.google.protobuf.ByteString getRegionBytes(); /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return Whether the requestId field is set. */ boolean hasRequestId(); /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The requestId. */ java.lang.String getRequestId(); /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The bytes for requestId. */ com.google.protobuf.ByteString getRequestIdBytes(); }
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/PatchRegionHealthCheckRequestOrBuilder.java
Java
apache-2.0
6,377
package de.st_ddt.crazyspawner.entities.properties; import java.util.Map; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Sheep; import de.st_ddt.crazyspawner.CrazySpawner; import de.st_ddt.crazyutil.paramitrisable.BooleanParamitrisable; import de.st_ddt.crazyutil.paramitrisable.Paramitrisable; import de.st_ddt.crazyutil.paramitrisable.TabbedParamitrisable; import de.st_ddt.crazyutil.source.Localized; public class SheepProperty extends BasicProperty { protected final boolean sheared; public SheepProperty() { super(); this.sheared = false; } public SheepProperty(final ConfigurationSection config) { super(config); this.sheared = config.getBoolean("sheared", false); } public SheepProperty(final Map<String, ? extends Paramitrisable> params) { super(params); final BooleanParamitrisable shearedParam = (BooleanParamitrisable) params.get("sheared"); this.sheared = shearedParam.getValue(); } @Override public boolean isApplicable(final Class<? extends Entity> clazz) { return Sheep.class.isAssignableFrom(clazz); } @Override public void apply(final Entity entity) { final Sheep sheep = (Sheep) entity; sheep.setSheared(sheared); } @Override public void getCommandParams(final Map<String, ? super TabbedParamitrisable> params, final CommandSender sender) { final BooleanParamitrisable shearedParam = new BooleanParamitrisable(sheared); params.put("s", shearedParam); params.put("sheared", shearedParam); } @Override public void save(final ConfigurationSection config, final String path) { config.set(path + "sheared", sheared); } @Override public void dummySave(final ConfigurationSection config, final String path) { config.set(path + "sheared", "boolean (true/false)"); } @Override @Localized("CRAZYSPAWNER.ENTITY.PROPERTY.SHEARED $Sheared$") public void show(final CommandSender target) { CrazySpawner.getPlugin().sendLocaleMessage("ENTITY.PROPERTY.SHEARED", target, sheared); } @Override public boolean equalsDefault() { return sheared == false; } }
ST-DDT/CrazySpawner
src/main/java/de/st_ddt/crazyspawner/entities/properties/SheepProperty.java
Java
apache-2.0
2,150
package com.github.binarywang.wxpay.bean.marketing.enums; import lombok.AllArgsConstructor; import lombok.Getter; /** * 批次类型 * * @author yujam */ @Getter @AllArgsConstructor public enum StockTypeEnum { /** * NORMAL:固定面额满减券批次 */ NORMAL("NORMAL"), /** * DISCOUNT:折扣券批次 */ DISCOUNT("DISCOUNT"), /** * EXCHANGE:换购券批次 */ EXCHANGE("EXCHANGE"); /** * 批次类型 */ private final String value; }
Wechat-Group/WxJava
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/marketing/enums/StockTypeEnum.java
Java
apache-2.0
492
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * CustomerGatewayIdSetType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.6 Built on : Aug 30, 2011 (10:01:01 CEST) */ package com.amazon.ec2; /** * CustomerGatewayIdSetType bean class */ public class CustomerGatewayIdSetType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = CustomerGatewayIdSetType Namespace URI = http://ec2.amazonaws.com/doc/2012-08-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for Item * This was an Array! */ protected com.amazon.ec2.CustomerGatewayIdSetItemType[] localItem ; /* This tracker boolean wil be used to detect whether the user called the set method * for this attribute. It will be used to determine whether to include this field * in the serialized XML */ protected boolean localItemTracker = false ; /** * Auto generated getter method * @return com.amazon.ec2.CustomerGatewayIdSetItemType[] */ public com.amazon.ec2.CustomerGatewayIdSetItemType[] getItem(){ return localItem; } /** * validate the array for Item */ protected void validateItem(com.amazon.ec2.CustomerGatewayIdSetItemType[] param){ } /** * Auto generated setter method * @param param Item */ public void setItem(com.amazon.ec2.CustomerGatewayIdSetItemType[] param){ validateItem(param); if (param != null){ //update the setting tracker localItemTracker = true; } else { localItemTracker = false; } this.localItem=param; } /** * Auto generated add method for the array for convenience * @param param com.amazon.ec2.CustomerGatewayIdSetItemType */ public void addItem(com.amazon.ec2.CustomerGatewayIdSetItemType param){ if (localItem == null){ localItem = new com.amazon.ec2.CustomerGatewayIdSetItemType[]{}; } //update the setting tracker localItemTracker = true; java.util.List list = org.apache.axis2.databinding.utils.ConverterUtil.toList(localItem); list.add(param); this.localItem = (com.amazon.ec2.CustomerGatewayIdSetItemType[])list.toArray( new com.amazon.ec2.CustomerGatewayIdSetItemType[list.size()]); } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { CustomerGatewayIdSetType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2012-08-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":CustomerGatewayIdSetType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "CustomerGatewayIdSetType", xmlWriter); } } if (localItemTracker){ if (localItem!=null){ for (int i = 0;i < localItem.length;i++){ if (localItem[i] != null){ localItem[i].serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","item"), factory,xmlWriter); } else { // we don't have to do any thing since minOccures is zero } } } else { throw new org.apache.axis2.databinding.ADBException("item cannot be null!!"); } } xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); if (localItemTracker){ if (localItem!=null) { for (int i = 0;i < localItem.length;i++){ if (localItem[i] != null){ elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/", "item")); elementList.add(localItem[i]); } else { // nothing to do } } } else { throw new org.apache.axis2.databinding.ADBException("item cannot be null!!"); } } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static CustomerGatewayIdSetType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ CustomerGatewayIdSetType object = new CustomerGatewayIdSetType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"CustomerGatewayIdSetType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (CustomerGatewayIdSetType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); java.util.ArrayList list1 = new java.util.ArrayList(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","item").equals(reader.getName())){ // Process the array and step past its final element's end. list1.add(com.amazon.ec2.CustomerGatewayIdSetItemType.Factory.parse(reader)); //loop until we find a start element that is not part of this array boolean loopDone1 = false; while(!loopDone1){ // We should be at the end element, but make sure while (!reader.isEndElement()) reader.next(); // Step out of this element reader.next(); // Step to next element event. while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isEndElement()){ //two continuous end elements means we are exiting the xml structure loopDone1 = true; } else { if (new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","item").equals(reader.getName())){ list1.add(com.amazon.ec2.CustomerGatewayIdSetItemType.Factory.parse(reader)); }else{ loopDone1 = true; } } } // call the converter utility to convert and set the array object.setItem((com.amazon.ec2.CustomerGatewayIdSetItemType[]) org.apache.axis2.databinding.utils.ConverterUtil.convertToArray( com.amazon.ec2.CustomerGatewayIdSetItemType.class, list1)); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
mufaddalq/cloudstack-datera-driver
awsapi/src/com/amazon/ec2/CustomerGatewayIdSetType.java
Java
apache-2.0
26,876
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.operators; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.junit.Test; import org.mockito.InOrder; import rx.Notification; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observer; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.exceptions.MissingBackpressureException; import rx.exceptions.TestException; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.internal.util.RxRingBuffer; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; public class OperatorObserveOnTest { /** * This is testing a no-op path since it uses Schedulers.immediate() which will not do scheduling. */ @Test @SuppressWarnings("unchecked") public void testObserveOn() { Observer<Integer> observer = mock(Observer.class); Observable.just(1, 2, 3).observeOn(Schedulers.immediate()).subscribe(observer); verify(observer, times(1)).onNext(1); verify(observer, times(1)).onNext(2); verify(observer, times(1)).onNext(3); verify(observer, times(1)).onCompleted(); } @Test @SuppressWarnings("unchecked") public void testOrdering() throws InterruptedException { Observable<String> obs = Observable.just("one", null, "two", "three", "four"); Observer<String> observer = mock(Observer.class); InOrder inOrder = inOrder(observer); TestSubscriber<String> ts = new TestSubscriber<String>(observer); obs.observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); if (ts.getOnErrorEvents().size() > 0) { for (Throwable t : ts.getOnErrorEvents()) { t.printStackTrace(); } fail("failed with exception"); } inOrder.verify(observer, times(1)).onNext("one"); inOrder.verify(observer, times(1)).onNext(null); inOrder.verify(observer, times(1)).onNext("two"); inOrder.verify(observer, times(1)).onNext("three"); inOrder.verify(observer, times(1)).onNext("four"); inOrder.verify(observer, times(1)).onCompleted(); inOrder.verifyNoMoreInteractions(); } @Test @SuppressWarnings("unchecked") public void testThreadName() throws InterruptedException { System.out.println("Main Thread: " + Thread.currentThread().getName()); Observable<String> obs = Observable.just("one", null, "two", "three", "four"); Observer<String> observer = mock(Observer.class); final String parentThreadName = Thread.currentThread().getName(); final CountDownLatch completedLatch = new CountDownLatch(1); // assert subscribe is on main thread obs = obs.doOnNext(new Action1<String>() { @Override public void call(String s) { String threadName = Thread.currentThread().getName(); System.out.println("Source ThreadName: " + threadName + " Expected => " + parentThreadName); assertEquals(parentThreadName, threadName); } }); // assert observe is on new thread obs.observeOn(Schedulers.newThread()).doOnNext(new Action1<String>() { @Override public void call(String t1) { String threadName = Thread.currentThread().getName(); boolean correctThreadName = threadName.startsWith("RxNewThreadScheduler"); System.out.println("ObserveOn ThreadName: " + threadName + " Correct => " + correctThreadName); assertTrue(correctThreadName); } }).finallyDo(new Action0() { @Override public void call() { completedLatch.countDown(); } }).subscribe(observer); if (!completedLatch.await(1000, TimeUnit.MILLISECONDS)) { fail("timed out waiting"); } verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(5)).onNext(any(String.class)); verify(observer, times(1)).onCompleted(); } @Test public void observeOnTheSameSchedulerTwice() { Scheduler scheduler = Schedulers.immediate(); Observable<Integer> o = Observable.just(1, 2, 3); Observable<Integer> o2 = o.observeOn(scheduler); @SuppressWarnings("unchecked") Observer<Object> observer1 = mock(Observer.class); @SuppressWarnings("unchecked") Observer<Object> observer2 = mock(Observer.class); InOrder inOrder1 = inOrder(observer1); InOrder inOrder2 = inOrder(observer2); o2.subscribe(observer1); o2.subscribe(observer2); inOrder1.verify(observer1, times(1)).onNext(1); inOrder1.verify(observer1, times(1)).onNext(2); inOrder1.verify(observer1, times(1)).onNext(3); inOrder1.verify(observer1, times(1)).onCompleted(); verify(observer1, never()).onError(any(Throwable.class)); inOrder1.verifyNoMoreInteractions(); inOrder2.verify(observer2, times(1)).onNext(1); inOrder2.verify(observer2, times(1)).onNext(2); inOrder2.verify(observer2, times(1)).onNext(3); inOrder2.verify(observer2, times(1)).onCompleted(); verify(observer2, never()).onError(any(Throwable.class)); inOrder2.verifyNoMoreInteractions(); } @Test public void observeSameOnMultipleSchedulers() { TestScheduler scheduler1 = new TestScheduler(); TestScheduler scheduler2 = new TestScheduler(); Observable<Integer> o = Observable.just(1, 2, 3); Observable<Integer> o1 = o.observeOn(scheduler1); Observable<Integer> o2 = o.observeOn(scheduler2); @SuppressWarnings("unchecked") Observer<Object> observer1 = mock(Observer.class); @SuppressWarnings("unchecked") Observer<Object> observer2 = mock(Observer.class); InOrder inOrder1 = inOrder(observer1); InOrder inOrder2 = inOrder(observer2); o1.subscribe(observer1); o2.subscribe(observer2); scheduler1.advanceTimeBy(1, TimeUnit.SECONDS); scheduler2.advanceTimeBy(1, TimeUnit.SECONDS); inOrder1.verify(observer1, times(1)).onNext(1); inOrder1.verify(observer1, times(1)).onNext(2); inOrder1.verify(observer1, times(1)).onNext(3); inOrder1.verify(observer1, times(1)).onCompleted(); verify(observer1, never()).onError(any(Throwable.class)); inOrder1.verifyNoMoreInteractions(); inOrder2.verify(observer2, times(1)).onNext(1); inOrder2.verify(observer2, times(1)).onNext(2); inOrder2.verify(observer2, times(1)).onNext(3); inOrder2.verify(observer2, times(1)).onCompleted(); verify(observer2, never()).onError(any(Throwable.class)); inOrder2.verifyNoMoreInteractions(); } /** * Confirm that running on a NewThreadScheduler uses the same thread for the entire stream */ @Test public void testObserveOnWithNewThreadScheduler() { final AtomicInteger count = new AtomicInteger(); final int _multiple = 99; Observable.range(1, 100000).map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return t1 * _multiple; } }).observeOn(Schedulers.newThread()) .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { assertEquals(count.incrementAndGet() * _multiple, t1.intValue()); assertTrue(Thread.currentThread().getName().startsWith("RxNewThreadScheduler")); } }); } /** * Confirm that running on a ThreadPoolScheduler allows multiple threads but is still ordered. */ @Test public void testObserveOnWithThreadPoolScheduler() { final AtomicInteger count = new AtomicInteger(); final int _multiple = 99; Observable.range(1, 100000).map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return t1 * _multiple; } }).observeOn(Schedulers.computation()) .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { assertEquals(count.incrementAndGet() * _multiple, t1.intValue()); assertTrue(Thread.currentThread().getName().startsWith("RxComputationThreadPool")); } }); } /** * Attempts to confirm that when pauses exist between events, the ScheduledObserver * does not lose or reorder any events since the scheduler will not block, but will * be re-scheduled when it receives new events after each pause. * * * This is non-deterministic in proving success, but if it ever fails (non-deterministically) * it is a sign of potential issues as thread-races and scheduling should not affect output. */ @Test public void testObserveOnOrderingConcurrency() { final AtomicInteger count = new AtomicInteger(); final int _multiple = 99; Observable.range(1, 10000).map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { if (randomIntFrom0to100() > 98) { try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } return t1 * _multiple; } }).observeOn(Schedulers.computation()) .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { assertEquals(count.incrementAndGet() * _multiple, t1.intValue()); assertTrue(Thread.currentThread().getName().startsWith("RxComputationThreadPool")); } }); } @Test public void testNonBlockingOuterWhileBlockingOnNext() throws InterruptedException { final CountDownLatch completedLatch = new CountDownLatch(1); final CountDownLatch nextLatch = new CountDownLatch(1); final AtomicLong completeTime = new AtomicLong(); // use subscribeOn to make async, observeOn to move Observable.range(1, 2).subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(new Observer<Integer>() { @Override public void onCompleted() { System.out.println("onCompleted"); completeTime.set(System.nanoTime()); completedLatch.countDown(); } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { // don't let this thing finish yet try { if (!nextLatch.await(1000, TimeUnit.MILLISECONDS)) { throw new RuntimeException("it shouldn't have timed out"); } } catch (InterruptedException e) { throw new RuntimeException("it shouldn't have failed"); } } }); long afterSubscribeTime = System.nanoTime(); System.out.println("After subscribe: " + completedLatch.getCount()); assertEquals(1, completedLatch.getCount()); nextLatch.countDown(); completedLatch.await(1000, TimeUnit.MILLISECONDS); assertTrue(completeTime.get() > afterSubscribeTime); System.out.println("onComplete nanos after subscribe: " + (completeTime.get() - afterSubscribeTime)); } private static int randomIntFrom0to100() { // XORShift instead of Math.random http://javamex.com/tutorials/random_numbers/xorshift.shtml long x = System.nanoTime(); x ^= (x << 21); x ^= (x >>> 35); x ^= (x << 4); return Math.abs((int) x % 100); } @Test public void testDelayedErrorDeliveryWhenSafeSubscriberUnsubscribes() { TestScheduler testScheduler = new TestScheduler(); Observable<Integer> source = Observable.concat(Observable.<Integer> error(new TestException()), Observable.just(1)); @SuppressWarnings("unchecked") Observer<Integer> o = mock(Observer.class); InOrder inOrder = inOrder(o); source.observeOn(testScheduler).subscribe(o); inOrder.verify(o, never()).onError(any(TestException.class)); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); inOrder.verify(o).onError(any(TestException.class)); inOrder.verify(o, never()).onNext(anyInt()); inOrder.verify(o, never()).onCompleted(); } @Test public void testAfterUnsubscribeCalledThenObserverOnNextNeverCalled() { final TestScheduler testScheduler = new TestScheduler(); @SuppressWarnings("unchecked") final Observer<Integer> observer = mock(Observer.class); final Subscription subscription = Observable.just(1, 2, 3) .observeOn(testScheduler) .subscribe(observer); subscription.unsubscribe(); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); final InOrder inOrder = inOrder(observer); inOrder.verify(observer, never()).onNext(anyInt()); inOrder.verify(observer, never()).onError(any(Exception.class)); inOrder.verify(observer, never()).onCompleted(); } @Test public void testBackpressureWithTakeAfter() { final AtomicInteger generated = new AtomicInteger(); Observable<Integer> observable = Observable.from(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public void remove() { } @Override public Integer next() { return generated.getAndIncrement(); } @Override public boolean hasNext() { return true; } }; } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>() { @Override public void onNext(Integer t) { System.err.println("c t = " + t + " thread " + Thread.currentThread()); super.onNext(t); try { Thread.sleep(10); } catch (InterruptedException e) { } } }; observable .observeOn(Schedulers.newThread()) .take(3) .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); System.err.println(testSubscriber.getOnNextEvents()); testSubscriber.assertReceivedOnNext(Arrays.asList(0, 1, 2)); // it should be between the take num and requested batch size across the async boundary System.out.println("Generated: " + generated.get()); assertTrue(generated.get() >= 3 && generated.get() <= RxRingBuffer.SIZE); } @Test public void testBackpressureWithTakeAfterAndMultipleBatches() { int numForBatches = RxRingBuffer.SIZE * 3 + 1; // should be 4 batches == ((3*n)+1) items final AtomicInteger generated = new AtomicInteger(); Observable<Integer> observable = Observable.from(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public void remove() { } @Override public Integer next() { return generated.getAndIncrement(); } @Override public boolean hasNext() { return true; } }; } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>() { @Override public void onNext(Integer t) { // System.err.println("c t = " + t + " thread " + Thread.currentThread()); super.onNext(t); } }; observable .observeOn(Schedulers.newThread()) .take(numForBatches) .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); System.err.println(testSubscriber.getOnNextEvents()); // it should be between the take num and requested batch size across the async boundary System.out.println("Generated: " + generated.get()); assertTrue(generated.get() >= numForBatches && generated.get() <= numForBatches + RxRingBuffer.SIZE); } @Test public void testBackpressureWithTakeBefore() { final AtomicInteger generated = new AtomicInteger(); Observable<Integer> observable = Observable.from(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public void remove() { } @Override public Integer next() { return generated.getAndIncrement(); } @Override public boolean hasNext() { return true; } }; } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>(); observable .take(7) .observeOn(Schedulers.newThread()) .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertReceivedOnNext(Arrays.asList(0, 1, 2, 3, 4, 5, 6)); assertEquals(7, generated.get()); } @Test public void testQueueFullEmitsError() { final CountDownLatch latch = new CountDownLatch(1); Observable<Integer> observable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> o) { for (int i = 0; i < RxRingBuffer.SIZE + 10; i++) { o.onNext(i); } latch.countDown(); o.onCompleted(); } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { // force it to be slow and wait until we have queued everything try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }); observable.observeOn(Schedulers.newThread()).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); List<Throwable> errors = testSubscriber.getOnErrorEvents(); assertEquals(1, errors.size()); System.out.println("Errors: " + errors); Throwable t = errors.get(0); if (t instanceof MissingBackpressureException) { // success, we expect this } else { if (t.getCause() instanceof MissingBackpressureException) { // this is also okay } else { fail("Expecting MissingBackpressureException"); } } } @Test public void testAsyncChild() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, 100000).observeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); } @Test public void testOnErrorCutsAheadOfOnNext() { for (int i = 0; i < 50; i++) { final PublishSubject<Long> subject = PublishSubject.create(); final AtomicLong counter = new AtomicLong(); TestSubscriber<Long> ts = new TestSubscriber<Long>(new Observer<Long>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Long t) { // simulate slow consumer to force backpressure failure try { Thread.sleep(1); } catch (InterruptedException e) { } } }); subject.observeOn(Schedulers.computation()).subscribe(ts); // this will blow up with backpressure while (counter.get() < 102400) { subject.onNext(counter.get()); counter.incrementAndGet(); } ts.awaitTerminalEvent(); assertEquals(1, ts.getOnErrorEvents().size()); assertTrue(ts.getOnErrorEvents().get(0) instanceof MissingBackpressureException); // assert that the values are sequential, that cutting in didn't allow skipping some but emitting others. // example [0, 1, 2] not [0, 1, 4] List<Long> onNextEvents = ts.getOnNextEvents(); assertTrue(onNextEvents.isEmpty() || onNextEvents.size() == onNextEvents.get(onNextEvents.size() - 1) + 1); // we should emit the error without emitting the full buffer size assertTrue(onNextEvents.size() < RxRingBuffer.SIZE); } } /** * Make sure we get a MissingBackpressureException propagated through when we have a fast temporal (hot) producer. */ @Test public void testHotOperatorBackpressure() { TestSubscriber<String> ts = new TestSubscriber<String>(); Observable.timer(0, 1, TimeUnit.MICROSECONDS) .observeOn(Schedulers.computation()) .map(new Func1<Long, String>() { @Override public String call(Long t1) { System.out.println(t1); try { Thread.sleep(100); } catch (InterruptedException e) { } return t1 + " slow value"; } }).subscribe(ts); ts.awaitTerminalEvent(); System.out.println("Errors: " + ts.getOnErrorEvents()); assertEquals(1, ts.getOnErrorEvents().size()); assertEquals(MissingBackpressureException.class, ts.getOnErrorEvents().get(0).getClass()); } @Test public void testErrorPropagatesWhenNoOutstandingRequests() { Observable<Long> timer = Observable.timer(0, 1, TimeUnit.MICROSECONDS) .doOnEach(new Action1<Notification<? super Long>>() { @Override public void call(Notification<? super Long> n) { // System.out.println("BEFORE " + n); } }) .observeOn(Schedulers.newThread()) .doOnEach(new Action1<Notification<? super Long>>() { @Override public void call(Notification<? super Long> n) { try { Thread.sleep(100); } catch (InterruptedException e) { } // System.out.println("AFTER " + n); } }); TestSubscriber<Long> ts = new TestSubscriber<Long>(); Observable.combineLatest(timer, Observable.<Integer> never(), new Func2<Long, Integer, Long>() { @Override public Long call(Long t1, Integer t2) { return t1; } }).take(RxRingBuffer.SIZE * 2).subscribe(ts); ts.awaitTerminalEvent(); assertEquals(1, ts.getOnErrorEvents().size()); assertEquals(MissingBackpressureException.class, ts.getOnErrorEvents().get(0).getClass()); } @Test public void testRequestOverflow() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger count = new AtomicInteger(); Observable.range(1, 100).observeOn(Schedulers.computation()) .subscribe(new Subscriber<Integer>() { boolean first = true; @Override public void onStart() { request(2); } @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { count.incrementAndGet(); if (first) { request(Long.MAX_VALUE - 1); request(Long.MAX_VALUE - 1); request(10); first = false; } } }); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertEquals(100, count.get()); } }
hyarlagadda/RxJava
src/test/java/rx/internal/operators/OperatorObserveOnTest.java
Java
apache-2.0
27,633
package org.qi4j.tutorials.composites.tutorial6; import org.qi4j.api.mixin.Mixins; import org.qi4j.library.constraints.annotation.NotEmpty; // START SNIPPET: solution /** * This interface contains only the state * of the HelloWorld object. * <p> * The parameters are declared as @NotEmpty, so the client cannot pass in empty strings * as values. * </p> */ @Mixins( HelloWorldStateMixin.class ) public interface HelloWorldState { void setPhrase( @NotEmpty String phrase ) throws IllegalArgumentException; String getPhrase(); void setName( @NotEmpty String name ) throws IllegalArgumentException; String getName(); } // END SNIPPET: solution
joobn72/qi4j-sdk
tutorials/composites/src/main/java/org/qi4j/tutorials/composites/tutorial6/HelloWorldState.java
Java
apache-2.0
685
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codestar.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.codestar.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteProjectRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteProjectRequestMarshaller { private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("id").build(); private static final MarshallingInfo<String> CLIENTREQUESTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("clientRequestToken").build(); private static final MarshallingInfo<Boolean> DELETESTACK_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deleteStack").build(); private static final DeleteProjectRequestMarshaller instance = new DeleteProjectRequestMarshaller(); public static DeleteProjectRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteProjectRequest deleteProjectRequest, ProtocolMarshaller protocolMarshaller) { if (deleteProjectRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteProjectRequest.getId(), ID_BINDING); protocolMarshaller.marshall(deleteProjectRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); protocolMarshaller.marshall(deleteProjectRequest.getDeleteStack(), DELETESTACK_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-codestar/src/main/java/com/amazonaws/services/codestar/model/transform/DeleteProjectRequestMarshaller.java
Java
apache-2.0
2,647
/* 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.activiti.app.rest.runtime; import javax.servlet.http.HttpServletRequest; import org.activiti.app.service.runtime.ActivitiProcessDefinitionService; import org.activiti.form.model.FormDefinition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class ProcessDefinitionResource { @Autowired protected ActivitiProcessDefinitionService processDefinitionService; @RequestMapping(value = "/rest/process-definitions/{processDefinitionId}/start-form", method = RequestMethod.GET, produces = "application/json") public FormDefinition getProcessDefinitionStartForm(HttpServletRequest request) { return processDefinitionService.getProcessDefinitionStartForm(request); } }
roberthafner/flowable-engine
modules/flowable-ui-task/flowable-ui-task-rest/src/main/java/org/activiti/app/rest/runtime/ProcessDefinitionResource.java
Java
apache-2.0
1,475
using System; using FlagMySpace.Agnostic.IoC; using FlagMySpace.Portable.IoC; using FlagMySpace.Portable.Localization; using FlagMySpace.Portable.Resources; using FlagMySpace.Portable.NinjectModules; using FlagMySpace.Portable.ViewFactory; using FlagMySpace.Portable.ViewModels; using Ninject; namespace FlagMySpace.Portable.Bootstrap { public class NinjectBoostrapper : BootstrapperBase { protected override IIoC ConfigureContainer() { var kernel = new StandardKernel(new FlagMySpaceModule(), new MockProviderModule()); return kernel.Get<IoCNinject>(); } } }
FlagMySpace/CrossPlatformClient
FlagMySpace/FlagMySpace.Portable/Bootstrap/NinjectBoostrapper.cs
C#
apache-2.0
623
/** * Copyright © 2013-2018 shadowhunt (dev@shadowhunt.de) * * 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 de.shadowhunt.subversion.internal.httpv2.v1_8; import de.shadowhunt.subversion.internal.AbstractRepositoryAddIT; public class RepositoryAddIT extends AbstractRepositoryAddIT { private static final Helper HELPER = new Helper(); public RepositoryAddIT() { super(HELPER.getRepositoryA(), HELPER.getTestId()); } }
thrawn-sh/subversion
src/test/java/de/shadowhunt/subversion/internal/httpv2/v1_8/RepositoryAddIT.java
Java
apache-2.0
965
package com.ubb.app; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
BoldijarPaul/ubb
app/src/androidTest/java/com/ubb/app/ApplicationTest.java
Java
apache-2.0
342
//------------------------------------------------------------------------------ /// \file Mod.cpp /// \author Ernest Yeung /// \email ernestyalumni@gmail.com /// \brief Program 9.2. Source file for the Mod class, Mod.cc /// \details /// \ref pp. 162. Edward Scheinerman. C++ for Mathematicians: An Introduction /// for Students and Professionals. 2006. Ch. 9 Modular Arithmetic. /// \copyright If you find this code useful, feel free to donate directly and /// easily at this direct PayPal link: /// /// https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ernestsaveschristmas%2bpaypal%40gmail%2ecom&lc=US&item_name=ernestyalumni&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted /// /// which won't go through a 3rd. party such as indiegogo, kickstarter, patreon. /// Otherwise, I receive emails and messages on how all my (free) material on /// physics, math, and engineering have helped students with their studies, and /// I know what it's like to not have money as a student, but love physics (or /// math, sciences, etc.), so I am committed to keeping all my material /// open-source and free, whether or not sufficiently crowdfunded, under the /// open-source MIT license: feel free to copy, edit, paste, make your own /// versions, share, use as you wish. /// Peace out, never give up! -EY //------------------------------------------------------------------------------ /// COMPILATION TIPS: /// g++ -std=c++14 FileOpen_main.cpp FileOpen.cpp -o FileOpen_main //------------------------------------------------------------------------------ #include "Mod.h" #include "gcdx.h" #include <iostream> long Mod::default_modulus = INITIAL_DEFAULT_MODULUS; std::ostream& operator<<(std::ostream& os, const Mod& M) { if (!M.is_invalid()) { os << "Mod(" << M.get_val() << "," << M.get_mod() << ")"; } else { os << "INVALID"; } return os; } Mod Mod::add(Mod that) const { if (is_invalid() || that.is_invalid()) { return Mod(0, 0); } if (mod != that.mod) { return Mod(0, 0); } return Mod(val + that.val, mod); } Mod Mod::multiply(Mod that) const { if (is_invalid() || that.is_invalid()) { return Mod(0, 0); } if (mod != that.mod) { return Mod(0, 0); } return Mod(val * that.val, mod); } Mod Mod::inverse() const { long d, a, b; if (is_invalid()) { return Mod(0, 0); } d = gcd(val, mod, a, b); if (d > 1) { return Mod(0, 0); // no reciprocal if gcd(v, x) != 1 } return Mod(a, mod); } Mod Mod::pow(long k) const { if (is_invalid()) { return Mod(0, 0); // invalid is forever } // negative exponent: reciprocal and try again if (k < 0) { return (inverse()).pow(-k); } // zero exponent: return 1 if (k == 0) { return Mod(1, mod); } // exponent equal to 1: return self if (k == 1) { return *this; } // even exponent: return (m^(k/2))^2 if (k % 2 == 0) { Mod tmp = pow(k/2); return tmp * tmp; } // odd exponent: return (m^((k-1)/2))^2 * m Mod tmp = pow((k - 1)/2); return tmp * tmp * (*this); }
ernestyalumni/CompPhys
Cpp/math/09-ModularArithmetic/Mod.cpp
C++
apache-2.0
3,118
/* * Copyright 2016-2022 Talsma ICT * * 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 nl.talsmasoftware.umldoclet.issues; import nl.talsmasoftware.umldoclet.UMLDoclet; import nl.talsmasoftware.umldoclet.util.TestUtil; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.File; import java.util.Optional; import java.util.spi.ToolProvider; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; public class Bug79GenericsAsMarkupTest { private static final String packageAsPath = Bug79GenericsAsMarkupTest.class.getPackageName().replace('.', '/'); private static final File outputdir = new File("target/issues/79"); private static String classUml; public <U> Optional<U> underlineMarkup() { return Optional.empty(); } public <I> Optional<I> italicMarkup() { return Optional.empty(); } public <B> Optional<B> boldMarkup() { return Optional.empty(); } @BeforeAll public static void createJavadoc() { String classAsPath = packageAsPath + '/' + Bug79GenericsAsMarkupTest.class.getSimpleName(); assertThat("Javadoc result", ToolProvider.findFirst("javadoc").get().run( System.out, System.err, "-d", outputdir.getPath(), "-doclet", UMLDoclet.class.getName(), "-quiet", "-createPumlFiles", "src/test/java/" + Bug79GenericsAsMarkupTest.class.getName().replace('.', '/') + ".java" ), is(0)); classUml = TestUtil.read(new File(outputdir, classAsPath + ".puml")); } @Test public void testNoMarkup() { assertThat(classUml, not(containsString("Optional<U>"))); assertThat(classUml, not(containsString("Optional<I>"))); assertThat(classUml, not(containsString("Optional<B>"))); String stripped = classUml.replace('\u200B', '?'); // Make zero-width-space 'visible' for test assertThat(stripped, containsString("Optional<?U>")); assertThat(stripped, containsString("Optional<?I>")); assertThat(stripped, containsString("Optional<?B>")); } }
talsma-ict/umldoclet
src/test/java/nl/talsmasoftware/umldoclet/issues/Bug79GenericsAsMarkupTest.java
Java
apache-2.0
2,795
package trendli.me.makhana.gameserver.net.listener.game; import java.util.Arrays; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import trendli.me.makhana.common.data.Session; import trendli.me.makhana.common.entities.ComponentUtil; import trendli.me.makhana.common.entities.components.LocationTrait; import trendli.me.makhana.common.entities.components.MoveableTrait; import trendli.me.makhana.common.entities.components.Player; import trendli.me.makhana.common.entities.components.StaticTrait; import trendli.me.makhana.common.entities.components.WorldTrait; import trendli.me.makhana.common.net.msg.EntityActionRequest; import trendli.me.makhana.common.net.msg.EntityCreationRequest; import trendli.me.makhana.common.net.msg.EntityDeletionRequest; import trendli.me.makhana.common.net.msg.EntityResponse; import trendli.me.makhana.gameserver.net.GameServerManager; import com.jme3.network.HostedConnection; import com.jme3.network.Message; import com.jme3.network.MessageListener; import com.simsilica.es.ComponentFilter; import com.simsilica.es.CreatedBy; import com.simsilica.es.Entity; import com.simsilica.es.EntityComponent; import com.simsilica.es.EntityData; import com.simsilica.es.EntityId; import com.simsilica.es.filter.FieldFilter; /** * * @author Elliott Butler * */ public class EntityRequestListener implements MessageListener< HostedConnection > { /** * The logger for this class. */ private final static Logger logger = Logger.getLogger( EntityRequestListener.class.getName( ) ); /** * The server manager */ private GameServerManager manager; /** * The default constructor accepts the server's manager. * * @param manager * the server manager */ public EntityRequestListener( GameServerManager manager ) { this.manager = manager; } @Override public void messageReceived( HostedConnection source, Message message ) { EntityData entityData = manager.getEntityData( ); if ( message instanceof EntityCreationRequest ) { EntityCreationRequest entityMsg = ( EntityCreationRequest ) message; logger.log( Level.INFO, "Received an EntityCreationRequest from " + source.getAddress( ) + ", " + ( entityMsg.getLocation( ) != null ? entityMsg.getLocation( ) : "null" ) + ", " + Arrays.toString( entityMsg.getComponents( ) ) ); if ( entityMsg.getLocation( ) != null ) { LocationTrait location = entityMsg.getLocation( ); if ( location.getTile( ) != null ) { EntityId ownerId = ComponentUtil.getOwner( entityData, location.getTile( ) ); if ( ownerId != null ) { Entity owner = entityData.getEntity( ownerId, Player.class ); if ( owner != null && owner.get( Player.class ) != null ) { Session session = manager.getSessionManager( ).get( source ); if ( owner.get( Player.class ).getSession( ).equals( session ) ) { /* * TODO: More validation, need to check that all * EntityComponents passed are valid */ boolean isBuilding = false; boolean isUnit = false; for ( EntityComponent e : entityMsg.getComponents( ) ) { if ( e instanceof MoveableTrait ) { isUnit = true; } if ( e instanceof StaticTrait ) { isBuilding = true; } } // As of now, clients can only build // buildings or units if ( isBuilding || isUnit ) { ComponentFilter< LocationTrait > locFilter = FieldFilter.create( LocationTrait.class, "tile", location.getTile( ) ); Set< EntityId > targetIdSet = entityData.findEntities( locFilter, LocationTrait.class ); int unitCount = ComponentUtil.countUnits( entityData, targetIdSet ); int buildingCount = ComponentUtil.countBuildings( entityData, targetIdSet ); System.out.println( String.format( "Unit( %s ): %d, Building( %s ): %d", isUnit, unitCount, isBuilding, buildingCount ) ); WorldTrait wt = entityData.getComponent( manager.getTheWorld( ), WorldTrait.class ); if ( !isBuilding ) { if ( unitCount < 6 ) { // TODO: Need to check that we // have the required buildings // and they are not currently // being built EntityId newEntityId = entityData.createEntity( ); entityData.setComponent( newEntityId, new LocationTrait( location.getTile( ), ComponentUtil.getOpenUnitPosition( entityData, targetIdSet ) ) ); entityData.setComponents( newEntityId, entityMsg.getComponents( ) ); ComponentUtil.entityParturition( entityData, newEntityId, entityMsg.getComponents( ), wt.getCurrentTurn( ) ); source.send( new EntityResponse( newEntityId, EntityCreationRequest.class.getSimpleName( ) + entityData.getEntities( LocationTrait.class ).size( ), true ) ); return; } } else { if ( buildingCount < 6 ) { EntityId newEntityId = entityData.createEntity( ); entityData.setComponent( newEntityId, new LocationTrait( location.getTile( ), ComponentUtil.getOpenBuildingPosition( entityData, targetIdSet ) ) ); entityData.setComponents( newEntityId, entityMsg.getComponents( ) ); ComponentUtil.entityParturition( entityData, newEntityId, entityMsg.getComponents( ), wt.getCurrentTurn( ) ); source.send( new EntityResponse( newEntityId, EntityCreationRequest.class.getSimpleName( ) + entityData.getEntities( LocationTrait.class ).size( ), true ) ); return; } } } } } } } } source.send( new EntityResponse( null, EntityCreationRequest.class.getSimpleName( ) + " Unfinished", false ) ); return; } else if ( message instanceof EntityDeletionRequest ) { EntityDeletionRequest entityMsg = ( EntityDeletionRequest ) message; logger.log( Level.INFO, "Received an EntityDeletionRequest from " + source.getAddress( ) + ", " + entityMsg.getEntityId( ) ); if ( entityMsg.getEntityId( ) != null ) { Entity theEntity = entityData.getEntity( entityMsg.getEntityId( ), CreatedBy.class, LocationTrait.class ); if ( theEntity != null ) { // TODO: EntityId ownerId = null; if ( ownerId == null && theEntity.get( CreatedBy.class ) != null ) { ownerId = theEntity.get( CreatedBy.class ).getCreatorId( ); } if ( ownerId == null && theEntity.get( LocationTrait.class ) != null ) { LocationTrait location = theEntity.get( LocationTrait.class ); if ( location.getTile( ) != null ) { Entity tile = entityData.getEntity( location.getTile( ), CreatedBy.class ); if ( tile != null && tile.get( CreatedBy.class ) != null ) { ownerId = tile.get( CreatedBy.class ).getCreatorId( ); } } } if ( ownerId != null ) { Entity owner = entityData.getEntity( ownerId, Player.class ); if ( owner != null && owner.get( Player.class ) != null ) { Session session = manager.getSessionManager( ).get( source ); if ( owner.get( Player.class ).getSession( ).equals( session ) ) { entityData.removeEntity( entityMsg.getEntityId( ) ); source.send( new EntityResponse( entityMsg.getEntityId( ), EntityDeletionRequest.class.getSimpleName( ), true ) ); return; } } } } } source.send( new EntityResponse( entityMsg.getEntityId( ), EntityDeletionRequest.class.getSimpleName( ), false ) ); } else if ( message instanceof EntityActionRequest ) { EntityActionRequest entityMsg = ( EntityActionRequest ) message; logger.log( Level.INFO, "Received an EntityActionRequest from " + source.getAddress( ) ); if ( entityMsg.getEntityId( ) != null ) { System.out.println( "EntityActionRequest: " + !ComponentUtil.inAction( entityData, entityMsg.getEntityId( ) ) + ", " + ComponentUtil.isUnit( entityData, entityMsg.getEntityId( ) ) ); if ( !ComponentUtil.inAction( entityData, entityMsg.getEntityId( ) ) ) { if ( ComponentUtil.isUnit( entityData, entityMsg.getEntityId( ) ) ) { EntityId ownerId = ComponentUtil.getOwner( entityData, entityMsg.getEntityId( ) ); System.out.println( "EntityActionRequest: owner: " + ownerId ); if ( ownerId != null ) { // TODO: Validate movement since the user made it // Check movetrait's date isn't more than 2 seconds // ago // Check movetrait's duration is valid // Check that the next tile is actually a neighbor entityData.setComponent( entityMsg.getEntityId( ), entityMsg.getAction( ) ); source.send( new EntityResponse( null, EntityActionRequest.class.getSimpleName( ) + " Unfinished", true ) ); return; } } } } source.send( new EntityResponse( null, EntityActionRequest.class.getSimpleName( ) + " Unfinished", false ) ); return; // TODO: } } }
elliottmb/makhana
gameserver/src/main/java/trendli/me/makhana/gameserver/net/listener/game/EntityRequestListener.java
Java
apache-2.0
13,005
import React from 'react' import PropTypes from 'prop-types' import Search from '../components/Search//Search' import FacetQueryParms from '../modules/FacetQueryParams' import HoneycombURL from '../modules/HoneycombURL' const SearchPage = ({ match, children }) => { const queryParams = new URLSearchParams(window.location.search) return ( <div> <Search collection={HoneycombURL() + '/v1/collections/' + match.params.collectionID} hits={HoneycombURL() + '/v1/collections/' + match.params.collectionID + '/search'} searchTerm={queryParams.get('q') || ''} sortTerm={queryParams.get('sort')} facet={FacetQueryParms()} matchMode={queryParams.get('mode')} field={queryParams.get('field')} start={parseInt(queryParams.get('start'), 10)} view={queryParams.get('view')} currentItem={queryParams.get('item')} /> {children} </div> ) } SearchPage.propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ collectionID: PropTypes.string, }), }), children: PropTypes.node, } export default SearchPage
ndlib/beehive
src/routes/SearchPage.js
JavaScript
apache-2.0
1,127
<?php if ( ! defined('EXT')) { exit('Invalid file request'); } /** * VWM Polls * * @package VWM Polls * @author Victor Michnowicz * @copyright Copyright (c) 2011 Victor Michnowicz * @license http://www.apache.org/licenses/LICENSE-2.0.html * @link http://github.com/vmichnowicz/vwm_polls */ // ----------------------------------------------------------------------------- /** * Make sure we are dealing with a (at least somewhat) valid hex color. If no color is provided, just output a default * color * * @access public * @param string User submitted hex color * @return string */ function hex_color($color) { if ($color) { // Remove all non alpha numeric characters $color = preg_replace('/[^a-zA-Z0-9]/', '', $color); // Color can be a max of six characters return substr($color, 0, 6); } // If no color is provided, return a random color else { return sprintf('%02X%02X%02X', mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); } } /** * Calculate percentages for poll options * * @access public * @param array Poll options * @param int Total number of votes in this poll * @return array */ function calculate_results($options, $total_votes) { $options = array_values($options); foreach($options as &$option) { if ($total_votes) { $percent_decimal = $option['votes'] / $total_votes; $option['percent_decimal'] = $percent_decimal; $option['percent'] = round($percent_decimal * 100, 2); } else { $option['percent_decimal'] = 0; $option['percent'] = 0; } } return $options; } /** * Generate a Google chart * * This function is duplicated in ft.vwm_polls.php * * @param array Poll settings * @param array Poll options * @return string */ function google_chart($poll_settings, $poll_options) { // Google charts URL $data = 'http://chart.apis.google.com/chart?'; // Chart size $data .= 'chs=' . $poll_settings['results_chart_width'] . 'x' . $poll_settings['results_chart_height']; // Display chart labels $labels = isset($poll_settings['results_chart_labels']) && $poll_settings['results_chart_labels']; // Chart type switch($poll_settings['results_chart_type']) { case 'pie': $data .= AMP . 'cht=p'; $chds = NULL; // Don't need this for pie charts break; case 'bar': $data .= AMP . 'chbh=a'; $data .= AMP . 'cht=bhs'; $data .= AMP . 'chg=10,0,5,5'; //$data .= AMP . 'chxr=0,100'; $chds = AMP . 'chds=0,'; break; } $most_votes = 0; // Chart data $chd = array(); // Chart data $chdl = array(); // Chart labels $chco = array(); // Chart colors foreach ($poll_options as $option) { $votes = $option['votes']; $most_votes = $votes > $most_votes ? $votes : $most_votes; $chdl[ $option['id'] ] = urlencode($option['text']); $chd[ $option['id'] ] = $votes; $chco[ $option['id'] ] = $option['color']; } $chd = implode(',', $chd); $chdl = implode('|', $chdl); $chco = implode('|', $chco); $data .= AMP . 'chd=t:' . $chd; if ($labels) { $data .= AMP . 'chdl=' . $chdl; } $data .= AMP . 'chf=bg,s,00000000'; $data .= AMP . 'chco=' . $chco; $data .= $chds ? AMP . $chds . $most_votes : NULL; return $data; } // EOF
vmichnowicz/vwm_polls
system/expressionengine/third_party/vwm_polls/helpers/vwm_polls_helper.php
PHP
apache-2.0
3,179
/******************************************************************************* * Copyright 2014 Manuel Mauky * * 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 de.saxsys.mvvmfx.utils.sizebinding; import static org.assertj.core.api.Assertions.assertThat; import javafx.beans.property.ReadOnlyDoubleWrapper; import javafx.scene.control.Control; import javafx.scene.control.ScrollPane; import javafx.scene.image.ImageView; import javafx.scene.layout.Region; import javafx.scene.shape.Rectangle; import org.junit.Before; import org.junit.runner.RunWith; import org.mockito.internal.util.reflection.Whitebox; import de.saxsys.javafx.test.JfxRunner; @RunWith(JfxRunner.class) public abstract class SizeBindingsBuilderTestBase { protected static final double SIZEVAL = 100d; protected Region fromRegion; protected Control fromControl; protected Rectangle fromRectangle; protected ImageView fromImageView; @Before public void setup() { fromRegion = new Region(); mockSize(fromRegion); fromControl = new ScrollPane(); mockSize(fromControl); fromRectangle = new Rectangle(); mockSize(fromRectangle); fromImageView = new ImageView(); fromImageView.setFitWidth(SIZEVAL); fromImageView.setFitHeight(SIZEVAL); } /** * Mock the internal storage of the width and height. This is a workaround because we can't use PowerMock in this * case due to conflicts with Javafx 8 initialization of controls. */ private void mockSize(Object object) { Whitebox.setInternalState(object, "width", new ReadOnlyDoubleWrapper(SIZEVAL)); Whitebox.setInternalState(object, "height", new ReadOnlyDoubleWrapper(SIZEVAL)); } protected void assertCorrectSize(Rectangle rectangle) { assertCorrectHeight(rectangle); assertCorrectWidth(rectangle); } protected void assertCorrectSize(Control control) { assertCorrectHeight(control); assertCorrectWidth(control); } protected void assertCorrectSize(Region region) { assertCorrectHeight(region); assertCorrectWidth(region); } protected void assertCorrectSize(ImageView imageView) { assertCorrectHeight(imageView); assertCorrectWidth(imageView); } protected void assertCorrectHeight(Rectangle rectangle) { assertThat(rectangle.getHeight()).isEqualTo(SIZEVAL); } protected void assertCorrectHeight(Control control) { assertThat(control.getMaxHeight()).isEqualTo(SIZEVAL); assertThat(control.getMinHeight()).isEqualTo(SIZEVAL); } protected void assertCorrectHeight(Region region) { assertThat(region.getMaxHeight()).isEqualTo(SIZEVAL); assertThat(region.getMinHeight()).isEqualTo(SIZEVAL); } protected void assertCorrectHeight(ImageView imageView) { assertThat(imageView.getFitHeight()).isEqualTo(SIZEVAL); } protected void assertCorrectWidth(Rectangle rectangle) { assertThat(rectangle.getWidth()).isEqualTo(SIZEVAL); } protected void assertCorrectWidth(Control control) { assertThat(control.getMaxWidth()).isEqualTo(SIZEVAL); assertThat(control.getMinWidth()).isEqualTo(SIZEVAL); } protected void assertCorrectWidth(Region region) { assertThat(region.getMaxWidth()).isEqualTo(SIZEVAL); assertThat(region.getMinWidth()).isEqualTo(SIZEVAL); } protected void assertCorrectWidth(ImageView imageView) { assertThat(imageView.getFitWidth()).isEqualTo(SIZEVAL); } }
mthiele/mvvmFX
mvvmfx-utils/src/test/java/de/saxsys/mvvmfx/utils/sizebinding/SizeBindingsBuilderTestBase.java
Java
apache-2.0
3,918
/* * Copyright 2014-15 Dilip Kumar * 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.dilipkumarg.qb.models; import com.dilipkumarg.qb.DeleteQueryBuilder; import com.dilipkumarg.qb.InsertQueryBuilder; import com.dilipkumarg.qb.SelectQueryBuilder; import com.dilipkumarg.qb.UpdateQueryBuilder; /** * @author Dilip Kumar. * @since 1/7/14 */ public abstract class AbstractSqlTable implements SqlTable { private static final String AS = " "; protected String tableName; protected String tableAlias; protected AbstractSqlTable(String tableName, String tableAlias) { this.tableName = tableName; this.tableAlias = tableAlias; } public AbstractSqlTable(String tableName) { this(tableName, tableName.toLowerCase()); } @Override public String getTableName() { return tableName; } @Override public String getTableAlias() { return tableAlias; } @Override public String getTableNameWithAlias() { return getTableName() + AS + getTableAlias(); } @Override public String getTableName(boolean withAlias) { return withAlias ? getTableNameWithAlias() : getTableName(); } @Override public TableColumn createTableColumn(String fieldName) { return new TableColumn(fieldName, this); } /** * Creates new {@link com.dilipkumarg.qb.SelectQueryBuilder} for this {@link com.wavemaker.gateway * .commons.qb.models.SqlTable} * * @return {@link com.dilipkumarg.qb.SelectQueryBuilder} object. */ public SelectQueryBuilder select() { return new SelectQueryBuilder(this); } /** * Creates new {@link com.dilipkumarg.qb.InsertQueryBuilder} for this {@link com.wavemaker.gateway * .commons.qb.models.SqlTable} * * @return {@link com.dilipkumarg.qb.InsertQueryBuilder} object. */ public InsertQueryBuilder insert() { return new InsertQueryBuilder(this); } /** * Creates new {@link com.dilipkumarg.qb.UpdateQueryBuilder} for this {@link com.wavemaker.gateway * .commons.qb.models.SqlTable} * * @return {@link com.dilipkumarg.qb.UpdateQueryBuilder} object. */ public UpdateQueryBuilder update() { return new UpdateQueryBuilder(this); } /** * Creates new {@link com.dilipkumarg.qb.DeleteQueryBuilder} for this {@link com.wavemaker.gateway * .commons.qb.models.SqlTable} * * @return {@link com.dilipkumarg.qb.DeleteQueryBuilder} object. */ public DeleteQueryBuilder delete() { return new DeleteQueryBuilder(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AbstractSqlTable)) return false; AbstractSqlTable that = (AbstractSqlTable) o; if (!tableAlias.equals(that.tableAlias)) return false; if (!tableName.equals(that.tableName)) return false; return true; } @Override public int hashCode() { int result = tableName.hashCode(); result = 31 * result + tableAlias.hashCode(); return result; } }
gdilipkumar/querybuilder
src/main/java/com/dilipkumarg/qb/models/AbstractSqlTable.java
Java
apache-2.0
3,674
// Package diskconfig provides information and interaction with the the Disk // Config extension that works with the OpenStack Compute service. package diskconfig
alex/gophercloud
openstack/compute/v2/extensions/diskconfig/doc.go
GO
apache-2.0
163
package net.wickborn.notebark; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.view.MenuItem; public class SettingsActivity extends PreferenceActivity { public static final String PREF_KEY_SUBJECT = "pref_key_subject"; public static final String PREF_KEY_USERNAME = "pref_key_username"; public static final String PREF_KEY_PASSWORD = "pref_key_password"; public static final String PREF_KEY_SERVER = "pref_key_server"; public static final String PREF_KEY_SENDER = "pref_key_sender"; public static final String PREF_KEY_RECIPIENT = "pref_key_recipient"; /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); preference.setSummary(stringValue); return true; } }; /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference(SettingsActivity.PREF_KEY_SERVER)); bindPreferenceSummaryToValue(findPreference(SettingsActivity.PREF_KEY_USERNAME)); bindPreferenceSummaryToValue(findPreference(SettingsActivity.PREF_KEY_SENDER)); bindPreferenceSummaryToValue(findPreference(SettingsActivity.PREF_KEY_RECIPIENT)); bindPreferenceSummaryToValue(findPreference(SettingsActivity.PREF_KEY_SUBJECT)); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { startActivity(new Intent(getActivity(), SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } } }
fawick/notebark
app/src/main/java/net/wickborn/notebark/SettingsActivity.java
Java
apache-2.0
4,227
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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 { shallow } from 'enzyme'; import Immutable from 'immutable'; import WorkersGrid, { WORKER_STATE_TO_COLOR as gridColors } from './WorkersGrid'; describe('WorkersGrid', () => { let minimalProps; let commonProps; beforeEach(() => { minimalProps = { entity: Immutable.fromJS({ workersSummary: { active: 0, pending: 0, disconnected: 0, decommissioning: 0 } }) }; commonProps = { ...minimalProps, entity: Immutable.fromJS({ workersSummary: { active: 1, pending: 2, disconnected: 3, decommissioning: 4 } }) }; }); it('should render with minimal props without exploding', () => { const wrapper = shallow(<WorkersGrid {...minimalProps}/>); expect(wrapper).to.have.length(1); }); describe('getGridItemSize', () => { let wrapper; let instance; beforeEach(() => { wrapper = shallow(<WorkersGrid {...minimalProps}/>); instance = wrapper.instance(); }); it('should return 15 when worker\'s count less then 40', () => { const gridItems = [ { workerState: 'active', value: 39 }, { workerState: 'pending', value: 1 }, { workerState: 'provisioning', value: 0 }, { workerState: 'decommissioning', value: 0 } ]; expect(instance.getGridItemSize(gridItems)).to.be.eql(15); }); it('should return 9 when worker\'s count less more then 40 but less then 175', () => { let gridItems = [ { workerState: 'active', value: 39 }, { workerState: 'pending', value: 2 }, { workerState: 'disconnected', value: 0 }, { workerState: 'decommissioning', value: 0 } ]; expect(instance.getGridItemSize(gridItems)).to.be.eql(9); gridItems = [ { workerState: 'active', value: 174 }, { workerState: 'pending', value: 1 }, { workerState: 'disconnected', value: 0 }, { workerState: 'decommissioning', value: 0 } ]; expect(instance.getGridItemSize(gridItems)).to.be.eql(9); }); it('should return 5 when worker\'s count less more then 175', () => { const gridItems = [ { workerState: 'active', value: 175 }, { workerState: 'pending', value: 1 }, { workerState: 'disconnected', value: 0 }, { workerState: 'decommissioning', value: 0 } ]; expect(instance.getGridItemSize(gridItems)).to.be.eql(5); }); }); describe('renderWorkersGrid', () => { let wrapper; beforeEach(() => { wrapper = shallow(<WorkersGrid {...minimalProps}/>); }); it('should render no items by default', () => { expect(wrapper.find('.grid-list').children()).to.have.length(0); }); it('should render same quantity of squares as total workers size', () => { wrapper.setProps(commonProps); expect(wrapper.find('.grid-list').children()).to.have.length(10); }); it('should render squares in following order: active, pending, provisioning, decommissioning', () => { wrapper.setProps(commonProps); const allGridItems = wrapper.find('.grid-list').children(); const getChildrenInRange = (start, end) => { const range = []; allGridItems.forEach((item, i) => { if (i < start || i >= end) { return; } range.push(item); }); return range; }; const getItemsColor = (children) => { return Immutable.Set(children.map((child) => child.props('style').style.background)).toJS(); }; const active = getChildrenInRange(0, 1); const pending = getChildrenInRange(1, 3); const disconnected = getChildrenInRange(3, 6); const decommissioning = getChildrenInRange(6, 9); expect(getItemsColor(active)).to.be.eql([gridColors.active]); expect(getItemsColor(pending)).to.be.eql([gridColors.pending]); expect(getItemsColor(disconnected)).to.be.eql([gridColors.disconnected]); expect(getItemsColor(decommissioning)).to.be.eql([gridColors.decommissioning]); }); }); });
dremio/dremio-oss
dac/ui/src/pages/AdminPage/subpages/Provisioning/components/WorkersGrid-spec.js
JavaScript
apache-2.0
4,743
(function($) { $.Arte.Toolbar.ButtonWithDialog = function(toolbar, buttonName, config) { var me = this; $.Arte.Toolbar.Button.call(this, toolbar, buttonName, config); var dialogClasses = $.Arte.Toolbar.configuration.classes.dialog; this.executeCommand = function() { if (me.isEnabled()) { me.showPopup(); } }; this.getOkCancelControl = function() { var wrapper = $("<div>").addClass(dialogClasses.okCancel); $("<a>").attr("href", "#").addClass(dialogClasses.button + " ok").html("&#x2713").appendTo(wrapper); $("<a>").attr("href", "#").addClass(dialogClasses.button + " cancel").html("&#x2717").appendTo(wrapper); return wrapper; }; this.showPopup = function() { var dialogContainer = $("." + dialogClasses.container); var contentWrapper = $("<div>").addClass(dialogClasses.contentWrapper).appendTo(dialogContainer); contentWrapper.append(me.getDialogContent()); contentWrapper.append(me.getOkCancelControl()); dialogContainer.on("mousedown ", function(e) { e.stopPropagation(); }); var savedSelection = rangy.saveSelection(); me.addContent(); contentWrapper.find(".ok").on("click", function() { rangy.restoreSelection(savedSelection); me.onOk(); me.closePopup(); }); contentWrapper.find(".cancel").on("click", function() { rangy.restoreSelection(savedSelection); me.closePopup(); }); dialogContainer.show({ duration: 200, complete: function() { contentWrapper.css("margin-top", -1 * contentWrapper.height() / 2); } }); }; this.closePopup = function() { var dialogContainer = $("." + dialogClasses.container); dialogContainer.children().each(function() { this.remove(); }); dialogContainer.hide(); }; return me; }; })(jQuery); (function() { $.Arte.Toolbar.InsertLink = function(toolbar, buttonName, config) { var dialogClasses = $.Arte.Toolbar.configuration.classes.dialog; var insertLinkClasses = dialogClasses.insertLink; $.Arte.Toolbar.ButtonWithDialog.call(this, toolbar, buttonName, config); var insertContent = function(contentToInsert) { $.each(toolbar.selectionManager.getSelectedEditors(), function() { this.insert.call(this, { commandValue: contentToInsert }); }); }; this.getDialogContent = function() { var textToShow = $("<div>").addClass(dialogClasses.insertLink.textToShow); $("<span>").html("Text to Show: ").addClass(dialogClasses.label).appendTo(textToShow); $("<input>").addClass(insertLinkClasses.input + " textToShow").attr({ type: "text" }).appendTo(textToShow); var urlInput = $("<div>").addClass(dialogClasses.insertLink.urlInput); $("<span>").html("Url: ").addClass(dialogClasses.label).appendTo(urlInput); $("<input>").addClass(insertLinkClasses.input + " url").attr({ type: "text" }).appendTo(urlInput); var dialogContent = $("<div>").addClass(dialogClasses.content).append(textToShow).append(urlInput); return dialogContent; }; this.onOk = function() { var textToShow = $("." + dialogClasses.container + " ." + dialogClasses.insertLink.textToShow + " input").val(); var url = $("." + dialogClasses.container + " ." + dialogClasses.insertLink.urlInput + " input").val(); if (url) { var html = $("<a>").attr("href", url).html(textToShow || url); insertContent(html.get(0).outerHTML); } }; this.addContent = function() { $("." + dialogClasses.container + " .textToShow").val(rangy.getSelection().toHtml()); }; }; })(jQuery); (function() { $.Arte.Toolbar.InsertImage = function(toolbar, buttonName, config) { var dialogClasses = $.Arte.Toolbar.configuration.classes.dialog; var insertLinkClasses = dialogClasses.insertLink; $.Arte.Toolbar.ButtonWithDialog.call(this, toolbar, buttonName, config); var insertContent = function(contentToInsert) { $.each(toolbar.selectionManager.getSelectedEditors(), function() { this.insert.call(this, { commandValue: contentToInsert }); }); }; this.getDialogContent = function() { var dialogContent = $("<div>").addClass("input-prepend input-append"); $("<span>").html("Text to Show: ").addClass(insertLinkClasses.label).appendTo(dialogContent); $("<input>").addClass(insertLinkClasses.input + " textToShow").attr({ type: "text" }).appendTo(dialogContent).css({ height: "auto" }); $("<span>").html("Url: ").addClass(insertLinkClasses.label).appendTo(dialogContent); $("<input>").addClass(insertLinkClasses.input + " url").attr({ type: "text" }).appendTo(dialogContent).css({ height: "auto" }); return dialogContent; }; this.onOk = function() { var contentToInsert = $("." + dialogClasses.container + " .url").val(); if (contentToInsert) { var html = $("<img>").attr("src", contentToInsert); insertContent(html.get(0).outerHTML); } }; this.addContent = function() { $("." + dialogClasses.container + " .textToShow").val(rangy.getSelection().toHtml()); }; }; })(jQuery);
vistaprint/ArteJS
src/toolbar/Buttons/ButtonWithDialog.js
JavaScript
apache-2.0
6,093
/* * Copyright 2008 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created on May 19, 2008 */ package org.drools.rule; import java.util.List; import java.util.Map; /** * FactType declarations are fact definitions (like classes) that * are managed alongside the rules. * You then communicate with the rulebase/knowledge base by using instances created by this. * There are utility set and get methods on this, as well as in the FieldAccessors. * * The Object that is used is a javabean (which was generated by the rules). You can also use reflection on it as normal. * * @author etirelli */ public interface FactType extends java.io.Externalizable { public String getName(); public List<FactField> getFields(); public FactField getField(String name); public Class< ? > getFactClass(); /** * Create a new fact based on the declared fact type. * This object will normally be a javabean. */ public Object newInstance() throws InstantiationException, IllegalAccessException; /** * Set the value of the field on a dynamic fact. */ public void set(Object bean, String field, Object value); /** * get the value of the specified field on the dynamic fact. */ public Object get(Object bean, String field); /** * Get a map of the fields and their values for the bean. */ public Map<String, Object> getAsMap(Object bean); /** * Set the values of the bean from a map. */ public void setFromMap(Object bean, Map<String, Object> values); }
bobmcwhirter/drools
drools-core/src/main/java/org/drools/rule/FactType.java
Java
apache-2.0
2,126
webpackHotUpdate(0,[ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function($) {var React = __webpack_require__(2); var ReactDOM = __webpack_require__(158); var bootstrap = __webpack_require__(159); var pullRight = { float: "right", marginRight: "5%" }; var footStyle = { position: "absolute", bottom: "0", height: "50px", width: "100%", borderTop: "1px solid #ccc" }; var ContactBox = React.createClass({displayName: "ContactBox", LoadContactsFromServer: function(){ $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data){ this.setState({data: data}); }.bind(this), error: function(xhr, status, err){ console.log(this.props.url, status, err.toString()); }.bind(this) }); }, getInitialState: function() { return {data: []}; }, componentDidMount: function(){ this.LoadContactsFromServer(); }, render: function(){ return ( React.createElement("div", null, React.createElement(ContactHeader, null), React.createElement(ContactList, {data: this.state.data}), React.createElement(ContactFoot, null) ) ); } }); var ContactHeader = React.createClass({displayName: "ContactHeader", render: function(){ return ( React.createElement(bootstrap.Navbar, {toggleNavKey: 0}, React.createElement(bootstrap.NavBrand, null, "G-Address"), React.createElement(bootstrap.CollapsibleNav, {eventKey: 0}, React.createElement(bootstrap.Nav, {navbar: true, right: true}, React.createElement(bootstrap.NavItem, {href: "/login", eventKey: 1}, "登录") ) ) ) ); } }); var ContactList = React.createClass({displayName: "ContactList", render: function(){ var contactNodes = this.props.data.map(function(contact, index){ return ( React.createElement(Contact, {key: index}, contact.name) ); }); return ( React.createElement(bootstrap.ListGroup, null, contactNodes ) ); } }); var Contact = React.createClass({displayName: "Contact", render: function(){ return ( React.createElement(bootstrap.ListGroupItem, {href: "#"}, this.props.children, React.createElement("span", null, React.createElement(bootstrap.Glyphicon, {glyph: "chevron-right", style: pullRight})) ) ); } }); var ContactFoot = React.createClass({displayName: "ContactFoot", render: function(){ return ( React.createElement("div", {style: footStyle} ) ); } }); ReactDOM.render(React.createElement(ContactBox, {url: "/contacts/data"}), document.getElementById("content")); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ } ])
JivaGzw/Gaddress
build/0.ce253bb41e20f52ec882.hot-update.js
JavaScript
apache-2.0
2,854
function updateScreenSize(size) { return { type: 'RECEIVE_SIZE', size }; } function setRenderer(renderer) { return { type: 'RECEIVE_RENDERER', renderer }; } function setCanvas(canvas) { return { type: 'RECEIVE_CANVAS', canvas }; } export default { updateScreenSize, setRenderer, setCanvas, };
eventbrite/cartogram
src/actions/core.js
JavaScript
apache-2.0
381
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Binary test_analyzer_client is a testing client that initiates a call // to a shipshape analyzer. It assumes that a shipshape analyzer service // has already been started at the specified ports package main import ( "flag" "io" "log" "strings" "github.com/golang/protobuf/proto" "github.com/google/shipshape/shipshape/util/file" "github.com/google/shipshape/shipshape/util/rpc/client" ctxpb "github.com/google/shipshape/shipshape/proto/shipshape_context_proto" rpcpb "github.com/google/shipshape/shipshape/proto/shipshape_rpc_proto" spb "github.com/google/shipshape/shipshape/proto/source_context_proto" ) var ( servicePort = flag.String("service_port", "localhost:10007", "Service port") filePaths = flag.String("files", "", "List of files (comma-separated)") projectName = flag.String("project_name", "quixotic-treat-519", "Project name of a Cloud project") hash = flag.String("hash", "master", "Hash in repo for Cloud project") categories = flag.String("categories", "", "Categories to trigger (comma-separated)") repoKind = flag.String("repo_kind", "LOCAL", "The repo kind (CLOUD or LOCAL)") repoBase = flag.String("repo_base", "/tmp", "The root of the repo to use, if LOCAL or the base directory to copy repo into if not LOCAL") volumeName = flag.String("volume_name", "/shipshape-workspace", "The name of the shipping_container volume") event = flag.String("event", "TestClient", "The name of the event to use") stage = flag.String("stage", "PRE_BUILD", "The stage to test, either PRE_BUILD or POST_BUILD") ) const ( cloudRepo = "CLOUD" local = "LOCAL" // TODO(supertri): Add GERRIT-ON-BORG when we implement for copying down ) // TODO(supertri): utility methods to create request protos shared with test_analyzer_client? func main() { flag.Parse() var root = "" var sourceContext *spb.SourceContext var err error switch *repoKind { case cloudRepo: sourceContext, root, err = file.SetupCloudRepo(*projectName, *hash, *repoBase, *volumeName) if err != nil { log.Fatalf("Failed to setup Cloud repo: %v", err) } case local: if *repoBase == "/tmp" { log.Fatal("Must specify the repo_base for local runs") } root = *repoBase default: log.Fatalf("Invalid repo kind %q", *repoKind) } var trigger = []string(nil) if len(*categories) > 0 { trigger = strings.Split(*categories, ",") } c := client.NewHTTPClient(*servicePort) var paths []string if *filePaths != "" { paths = strings.Split(*filePaths, ",") } var stageEnum ctxpb.Stage switch *stage { case "POST_BUILD": stageEnum = ctxpb.Stage_POST_BUILD case "PRE_BUILD": stageEnum = ctxpb.Stage_PRE_BUILD default: log.Fatalf("Invalid stage %q", *stage) } req := &rpcpb.ShipshapeRequest{ TriggeredCategory: trigger, ShipshapeContext: &ctxpb.ShipshapeContext{ FilePath: paths, SourceContext: sourceContext, RepoRoot: proto.String(root), }, Event: proto.String(*event), Stage: stageEnum.Enum(), } log.Println("About to call out to the shipshape service") rd := c.Stream("/ShipshapeService/Run", req) defer rd.Close() for { var msg rpcpb.ShipshapeResponse if err := rd.NextResult(&msg); err == io.EOF { break } else if err != nil { log.Fatalf("Error from call: %v", err) } log.Printf("result:\n\n%v\n", proto.MarshalTextString(&msg)) } log.Printf("Done.") }
google/shipshape
shipshape/test/test_shipshape_client.go
GO
apache-2.0
3,993
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.databasemigrationservice.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p/> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeReplicationTasksResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. * </p> */ private String marker; /** * <p> * A description of the replication tasks. * </p> */ private java.util.List<ReplicationTask> replicationTasks; /** * <p> * An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. * </p> * * @param marker * An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. */ public void setMarker(String marker) { this.marker = marker; } /** * <p> * An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. * </p> * * @return An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. */ public String getMarker() { return this.marker; } /** * <p> * An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. * </p> * * @param marker * An optional pagination token provided by a previous request. If this parameter is specified, the response * includes only records beyond the marker, up to the value specified by <code>MaxRecords</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeReplicationTasksResult withMarker(String marker) { setMarker(marker); return this; } /** * <p> * A description of the replication tasks. * </p> * * @return A description of the replication tasks. */ public java.util.List<ReplicationTask> getReplicationTasks() { return replicationTasks; } /** * <p> * A description of the replication tasks. * </p> * * @param replicationTasks * A description of the replication tasks. */ public void setReplicationTasks(java.util.Collection<ReplicationTask> replicationTasks) { if (replicationTasks == null) { this.replicationTasks = null; return; } this.replicationTasks = new java.util.ArrayList<ReplicationTask>(replicationTasks); } /** * <p> * A description of the replication tasks. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setReplicationTasks(java.util.Collection)} or {@link #withReplicationTasks(java.util.Collection)} if you * want to override the existing values. * </p> * * @param replicationTasks * A description of the replication tasks. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeReplicationTasksResult withReplicationTasks(ReplicationTask... replicationTasks) { if (this.replicationTasks == null) { setReplicationTasks(new java.util.ArrayList<ReplicationTask>(replicationTasks.length)); } for (ReplicationTask ele : replicationTasks) { this.replicationTasks.add(ele); } return this; } /** * <p> * A description of the replication tasks. * </p> * * @param replicationTasks * A description of the replication tasks. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeReplicationTasksResult withReplicationTasks(java.util.Collection<ReplicationTask> replicationTasks) { setReplicationTasks(replicationTasks); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMarker() != null) sb.append("Marker: ").append(getMarker()).append(","); if (getReplicationTasks() != null) sb.append("ReplicationTasks: ").append(getReplicationTasks()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeReplicationTasksResult == false) return false; DescribeReplicationTasksResult other = (DescribeReplicationTasksResult) obj; if (other.getMarker() == null ^ this.getMarker() == null) return false; if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false; if (other.getReplicationTasks() == null ^ this.getReplicationTasks() == null) return false; if (other.getReplicationTasks() != null && other.getReplicationTasks().equals(this.getReplicationTasks()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode()); hashCode = prime * hashCode + ((getReplicationTasks() == null) ? 0 : getReplicationTasks().hashCode()); return hashCode; } @Override public DescribeReplicationTasksResult clone() { try { return (DescribeReplicationTasksResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
aws/aws-sdk-java
aws-java-sdk-dms/src/main/java/com/amazonaws/services/databasemigrationservice/model/DescribeReplicationTasksResult.java
Java
apache-2.0
7,793
/** * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace IBM.Watson.DeveloperCloud.Utilities { /// <summary> /// This class wraps all constants. /// </summary> public static class Constants { /// <summary> /// All constant path variables liste here. Exp. Configuration file /// </summary> public static class Path { /// <summary> /// Configuration file name. /// </summary> public const string CONFIG_FILE = "/Config.json"; /// <summary> /// Cache folder to customize a parent folder for cache directory /// </summary> public static string CACHE_FOLDER = ""; //It needs to start with / /// <summary> /// Log folder to customize a parent folder for logs /// </summary> public static string LOG_FOLDER = ""; //It needs to start with / } /// <summary> /// All resources (files names under resource directory) used in the SDK listed here. Exp. Watson Logo /// </summary> public static class Resources { /// <summary> /// Watson icon. /// </summary> public const string WATSON_ICON = "watsonSpriteIcon-32x32"; /// <summary> /// Watson logo. /// </summary> public const string WATSON_LOGO = "watsonSpriteLogo-506x506"; } /// <summary> /// All string variables or string formats used in the SDK listed here. Exp. Quality Debug Format = Quality {0} /// </summary> public static class String { /// <exclude /> public const string VERSION = "watson-developer-cloud-unity-sdk-0.12.0"; /// <exclude /> public const string DEBUG_DISPLAY_QUALITY = "Quality: {0}"; } } }
scottdangelo/unity-sdk
Scripts/Utilities/Constants.cs
C#
apache-2.0
2,378
from testlink.testlinkerrors import TLResponseError class TestReporter(dict): def __init__(self, tls, testcases, *args, **kwargs): """This can be given one or more testcases, but they all must have the same project, plan, and platform.""" super(TestReporter, self).__init__(*args, **kwargs) self.tls = tls # handle single testcase self.testcases = testcases if isinstance(testcases, list) else [testcases] self._plan_testcases = None self.remove_non_report_kwargs() self._platformname_generated = False def remove_non_report_kwargs(self): self.buildname = self.pop('buildname') self.buildnotes = self.pop('buildnotes', "Created with automation.") def setup_testlink(self): """Call properties that may set report kwarg values.""" self.testprojectname self.testprojectid self.testplanid self.testplanname self.platformname self.platformid self.buildid def _get_project_name_by_id(self): if self.testprojectid: for project in self.tls.getProjects(): if project['id'] == self.testprojectid: return project['name'] def _projectname_getter(self): if not self.get('testprojectname') and self.testprojectid: self['testprojectname'] = self._get_project_name_by_id() return self.get('testprojectname') @property def testprojectname(self): return self._projectname_getter() def _get_project_id(self): tpid = self.get('testprojectid') if not tpid and self.testprojectname: self['testprojectid'] = self.tls.getProjectIDByName(self['testprojectname']) return self['testprojectid'] return tpid def _get_project_id_or_none(self): project_id = self._get_project_id() # If not found the id will return as -1 if project_id == -1: project_id = None return project_id @property def testprojectid(self): self['testprojectid'] = self._get_project_id_or_none() return self.get('testprojectid') @property def testplanid(self): return self.get('testplanid') @property def testplanname(self): return self.get('testplanname') @property def platformname(self): """Return a platformname added to the testplan if there is one.""" return self.get('platformname') @property def platformid(self): return self.get('platformid') @property def buildid(self): return self.get('buildid') @property def plan_tcids(self): if not self._plan_testcases: self._plan_testcases = set() tc_dict = self.tls.getTestCasesForTestPlan(self.testplanid) try: for _, platform in tc_dict.items(): for k, v in platform.items(): self._plan_testcases.add(v['full_external_id']) except AttributeError: # getTestCasesForTestPlan returns an empty list instead of an empty dict pass return self._plan_testcases def reportgen(self): """For use if you need to look at the status returns of individual reporting.""" self.setup_testlink() for testcase in self.testcases: yield self.tls.reportTCResult(testcaseexternalid=testcase, **self) def report(self): for _ in self.reportgen(): pass class AddTestReporter(TestReporter): """Add testcase to testplan if not added.""" def setup_testlink(self): super(AddTestReporter, self).setup_testlink() self.ensure_testcases_in_plan() def ensure_testcases_in_plan(self): # Get the platformid if possible or else addition will fail self.platformid for testcase in self.testcases: # Can't check if testcase is in plan_tcids, because that won't work if it's there, but of the wrong platform try: self.tls.addTestCaseToTestPlan( self.testprojectid, self.testplanid, testcase, self.get_latest_tc_version(testcase), platformid=self.platformid ) except TLResponseError as e: # Test Case version is already linked to Test Plan if e.code == 3045: pass else: raise def get_latest_tc_version(self, testcaseexternalid): return int(self.tls.getTestCase(None, testcaseexternalid=testcaseexternalid)[0]['version']) class AddTestPlanReporter(TestReporter): @property def testplanid(self): if not self.get('testplanid'): try: self['testplanid'] = self.tls.getTestPlanByName(self.testprojectname, self.testplanname)[0]['id'] except TLResponseError as e: # Name does not exist if e.code == 3033: self['testplanid'] = self.generate_testplanid() else: raise except TypeError: self['testplanid'] = self.generate_testplanid() return self['testplanid'] def generate_testplanid(self): """This won't necessarily be able to create a testplanid. It requires a planname and projectname.""" if 'testplanname' not in self: raise RuntimeError("Need testplanname to generate a testplan for results.") tp = self.tls.createTestPlan(self['testplanname'], self.testprojectname) self['testplanid'] = tp[0]['id'] return self['testplanid'] class AddPlatformReporter(TestReporter): @property def platformname(self): """Return a platformname added to the testplan if there is one.""" pn_kwarg = self.get('platformname') if pn_kwarg and self._platformname_generated is False: # If we try to create platform and catch platform already exists error (12000) it sometimes duplicates a # platformname try: self.tls.addPlatformToTestPlan(self.testplanid, pn_kwarg) except TLResponseError as e: if int(e.code) == 235: self.tls.createPlatform(self.testprojectname, pn_kwarg) self.tls.addPlatformToTestPlan(self.testplanid, pn_kwarg) else: raise self._platformname_generated = True return pn_kwarg @property def platformid(self): if not self.get('platformid'): self['platformid'] = self.getPlatformID(self.platformname) # This action is idempotent self.tls.addPlatformToTestPlan(self.testplanid, self.platformname) return self['platformid'] def getPlatformID(self, platformname, _firstrun=True): """ This is hardcoded for platformname to always be self.platformname """ platforms = self.tls.getTestPlanPlatforms(self.testplanid) for platform in platforms: if platform['name'] == platformname: return platform['id'] # Platformname houses platform creation as platform creation w/o a name isn't possible if not self.platformname: raise RuntimeError( "Couldn't find platformid for {}.{}, " "please provide a platformname to generate.".format(self.testplanid, platformname) ) if _firstrun is True: return self.getPlatformID(self.platformname, _firstrun=False) else: raise RuntimeError("PlatformID not found after generated from platformname '{}' " "in test plan {}.".format(self.platformname, self.testplanid)) class AddBuildReporter(TestReporter): @property def buildid(self): bid = self.get('buildid') if not bid or bid not in self.tls.getBuildsForTestPlan(self.testplanid): self['buildid'] = self._generate_buildid() return self.get('buildid') def _generate_buildid(self): r = self.tls.createBuild(self.testplanid, self.buildname, self.buildnotes) return r[0]['id'] class TestGenReporter(AddTestReporter, AddBuildReporter, AddTestPlanReporter, AddPlatformReporter, TestReporter): """This is the default generate everything it can version of test reporting. If you don't want to generate one of these values you can 'roll your own' version of this class with only the needed features that you want to generate. For example if you wanted to add platforms and/or tests to testplans, but didn't want to ever make a new testplan you could use a class like: `type('MyOrgTestGenReporter', (AddTestReporter, AddPlatformReporter, TestReporter), {})` Example usage with fake testlink server test and a manual project. ``` tls = testlink.TestLinkHelper('https://testlink.corp.com/testlink/lib/api/xmlrpc/v1/xmlrpc.php', 'devkeyabc123').connect(testlink.TestlinkAPIClient) tgr = TestGenReporter(tls, ['TEST-123'], testprojectname='MANUALLY_MADE_PROJECT', testplanname='generated', platformname='gend', buildname='8.fake', status='p') ``` """
orenault/TestLink-API-Python-client
src/testlink/testreporter.py
Python
apache-2.0
9,333