hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
d0198c1b03d1d554c246855094e67b058c5eb149 | 2,376 | package com.cunctator.cutedgems.core.init;
import com.cunctator.cutedgems.CutedGems;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Rarity;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import java.rmi.registry.Registry;
public class ItemInit {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, CutedGems.MOD_ID);
public static final RegistryObject<Item> CUTED_DIAMOND = ITEMS.register("cuted_diamond", () -> new Item(new Item.Properties().group(CutedGems.CUTED_GEMS_GROUP).rarity(Rarity.RARE)));
public static final RegistryObject<Item> CUTED_EMERALD = ITEMS.register("cuted_emerald", () -> new Item(new Item.Properties().group(CutedGems.CUTED_GEMS_GROUP).rarity(Rarity.UNCOMMON)));
public static final RegistryObject<Item> CUTED_LAPIS = ITEMS.register("cuted_lapis", () -> new Item(new Item.Properties().group(CutedGems.CUTED_GEMS_GROUP).rarity(Rarity.UNCOMMON)));
public static final RegistryObject<Item> CUTED_REDSTONE = ITEMS.register("cuted_redstone", () -> new Item(new Item.Properties().group(CutedGems.CUTED_GEMS_GROUP).rarity(Rarity.UNCOMMON)));
public static final RegistryObject<Item> HARDENED_DIAMOND = ITEMS.register("hardened_diamond", () -> new Item(new Item.Properties().group(CutedGems.CUTED_GEMS_GROUP)));
public static final RegistryObject<Item> HARDENED_DIAMOND_BLANK = ITEMS.register("hardened_diamond_blank", () -> new Item(new Item.Properties().group(CutedGems.CUTED_GEMS_GROUP)));
// /*
public static final RegistryObject<Item> HARDENED_DIAMOND_CUTERS = ITEMS.register("hardened_diamond_cuters", () -> new ItemHardenedDiamondCuters());
public static class ItemHardenedDiamondCuters extends Item {
public ItemHardenedDiamondCuters() {
super(new Properties().group(CutedGems.CUTED_GEMS_GROUP).maxDamage(256));
}
@Override
public boolean hasContainerItem() {
return true;
}
@Override
public ItemStack getContainerItem(ItemStack itemstack) {
ItemStack retval = new ItemStack(this);
retval.setDamage(itemstack.getDamage() + 1);
if (retval.getDamage() >= retval.getMaxDamage()) {
return ItemStack.EMPTY;
}
return retval;
}
}
//*/
}
| 47.52 | 192 | 0.774411 |
5c5caea03f0a70782c503882ed31073efe90a23c | 3,142 | /*
* MIT License
*
* Copyright (c) 2018 mnemotron
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package api.finance.yahoo.symbol.entity;
/**
* Symbol Result
*
* @author mnemotron
* @version 1.0.0
* @since 2018-01-01
*/
public class Symbol
{
private String symbol;
private String name;
private String exch;
private String type;
private String exchDisp;
private String typeDisp;
public Symbol()
{
this.symbol = new String();
this.name = new String();
this.exch = new String();
this.type = new String();
this.exchDisp = new String();
this.typeDisp = new String();
}
/**
* Yahoo Finance ticker ID
*
* @return Ticker ID
*/
public String getSymbol()
{
return symbol;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
/**
* Name of the asset
*
* @return Name
*/
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
/**
* Exchange
*
* @return Exchange
*/
public String getExch()
{
return exch;
}
public void setExch(String exch)
{
this.exch = exch;
}
/**
* Asset type i.e. "S"hare
*
* @return Asset Type
*/
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
/**
* Exchange display string
*
* @return Exchange display string
*/
public String getExchDisp()
{
return exchDisp;
}
public void setExchDisp(String exchDisp)
{
this.exchDisp = exchDisp;
}
/**
* Asset type display string
*
* @return Asset type display string
*/
public String getTypeDisp()
{
return typeDisp;
}
public void setTypeDisp(String typeDisp)
{
this.typeDisp = typeDisp;
}
public String toString()
{
return new String("{ " + "symbol:" + this.symbol + ", " + "name:" + this.name + ", " + "exch:" + this.exch + ", " + "type:" + this.type + ", " + "exchDisp:" + this.exchDisp + ", "
+ "typeDisp:" + this.typeDisp + " }");
}
}
| 21.087248 | 182 | 0.636537 |
f2bbc40e9cb15b6d62a4ff59fd75151c9167f231 | 645 | package jorn.hiel.urentracker.business.entities;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalTime;
/**
* @author Hiel Jorn
* @version 1.0
* <p>
* pojo to hold a day to-work hours
* </p>
*/
@Getter
@Setter
@Accessors(chain = true)
@Entity
@Table(name = "configdays")
@ToString
public class ConfigDay {
@Id
@Column(name = "dag")
private String dag;
@Column(name = "uren")
private LocalTime hours;
}
| 17.432432 | 48 | 0.713178 |
0680767d252ad12928d966ae8c686b49266e2aa0 | 5,629 | /*
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: shulie@shulie.io
* 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,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pamirs.tro.entity.domain.entity;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.pamirs.tro.common.util.LongToStringFormatSerialize;
/**
* 说明:业务链路管理实体类
*
* @author shulie
* @version V1.0
* @date: 2018年3月1日 下午12:49:55
*/
public class TLinkMnt extends BaseEntity {
private static final long serialVersionUID = 1L;
// @Field id : 业务链路管理id
@JsonSerialize(using = LongToStringFormatSerialize.class)
private long linkId;
// @Field linkName : 业务链路名称
private String linkName;
// @Field linkDesc : 链路说明
private String linkDesc;
//@Field aswanId : 阿斯旺链路id
private String aswanId;
// @Field linkRank : 链路等级
private String linkRank;
//@Field dictType : 字典类型
private String dictType;
// @Field principalNo : 负责人工号
private String principalNo;
// @Field bLinkOrder : 基础链路顺序(扩展字段)
private int bLinkOrder;
// @Field bLinkCheckStatus : 基础链路检测状态(扩展字段)(0代表失败红灯,1代表成功绿灯)
private String bLinkCheckStatus;
// @Field blinkBank : 基础链路等级(二级链路下有基础链路1,基础链路2等)
private int bLinkBank;
public TLinkMnt() {
super();
}
public int getbLinkOrder() {
return bLinkOrder;
}
public void setbLinkOrder(int bLinkOrder) {
this.bLinkOrder = bLinkOrder;
}
public String getbLinkCheckStatus() {
return bLinkCheckStatus;
}
public void setbLinkCheckStatus(String bLinkCheckStatus) {
this.bLinkCheckStatus = bLinkCheckStatus;
}
public int getBLinkBank() {
return bLinkBank;
}
public void setBLinkBank(int bLinkBank) {
this.bLinkBank = bLinkBank;
}
/**
* 2018年5月17日
*
* @return the linkId
* @author shulie
* @version 1.0
*/
public long getLinkId() {
return linkId;
}
/**
* 2018年5月17日
*
* @param linkId the linkId to set
* @author shulie
* @version 1.0
*/
public void setLinkId(long linkId) {
this.linkId = linkId;
}
/**
* 2018年5月17日
*
* @return the linkName
* @author shulie
* @version 1.0
*/
public String getLinkName() {
return linkName;
}
/**
* 2018年5月17日
*
* @param linkName the linkName to set
* @author shulie
* @version 1.0
*/
public void setLinkName(String linkName) {
this.linkName = linkName;
}
/**
* 2018年5月17日
*
* @return the linkDesc
* @author shulie
* @version 1.0
*/
public String getLinkDesc() {
return linkDesc;
}
/**
* 2018年5月17日
*
* @param linkDesc the linkDesc to set
* @author shulie
* @version 1.0
*/
public void setLinkDesc(String linkDesc) {
this.linkDesc = linkDesc;
}
/**
* 2018年5月17日
*
* @return the aswanId
* @author shulie
* @version 1.0
*/
public String getAswanId() {
return aswanId;
}
/**
* 2018年5月17日
*
* @param aswanId the aswanId to set
* @author shulie
* @version 1.0
*/
public void setAswanId(String aswanId) {
this.aswanId = aswanId;
}
/**
* 2018年5月17日
*
* @return the linkRank
* @author shulie
* @version 1.0
*/
public String getLinkRank() {
return linkRank;
}
/**
* 2018年5月17日
*
* @param linkRank the linkRank to set
* @author shulie
* @version 1.0
*/
public void setLinkRank(String linkRank) {
this.linkRank = linkRank;
}
/**
* 2018年5月17日
*
* @return the dictType
* @author shulie
* @version 1.0
*/
public String getDictType() {
return dictType;
}
/**
* 2018年5月17日
*
* @param dictType the dictType to set
* @author shulie
* @version 1.0
*/
public void setDictType(String dictType) {
this.dictType = dictType;
}
/**
* 2018年5月17日
*
* @return the principalNo
* @author shulie
* @version 1.0
*/
public String getPrincipalNo() {
return principalNo;
}
/**
* 2018年5月17日
*
* @param principalNo the principalNo to set
* @author shulie
* @version 1.0
*/
public void setPrincipalNo(String principalNo) {
this.principalNo = principalNo;
}
/**
* 2018年5月17日
*
* @return 返回实体字符串
* @author shulie
* @version 1.0
*/
@Override
public String toString() {
return "TLinkMnt{" +
"linkId=" + linkId +
", linkName='" + linkName + '\'' +
", linkDesc='" + linkDesc + '\'' +
", aswanId='" + aswanId + '\'' +
", linkRank='" + linkRank + '\'' +
", dictType='" + dictType + '\'' +
", principalNo='" + principalNo + '\'' +
", bLinkOrder=" + bLinkOrder +
", bLinkCheckStatus='" + bLinkCheckStatus + '\'' +
", bLinkBank=" + bLinkBank +
'}';
}
}
| 21.003731 | 70 | 0.567952 |
48d66273ee654c1df56c8f58254d91592c2d61ee | 241 | package com.moxuanran.learning.dto;
import lombok.Data;
@Data
public class ResultDto<T> {
private boolean success;
private int httpCode;
private String message;
private String Tag;
private T data;
} | 14.176471 | 36 | 0.655602 |
f92e80c1061dd63ea8918a5d25109f86db8e9469 | 5,101 | /*
* Copyright 1999-2021 Alibaba Group Holding 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.
*/
package com.aliyun.odps.mma.client;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.aliyun.odps.mma.config.AbstractConfiguration;
import com.aliyun.odps.mma.config.ConfigurationUtils;
import com.aliyun.odps.mma.config.DataDestType;
import com.aliyun.odps.mma.config.DataSourceType;
import com.aliyun.odps.mma.config.JobConfiguration;
import com.aliyun.odps.mma.config.MetaDestType;
import com.aliyun.odps.mma.config.MetaSourceType;
import com.aliyun.odps.mma.util.GsonUtils;
import com.google.gson.reflect.TypeToken;
public class MmaConfigurationValidator {
private static final Logger LOG = LogManager.getLogger(MmaConfigurationValidator.class);
private static final String CONFIG_LONG_OPT = "config";
public static void main(String args[]) throws Exception {
Option configOption = Option
.builder()
.longOpt(CONFIG_LONG_OPT)
.hasArg(true)
.required(true)
.build();
Options options = new Options().addOption(configOption);
DefaultParser defaultParser = new DefaultParser();
CommandLine cmd = defaultParser.parse(options, args);
String configPath = cmd.getOptionValue(CONFIG_LONG_OPT);
String json = IOUtils.toString(Paths.get(configPath).toUri(), StandardCharsets.UTF_8);
JobConfiguration config = new JobConfiguration(GsonUtils.GSON.fromJson(
json, new TypeToken<Map<String, String>>() {}.getType()));
if (config.containsKey(AbstractConfiguration.METADATA_SOURCE_TYPE)) {
MetaSourceType metaSourceType = MetaSourceType.valueOf(
config.get(AbstractConfiguration.METADATA_SOURCE_TYPE));
switch (metaSourceType) {
case Hive:
ConfigurationUtils.validateHiveMetaSource(config);
break;
case MaxCompute:
ConfigurationUtils.validateMcMetaSource(config);
break;
case OSS:
ConfigurationUtils.validateOssMetaSource(config);
break;
default:
throw new IllegalArgumentException(
"Unsupported value for "
+ AbstractConfiguration.METADATA_SOURCE_TYPE + ": " + metaSourceType.name());
}
}
if (config.containsKey(AbstractConfiguration.DATA_SOURCE_TYPE)) {
DataSourceType dataSourceType = DataSourceType.valueOf(
config.get(AbstractConfiguration.DATA_SOURCE_TYPE));
switch (dataSourceType) {
case Hive:
ConfigurationUtils.validateHiveDataSource(config);
break;
case MaxCompute:
ConfigurationUtils.validateMcDataSource(config);
break;
case OSS:
ConfigurationUtils.validateOssDataSource(config);
break;
default:
throw new IllegalArgumentException(
"Unsupported value for "
+ AbstractConfiguration.DATA_SOURCE_TYPE + ": " + dataSourceType.name());
}
}
if (config.containsKey(AbstractConfiguration.METADATA_DEST_TYPE)) {
MetaDestType metaDestType = MetaDestType.valueOf(
config.get(AbstractConfiguration.METADATA_DEST_TYPE));
switch (metaDestType) {
case MaxCompute:
ConfigurationUtils.validateMcMetaDest(config);
break;
case OSS:
ConfigurationUtils.validateOssMetaDest(config);
break;
default:
throw new IllegalArgumentException(
"Unsupported value for "
+ AbstractConfiguration.METADATA_DEST_TYPE + ": " + metaDestType.name());
}
}
if (config.containsKey(AbstractConfiguration.DATA_DEST_TYPE)) {
DataDestType dataDestType = DataDestType.valueOf(
config.get(AbstractConfiguration.DATA_DEST_TYPE));
switch (dataDestType) {
case MaxCompute:
ConfigurationUtils.validateMcDataDest(config);
break;
case OSS:
ConfigurationUtils.validateOssDataDest(config);
break;
default:
throw new IllegalArgumentException(
"Unsupported value for "
+ AbstractConfiguration.DATA_DEST_TYPE + ": " + dataDestType.name());
}
}
}
}
| 36.435714 | 95 | 0.694766 |
01a033d781cff669cd33cc65939f62c78028e6eb | 821 | package br.com.jdscaram.androidpetstore.services;
import java.util.List;
import br.com.jdscaram.androidpetstore.services.animals.bean.PetModel;
import io.reactivex.Observable;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
/**
* {Created by Jonatas Caram on 06/06/2017}.
*/
public interface ServiceMapper {
@Headers({
"Content-type: application/json"
})
@GET("pet/{petId}")
Call<PetModel> getPet(@Path("petId") long id);
@GET("pet/findByStatus")
Observable<List<PetModel>> getPets(@Query("status") String value);
@POST
Call<PetModel> registerPet(@Url String url, @Body PetModel petRequest);
}
| 23.457143 | 75 | 0.727162 |
c84b231026d904c29c45799e8c0b6dfa525cf331 | 218 | package gov.hhs.onc.phiz.web.ws.logging;
import gov.hhs.onc.phiz.logging.logstash.MarkerObjectFieldName;
@MarkerObjectFieldName("wsResponseMessage")
public interface WsResponseMessageEvent extends WsMessageEvent {
}
| 27.25 | 64 | 0.83945 |
bbb07a9f45cfb6c25f334decee8b9f71c6a5bda4 | 579 | package com.zf1976.ddns.api.auth;
/**
* @author mac
* @date 2021/7/18
*/
public class TokenCredentials implements ProviderCredentials {
private final String accessKeySecret;
public TokenCredentials(String token) {
if (token == null) {
throw new IllegalArgumentException("Access key secret cannot be null.");
}
this.accessKeySecret = token;
}
@Override
public String getAccessKeyId() {
return null;
}
@Override
public String getAccessKeySecret() {
return this.accessKeySecret;
}
}
| 18.677419 | 84 | 0.639033 |
713786c4501c32dce907041fa32aadff04aeb7e5 | 1,603 | package com.csc445.shared.game;
import java.util.ArrayList;
import java.util.List;
public class Spot {
private String name;
private byte color;
private int x;
private int y;
public Spot() {
}
public Spot(int x, int y) {
this.x = x;
this.y = y;
this.color = 6; // white
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getX() {
return x;
}
public void setX(byte x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(byte y) {
this.y = y;
}
public byte getColor() {
return color;
}
/**
* Colors:
* 0. RED,
* 1. ORANGE,
* 2. YELLOW,
* 3. GREEN,
* 4. BLUE,
* 5. PURPLE,
* 6. WHITE,
* 7. BLACK,
* 8. PINK,
* 9. TEAL
*
* @param color the number of the color
*/
public void setColor(byte color) {
this.color = color;
}
public byte[] getByteArray() {
final List<Byte> data = new ArrayList<>();
data.add((byte) x);
data.add((byte) y);
data.add(color);
if (name != null) {
for (byte b : name.getBytes()) {
data.add(b);
}
} else {
data.add((byte) 126); // ~
}
final byte[] dataArray = new byte[data.size()];
for (int i = 0; i < dataArray.length; i++) {
dataArray[i] = data.get(i);
}
return dataArray;
}
}
| 17.615385 | 55 | 0.466001 |
946c1304ab0077e48fcfbca58bfa67c0aefae5f3 | 9,862 | /*
* Copyright 2020 Couchbase, 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.couchbase.connector.testcontainers;
import com.couchbase.client.dcp.util.Version;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.Container;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.shaded.com.google.common.base.Stopwatch;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Optional;
import static com.couchbase.connector.testcontainers.ExecUtils.execInContainerUnchecked;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.SECONDS;
public class CouchbaseOps {
private static final Logger log = LoggerFactory.getLogger(CouchbaseOps.class);
private final GenericContainer container;
private final String username;
private final String password;
private final String hostname;
private final OkHttpClient httpClient = new OkHttpClient();
public CouchbaseOps(GenericContainer container, String hostname) {
this.container = requireNonNull(container);
this.username = "Administrator";
this.password = "password";
this.hostname = requireNonNull(hostname);
}
private void serverAdd(GenericContainer newNode, String newNodeHostname) {
execOrDie("couchbase-cli", "server-add",
"--cluster", hostname,
"--username=" + username,
"--password=" + password,
"--server-add=" + newNodeHostname,
"--server-add-username=" + username,
"--server-add-password=" + password);
}
public void createBucket(String bucketName, int bucketQuotaMb, int replicas) {
Stopwatch timer = Stopwatch.createStarted();
execOrDie("couchbase-cli", "bucket-create",
"--cluster", "localhost",
"--username", username,
"--password", password,
"--bucket", bucketName,
"--bucket-ramsize", String.valueOf(bucketQuotaMb),
"--bucket-type", "couchbase",
"--bucket-replica", String.valueOf(replicas)
, "--wait"
);
try {
// extra wait for good measure. will this fix failures in CI environment?
SECONDS.sleep(5);
} catch (Exception e) {
throw new RuntimeException(e);
}
log.info("Creating bucket took {}", timer);
}
public void deleteBucket(String bucketName) {
Stopwatch timer = Stopwatch.createStarted();
execOrDie("couchbase-cli", "bucket-delete",
"--cluster", "localhost",
"--username", username,
"--password", password,
"--bucket", bucketName);
log.info("Deleting bucket took " + timer);
}
Container.ExecResult execOrDie(String... command) {
return ExecUtils.execOrDie(container, command);
}
public void rebalance() {
execOrDie("couchbase-cli", "rebalance",
"-c", "localhost",
"-u", username,
"-p", password);
}
public void failover() {
execOrDie("couchbase-cli", "failover",
"--cluster", "localhost:8091",
"--username", username,
"--password", password,
"--server-failover", "localhost:8091");
}
/**
* Ensures the node refers to itself by hostname instead of IP address.
* Doesn't really matter, but it's nice to see consistent names in the web UI's server list.
*/
private void assignHostname(String hostname) {
execOrDie("curl",
"--silent",
"--user", username + ":" + password,
"http://127.0.0.1:8091/node/controller/rename",
"--data", "hostname=" + hostname);
}
public void loadSampleBucket(String bucketName) {
loadSampleBucket(bucketName, 100);
}
public void loadSampleBucket(String bucketName, int bucketQuotaMb) {
Stopwatch timer = Stopwatch.createStarted();
log.info("Loading sample bucket '" + bucketName + "'...");
Container.ExecResult result = execInContainerUnchecked(container,
"cbdocloader",
"--cluster", "localhost", // + ":8091" +
"--username", username,
"--password", password,
"--bucket", bucketName,
"--bucket-quota", String.valueOf(bucketQuotaMb),
"--dataset", "./opt/couchbase/samples/" + bucketName + ".zip");
// Query and index services must be present to avoid this warning. We don't need those services.
if (result.getExitCode() != 0 && !result.getStdout().contains("Errors occurred during the index creation phase")) {
throw new UncheckedIOException(new IOException("Failed to load sample bucket: " + result));
}
log.info("Importing sample bucket with cbdocloader took {}", timer);
// cbimport is faster, but isn't always available, and fails when query & index services are absent
// createBucket(bucketName, bucketQuotaMb, 0);
// execOrDie("cbimport", "json",
// "--threads", "2",
// "--cluster", "localhost",
// "--username", username,
// "--password", password,
// "--bucket", bucketName,
// "--format", "sample",
// "--dataset", "file://opt/couchbase/samples/" + bucketName + ".zip");
//
// log.info("Importing sample bucket with cbimport took " + timer);
}
public Optional<Version> getVersion() {
Container.ExecResult execResult = execInContainerUnchecked(container, "couchbase-server", "--version");
if (execResult.getExitCode() != 0) {
return getVersionFromDockerImageName(container);
}
Optional<Version> result = tryParseVersion(execResult.getStdout().trim());
return result.isPresent() ? result : getVersionFromDockerImageName(container);
}
private static Optional<Version> getVersionFromDockerImageName(GenericContainer couchbase) {
final String imageName = couchbase.getDockerImageName();
final int tagDelimiterIndex = imageName.indexOf(':');
return tagDelimiterIndex == -1 ? Optional.empty() : tryParseVersion(imageName.substring(tagDelimiterIndex + 1));
}
private static Optional<Version> tryParseVersion(final String versionString) {
try {
// We get a string like "Couchbase Server 5.5.0-2036 (EE)". The version parser
// tolerates trailing garbage, but not leading garbage, so...
final int actualStartIndex = indexOfFirstDigit(versionString);
if (actualStartIndex == -1) {
return Optional.empty();
}
final String versionWithoutLeadingGarbage = versionString.substring(actualStartIndex);
final Version version = Version.parseVersion(versionWithoutLeadingGarbage);
// builds off master branch might have version 0.0.0 :-(
return version.major() == 0 ? Optional.empty() : Optional.of(version);
} catch (Exception e) {
log.warn("Failed to parse version string '{}'", versionString, e);
return Optional.empty();
}
}
private static int indexOfFirstDigit(final String s) {
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
return i;
}
}
return -1;
}
// public static void main(String[] args) {
// Stopwatch timer = Stopwatch.createStarted();
//
// String hostname = "node1.couchbase.host";
// CouchbaseContainer couchbase = new CouchbaseContainer()
// .withNetworkAliases(hostname)
// .withEnabledServices(CouchbaseService.KV, CouchbaseService.QUERY, CouchbaseService.INDEX);
// CouchbaseOps ops = new CouchbaseOps(couchbase, hostname);
//
// couchbase.start();
// //ops.assignHostname(hostname);
//
// System.out.println("*** VERSION: " + ops.getVersion());
//
// ops.loadSampleBucket("travel-sample", 100);
//
// Cluster cluster = Cluster.connect(
// couchbase.getConnectionString(),
// couchbase.getUsername(),
// couchbase.getPassword());
//
//
//// ops.createBucket("default", 128, 0);
//// cluster.bucket("default").waitUntilReady(Duration.ofMinutes(1));
//
//
// System.out.println("done, finished in " + timer);
//
// // 33.79 s
// }
//
/**
* Helper method to perform a request against a couchbase server HTTP endpoint.
*
* @param port the (unmapped) original port that should be used.
* @param path the relative http path.
* @param method the http method to use.
* @param body if present, will be part of the payload.
* @param auth if authentication with the admin user and password should be used.
* @return the response of the request.
*/
private Response doHttpRequest(final int port, final String path, final String method, final RequestBody body,
final boolean auth) {
try {
Request.Builder requestBuilder = new Request.Builder()
.url("http://" + container.getContainerIpAddress() + ":" + container.getMappedPort(port) + path);
if (auth) {
requestBuilder = requestBuilder.header("Authorization", Credentials.basic(username, password));
}
if (body == null) {
requestBuilder = requestBuilder.get();
} else {
requestBuilder = requestBuilder.method(method, body);
}
return httpClient.newCall(requestBuilder.build()).execute();
} catch (Exception ex) {
throw new RuntimeException("Could not perform request against couchbase HTTP endpoint ", ex);
}
}
}
| 35.602888 | 119 | 0.669641 |
4d56a04212d57d835305cb16914c29666ad6722f | 1,700 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 und
*/
package org.wso2.carbon.identity.handler.event.account.lock.constants;
/**
* AccountConstants class
*/
public class AccountConstants {
public static final String ACCOUNT_LOCKED_CLAIM = "http://wso2.org/claims/accountLocked";
public static final String ACCOUNT_DISABLED_CLAIM = "http://wso2.org/claims/accountDisabled";
public static final String ACCOUNT_UNLOCK_TIME_CLAIM = "http://wso2.org/claims/unlockTime";
public static final String FAILED_LOGIN_ATTEMPTS_CLAIM = "http://wso2.org/claims/failedLoginAttempts";
public static final String EMAIL_VERIFIED_CLAIM = "http://wso2.org/claims/emailVerifed";
public static final String FAILED_LOGIN_LOCKOUT_COUNT_CLAIM = "http://wso2.org/claims/failedLoginLockoutCount";
public static final String EMAIL_TEMPLATE_TYPE_ACC_LOCKED = "accountLock";
public static final String EMAIL_TEMPLATE_TYPE_ACC_UNLOCKED = "accountUnLock";
public static final String EMAIL_TEMPLATE_TYPE_ACC_DISABLED = "accountDisable";
public static final String EMAIL_TEMPLATE_TYPE_ACC_ENABLED = "accountEnable";
}
| 43.589744 | 115 | 0.770588 |
0e80e336de2427cdb302ba995c9edd3170662adf | 730 | package com.example.demo.dto;
import java.time.LocalDateTime;
public class Message {
private String room;
private String user;
private String text;
private LocalDateTime time;
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
} | 16.976744 | 45 | 0.589041 |
06ae4324c36f58c1f27aabe1755a92418bc59865 | 205 | package com.example.oroles.hlin.Listeners;
public interface IConnectedBluetoothListener {
void updateConnectedBluetooth(String connectionStatus);
void updateLastTimeUsedBluetooth(String time);
}
| 25.625 | 59 | 0.82439 |
974fe0b33b17ccbe351373a22c14a72abec060f1 | 53 | package com.yipeipei.pprqs;
public class Query {
}
| 8.833333 | 27 | 0.735849 |
a13ffcf38844c8cef4379c9a8dea51192fb3a448 | 2,216 | package at.porscheinformatik.antimapper;
import java.io.Serializable;
/**
* A pair of two values
*
* @author HAM
*
* @param <Left> the left value
* @param <Right> the right value
*/
public class Pair<Left, Right> implements Serializable
{
private static final long serialVersionUID = 160174997957476433L;
public static <Left, Right> Pair<Left, Right> of(Left left, Right right)
{
return new Pair<>(left, right);
}
public static <Left> Left leftOf(Pair<Left, ?> pair)
{
return pair != null ? pair.left : null;
}
public static <Right> Right rightOf(Pair<?, Right> pair)
{
return pair != null ? pair.right : null;
}
private final Left left;
private final Right right;
public Pair(Left left, Right right)
{
super();
this.left = left;
this.right = right;
}
public Left getLeft()
{
return left;
}
public Right getRight()
{
return right;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((left == null) ? 0 : left.hashCode());
result = prime * result + ((right == null) ? 0 : right.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Pair))
{
return false;
}
Pair<?, ?> other = (Pair<?, ?>) obj;
if (left == null)
{
if (other.left != null)
{
return false;
}
}
else if (!left.equals(other.left))
{
return false;
}
if (right == null)
{
if (other.right != null)
{
return false;
}
}
else if (!right.equals(other.right))
{
return false;
}
return true;
}
@Override
public String toString()
{
return String.format("(%s, %s)", left, right);
}
}
| 18.621849 | 76 | 0.485108 |
391c09b004a81c445843ede0454c831228f775dd | 271 | package com.jaredscarito.jftp.model.pages.nodes;
import javafx.scene.control.Label;
import java.util.List;
public class NodeLabel extends Label {
public NodeLabel(String name, List<String> styleClasses) {}
public NodeLabel(String name, String styleClass) {}
}
| 24.636364 | 63 | 0.767528 |
d8068eefdea2e79cca06ca9ba8c546aea08c0ac5 | 567 | package main.java.staticcheckers;
public class CheckError implements Comparable<CheckError> {
private int x;
private int y;
public CheckError(int x, int y, String errString) {
this.x = x;
this.y = y;
this.errString = errString;
}
private String errString;
@Override
public String toString() {
return errString;
}
@Override
public int compareTo(CheckError o) {
if (this.x == o.x) {
return this.y - o.y;
} else {
return this.x - o.x;
}
}
}
| 19.551724 | 59 | 0.557319 |
6bca452932ee3bc734313bc225f7e3e3d44415d8 | 2,124 | package me.winter.boing;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
/**
* Represents a step for a dynamic body, typically has a movement and collision shifing but
* different World implementation may Steps with more fields.
* <p>
* Created by Alexander Winter on 2017-06-17.
*/
public interface MoveState
{
/**
* World in which this MoveState is valid.
*
* @return world reference of this MoveState
*/
PhysicsWorld getWorld();
/**
* Each MoveState keeps data about body in context of a world.
* This returns the body this MoveState keeps track of.
*
* @return the body this MoveState represent the movement of
*/
DynamicBody getBody();
/**
* The movement of a DynamicBody is how much it moved in this frame.
* <p>
* It is calculated by multiplying the current velocity with the delta of the frame.
*
* @return unit-scaled movement of this frame/step
*/
Vector2 getMovement();
/**
* The collision shifting is a way to represents the movement imposed by the
* collision resolver when dynamic bodies collides. If two bodies overlap, they
* need to be shifted in order to stop overlapping.
*
* @return shifting imposed by collision resolver on previous frame
*/
Vector2 getCollisionShifting();
/**
*
* @return vector of movement moving this body in function of the movement of other objects
*/
Vector2 getInfluence();
/**
*
* @return list of bodies this body is touching in this step
*/
Array<Collision> getCollisions();
/**
* Shifts this body by the specified vector, as response of a collision
*
* @param x x component of the vector to shift this body with
* @param y y component of the vector to shift this body with
*/
void shift(float x, float y);
/**
* Makes a step in the simulation, calculating the movement from the velocity and ready to
* resolve collisions.
*
* Also has the job to clear the collisions from the previous step
*
* @param frame get the number of frames (frame id or step id)
* @param delta get the delta to step it with
*/
void step(int frame, float delta);
}
| 27.230769 | 92 | 0.710452 |
e19f815db57429f8f759ade213070a59f72dd454 | 567 | package com.thewizrd.simplewear;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
/**
* Receiver class which shows notifications when the Device Administrator status
* of the application changes.
*/
public class ScreenLockAdminReceiver extends DeviceAdminReceiver {
@Override
public void onEnabled(@NonNull Context context, @NonNull Intent intent) {
}
@Override
public void onDisabled(@NonNull Context context, @NonNull Intent intent) {
}
} | 27 | 80 | 0.772487 |
48373e9d90168d672e12449ed7c350947c1e15fc | 960 | package cc.bodyplus.sdk.ble.dfu;
import java.util.List;
import cc.bodyplus.sdk.ble.utils.DeviceInfo;
/**
* Created by Shihoo.Wang 2019/3/21
* Email shihu.wang@bodyplus.cc 451082005@qq.com
*/
public class DfuNetConfig {
private static List<DfuUpdateInfo> updateInfoList;
public static void setUpdateInfoList(List<DfuUpdateInfo> updateInfoList) {
DfuNetConfig.updateInfoList = updateInfoList;
}
public static DfuUpdateInfo getDfuUpdateInfo(DeviceInfo device) {
int hw = Integer.parseInt(device.hwVn);
try {
if (updateInfoList != null && !updateInfoList.isEmpty()) {
for (DfuUpdateInfo updateInfo : updateInfoList) {
if (Integer.parseInt(updateInfo.hwVn) == hw){
return updateInfo;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
| 25.263158 | 78 | 0.601042 |
88ff69a0a40fd3f60a6e944f89b7c637027ccdf8 | 677 | /*
* 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 trabalho;
/**
*
* @author HP
*/
public class LivroAutorTeste {
String livro1 = "DEITEL, H.M; Java Como Programar - Ed. Pearson, 2005.";
String livro2 = "SIERRA, K.; Use a Cabeça Java – Ed. Alta Books,2005.";
String livro3 = "SIERRA, K; BATES, B.; Certificação Sun para Programador Java 6 – Ed. Alta Books, 2008.";
String autor1 = "Ed pearson";
String autor2 = "Sierra K";
String autor3 = "SIERRA, K; BATES, B";
String livalug;
}
| 32.238095 | 110 | 0.645495 |
3f5f4f04a499164c651b845ea0eb5897797e35d2 | 5,333 | /*******************************************************************************
* Copyright 2019 See AUTHORS file
*
* 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.mini2Dx.core.graphics.viewport;
import org.mini2Dx.core.util.Scaling;
import org.mini2Dx.gdx.math.MathUtils;
import org.mini2Dx.gdx.math.Vector2;
/**
* Similar to {@link FitViewport} except the viewport will expand its size after scaling to
* fill the remaining space of the window to avoid black bars. A maxiumum virtual screen size c
* an be set if black bars are desired after a certain amount of viewport expansion.
*/
public class ExtendViewport extends Viewport {
private float minWorldWidth, minWorldHeight;
private float maxWorldWidth, maxWorldHeight;
private boolean powerOfTwo = false;
private final Vector2 size = new Vector2();
private final Vector2 scale = new Vector2();
/**
* Constructor with no maxiumum virtual screen size
* @param minWorldWidth Minimum virtual screen width
* @param minWorldHeight Minimum virtual screen height
*/
public ExtendViewport(float minWorldWidth, float minWorldHeight) {
this(minWorldWidth, minWorldHeight, 0f, 0f);
}
/**
* Constructor
* @param minWorldWidth Minimum virtual screen width
* @param minWorldHeight Minimum virtual screen height
* @param maxWorldWidth Maximum virtual screen width
* @param maxWorldHeight Maximum virtual screen height
*/
public ExtendViewport(float minWorldWidth, float minWorldHeight, float maxWorldWidth, float maxWorldHeight) {
this(false, minWorldWidth, minWorldHeight, maxWorldWidth, maxWorldHeight);
}
/**
* Constructor with no maxiumum virtual screen size
* @param powerOfTwo True if scaling should only be applied in powers of two
* @param minWorldWidth Minimum virtual screen width
* @param minWorldHeight Minimum virtual screen height
*/
public ExtendViewport(boolean powerOfTwo, float minWorldWidth, float minWorldHeight) {
this(powerOfTwo, minWorldWidth, minWorldHeight, 0f, 0f);
}
/**
* Constructor
* @param powerOfTwo True if scaling should only be applied in powers of two
* @param minWorldWidth Minimum virtual screen width
* @param minWorldHeight Minimum virtual screen height
* @param maxWorldWidth Maximum virtual screen width
* @param maxWorldHeight Maximum virtual screen height
*/
public ExtendViewport(boolean powerOfTwo, float minWorldWidth, float minWorldHeight, float maxWorldWidth, float maxWorldHeight) {
super();
this.powerOfTwo = powerOfTwo;
this.minWorldWidth = minWorldWidth;
this.minWorldHeight = minWorldHeight;
this.maxWorldWidth = maxWorldWidth;
this.maxWorldHeight = maxWorldHeight;
}
@Override
public void onResize(int width, int height) {
float worldWidth = minWorldWidth;
float worldHeight = minWorldHeight;
Scaling.FIT.apply(size, scale, powerOfTwo, worldWidth, worldHeight, width, height);
int viewportWidth = Math.round(size.x);
int viewportHeight = Math.round(size.y);
if (viewportWidth < width) {
float toViewportSpace = viewportHeight / worldHeight;
float toWorldSpace = worldHeight / viewportHeight;
float lengthen = (width - viewportWidth) * toWorldSpace;
if (maxWorldWidth > 0) lengthen = Math.min(lengthen, maxWorldWidth - minWorldWidth);
worldWidth += lengthen;
viewportWidth += Math.round(lengthen * toViewportSpace);
}
if (viewportHeight < height) {
float toViewportSpace = viewportWidth / worldWidth;
float toWorldSpace = worldWidth / viewportWidth;
float lengthen = (height - viewportHeight) * toWorldSpace;
if (maxWorldHeight > 0) lengthen = Math.min(lengthen, maxWorldHeight - minWorldHeight);
worldHeight += lengthen;
viewportHeight += Math.round(lengthen * toViewportSpace);
}
setBounds((width - viewportWidth) / MathUtils.round(2 * scale.x),
(height - viewportHeight) / MathUtils.round(2 * scale.y),
MathUtils.round(worldWidth), MathUtils.round(worldHeight),
scale.x, scale.y);
}
public float getMinWorldWidth() {
return minWorldWidth;
}
public void setMinWorldWidth(float minWorldWidth) {
this.minWorldWidth = minWorldWidth;
}
public float getMinWorldHeight() {
return minWorldHeight;
}
public void setMinWorldHeight(float minWorldHeight) {
this.minWorldHeight = minWorldHeight;
}
public float getMaxWorldWidth() {
return maxWorldWidth;
}
public void setMaxWorldWidth(float maxWorldWidth) {
this.maxWorldWidth = maxWorldWidth;
}
public float getMaxWorldHeight() {
return maxWorldHeight;
}
public void setMaxWorldHeight(float maxWorldHeight) {
this.maxWorldHeight = maxWorldHeight;
}
public boolean isPowerOfTwo() {
return powerOfTwo;
}
public void setPowerOfTwo(boolean powerOfTwo) {
this.powerOfTwo = powerOfTwo;
}
}
| 34.856209 | 130 | 0.735421 |
f1a1f0a9a6168ece447749060f0437028d09738a | 28,574 | package com.hedera.services.bdd.suites.contract;
/*-
*
* Hedera Services Test Clients
*
* Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import com.google.protobuf.ByteString;
import com.hedera.services.bdd.spec.HapiApiSpec;
import com.hedera.services.bdd.spec.HapiSpecOperation;
import com.hedera.services.bdd.spec.HapiSpecSetup;
import com.hedera.services.bdd.spec.infrastructure.meta.ContractResources;
import com.hedera.services.bdd.spec.keys.KeyShape;
import com.hedera.services.bdd.spec.keys.SigControl;
import com.hedera.services.bdd.spec.transactions.TxnUtils;
import com.hedera.services.bdd.spec.utilops.CustomSpecAssert;
import com.hedera.services.bdd.spec.utilops.UtilVerbs;
import com.hedera.services.bdd.suites.HapiApiSuite;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Assertions;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import static com.hedera.services.bdd.spec.HapiApiSpec.defaultHapiSpec;
import static com.hedera.services.bdd.spec.assertions.AssertUtils.inOrder;
import static com.hedera.services.bdd.spec.assertions.ContractFnResultAsserts.isContractWith;
import static com.hedera.services.bdd.spec.assertions.ContractFnResultAsserts.isLiteralResult;
import static com.hedera.services.bdd.spec.assertions.ContractFnResultAsserts.resultWith;
import static com.hedera.services.bdd.spec.assertions.ContractInfoAsserts.contractWith;
import static com.hedera.services.bdd.spec.assertions.TransactionRecordAsserts.recordWith;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.ADD_NTH_FIB_ABI;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.CONSPICUOUS_DONATION_ABI;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.EMPTY_CONSTRUCTOR;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.FIBONACCI_PLUS_CONSTRUCTOR_ABI;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.FIBONACCI_PLUS_PATH;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.MULTIPURPOSE_BYTECODE_PATH;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.SEND_REPEATEDLY_ABI;
import static com.hedera.services.bdd.spec.infrastructure.meta.ContractResources.SEND_THEN_REVERT_NESTED_SENDS_ABI;
import static com.hedera.services.bdd.spec.keys.ControlForKey.forKey;
import static com.hedera.services.bdd.spec.keys.KeyFactory.KeyType.THRESHOLD;
import static com.hedera.services.bdd.spec.keys.KeyShape.CONTRACT;
import static com.hedera.services.bdd.spec.keys.KeyShape.DELEGATE_CONTRACT;
import static com.hedera.services.bdd.spec.keys.KeyShape.SIMPLE;
import static com.hedera.services.bdd.spec.keys.KeyShape.listOf;
import static com.hedera.services.bdd.spec.keys.KeyShape.sigs;
import static com.hedera.services.bdd.spec.keys.KeyShape.threshOf;
import static com.hedera.services.bdd.spec.keys.SigControl.OFF;
import static com.hedera.services.bdd.spec.keys.SigControl.ON;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getAccountBalance;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getAccountInfo;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getContractInfo;
import static com.hedera.services.bdd.spec.queries.QueryVerbs.getTxnRecord;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.contractCall;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.contractCreate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.cryptoCreate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.cryptoUpdate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.fileCreate;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.fileUpdate;
import static com.hedera.services.bdd.spec.utilops.CustomSpecAssert.allRunFor;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.contractListWithPropertiesInheritedFrom;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.inParallel;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.newKeyListNamed;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.newKeyNamed;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.sourcing;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.withOpContext;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.CONTRACT_DELETED;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.CONTRACT_REVERT_EXECUTED;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.ERROR_DECODING_BYTESTRING;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INSUFFICIENT_GAS;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INSUFFICIENT_PAYER_BALANCE;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INSUFFICIENT_TX_FEE;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_SIGNATURE;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_SOLIDITY_ADDRESS;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_ZERO_BYTE_IN_STRING;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.MAX_GAS_LIMIT_EXCEEDED;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.MEMO_TOO_LONG;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.SUCCESS;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.TRANSACTION_OVERSIZE;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ContractCreateSuite extends HapiApiSuite {
private static final Logger log = LogManager.getLogger(ContractCreateSuite.class);
private static final String defaultMaxGas =
HapiSpecSetup.getDefaultNodeProps().get("contracts.maxGas");
public static void main(String... args) {
new ContractCreateSuite().runSuiteSync();
}
@Override
protected List<HapiApiSpec> getSpecsInSuite() {
return List.of(
createEmptyConstructor(),
insufficientPayerBalanceUponCreation(),
rejectsInvalidMemo(),
rejectsInsufficientFee(),
rejectsInvalidBytecode(),
revertsNonzeroBalance(),
createFailsIfMissingSigs(),
rejectsInsufficientGas(),
createsVanillaContractAsExpectedWithOmittedAdminKey(),
childCreationsHaveExpectedKeysWithOmittedAdminKey(),
cannotCreateTooLargeContract(),
revertedTryExtCallHasNoSideEffects(),
getsInsufficientPayerBalanceIfSendingAccountCanPayEverythingButServiceFee(),
receiverSigReqTransferRecipientMustSignWithFullPubKeyPrefix(),
cannotSendToNonExistentAccount(),
canCallPendingContractSafely(),
delegateContractIdRequiredForTransferInDelegateCall(),
maxRefundIsMaxGasRefundConfiguredWhenTXGasPriceIsSmaller(),
minChargeIsTXGasUsedByContractCreate(),
gasLimitOverMaxGasLimitFailsPrecheck(),
vanillaSuccess()
);
}
private HapiApiSpec insufficientPayerBalanceUponCreation() {
return defaultHapiSpec("InsufficientPayerBalanceUponCreation")
.given(
cryptoCreate("bankrupt")
.balance(0L),
fileCreate("contractCode")
.path(EMPTY_CONSTRUCTOR)
)
.when()
.then(
contractCreate("defaultContract")
.bytecode("contractCode")
.payingWith("bankrupt")
.hasPrecheck(INSUFFICIENT_PAYER_BALANCE)
);
}
private HapiApiSpec canCallPendingContractSafely() {
final int numSlots = 64;
final int createBurstSize = 500;
final int[] targets = { 19, 24 };
final AtomicLong createdFileNum = new AtomicLong();
final var callTxn = "callTxn";
final var initcode = "initcode";
return defaultHapiSpec("CanCallPendingContractSafely")
.given(
UtilVerbs.overriding("contracts.throttle.throttleByGas", "false"),
fileCreate(initcode)
.path(FIBONACCI_PLUS_PATH)
.payingWith(GENESIS)
.exposingNumTo(createdFileNum::set),
inParallel(IntStream.range(0, createBurstSize)
.mapToObj(i ->
contractCreate("contract" + i, FIBONACCI_PLUS_CONSTRUCTOR_ABI, numSlots)
.fee(ONE_HUNDRED_HBARS)
.gas(300_000L)
.payingWith(GENESIS)
.noLogging()
.deferStatusResolution()
.bytecode(initcode)
.adminKey(THRESHOLD))
.toArray(HapiSpecOperation[]::new))
).when().then(
sourcing(() ->
contractCall(
"0.0." + (createdFileNum.get() + createBurstSize),
ADD_NTH_FIB_ABI, targets, 12
)
.payingWith(GENESIS)
.gas(300_000L)
.via(callTxn)),
UtilVerbs.resetAppPropertiesTo("src/main/resource/bootstrap.properties")
);
}
HapiApiSpec cannotSendToNonExistentAccount() {
Object[] donationArgs = new Object[] { 666666, "Hey, Ma!" };
return defaultHapiSpec("CannotSendToNonExistentAccount").given(
fileCreate("multiBytecode")
.path(MULTIPURPOSE_BYTECODE_PATH)
).when(
contractCreate("multi")
.bytecode("multiBytecode")
.balance(666)
).then(
contractCall("multi", CONSPICUOUS_DONATION_ABI, donationArgs)
.hasKnownStatus(INVALID_SOLIDITY_ADDRESS)
);
}
private HapiApiSpec createsVanillaContractAsExpectedWithOmittedAdminKey() {
final var name = "testContract";
return defaultHapiSpec("CreatesVanillaContract")
.given(
fileCreate("contractFile")
.path(ContractResources.VALID_BYTECODE_PATH)
).when().then(
contractCreate(name)
.omitAdminKey()
.bytecode("contractFile"),
getContractInfo(name)
.has(contractWith().immutableContractKey(name))
.logged()
);
}
private HapiApiSpec childCreationsHaveExpectedKeysWithOmittedAdminKey() {
final AtomicLong firstStickId = new AtomicLong();
final AtomicLong secondStickId = new AtomicLong();
final AtomicLong thirdStickId = new AtomicLong();
final String txn = "creation";
return defaultHapiSpec("ChildCreationsHaveExpectedKeysWithOmittedAdminKey")
.given(
fileCreate("bytecode").path(ContractResources.FUSE_BYTECODE_PATH),
contractCreate("fuse").bytecode("bytecode").omitAdminKey().gas(300_000).via(txn),
withOpContext((spec, opLog) -> {
final var op = getTxnRecord(txn);
allRunFor(spec, op);
final var record = op.getResponseRecord();
final var creationResult = record.getContractCreateResult();
final var createdIds = creationResult.getCreatedContractIDsList();
assertEquals(
4, createdIds.size(),
"Expected four creations but got " + createdIds);
firstStickId.set(createdIds.get(1).getContractNum());
secondStickId.set(createdIds.get(2).getContractNum());
thirdStickId.set(createdIds.get(3).getContractNum());
})
).when(
sourcing(() -> getContractInfo("0.0." + firstStickId.get())
.has(contractWith().immutableContractKey("0.0." + firstStickId.get()))
.logged()),
sourcing(() -> getContractInfo("0.0." + secondStickId.get())
.has(contractWith().immutableContractKey("0.0." + secondStickId.get()))
.logged()),
sourcing(() -> getContractInfo("0.0." + thirdStickId.get())
.logged()),
contractCall("fuse", ContractResources.LIGHT_ABI).via("lightTxn")
).then(
sourcing(() -> getContractInfo("0.0." + firstStickId.get())
.hasCostAnswerPrecheck(CONTRACT_DELETED)),
sourcing(() -> getContractInfo("0.0." + secondStickId.get())
.hasCostAnswerPrecheck(CONTRACT_DELETED)),
sourcing(() -> getContractInfo("0.0." + thirdStickId.get())
.hasCostAnswerPrecheck(CONTRACT_DELETED))
);
}
private HapiApiSpec createEmptyConstructor() {
return defaultHapiSpec("EmptyConstructor")
.given(
fileCreate("contractFile")
.path(ContractResources.EMPTY_CONSTRUCTOR)
).when(
).then(
contractCreate("emptyConstructorTest")
.bytecode("contractFile")
.hasKnownStatus(SUCCESS)
);
}
private HapiApiSpec revertedTryExtCallHasNoSideEffects() {
final var balance = 3_000;
final int sendAmount = balance / 3;
final var initcode = "initcode";
final var contract = "contract";
final var aBeneficiary = "aBeneficiary";
final var bBeneficiary = "bBeneficiary";
final var txn = "txn";
return defaultHapiSpec("RevertedTryExtCallHasNoSideEffects")
.given(
fileCreate(initcode)
.path(ContractResources.REVERTING_SEND_TRY),
contractCreate(contract)
.bytecode(initcode)
.balance(balance),
cryptoCreate(aBeneficiary).balance(0L),
cryptoCreate(bBeneficiary).balance(0L)
).when(
withOpContext((spec, opLog) -> {
final var registry = spec.registry();
final int aNum = (int) registry.getAccountID(aBeneficiary).getAccountNum();
final int bNum = (int) registry.getAccountID(bBeneficiary).getAccountNum();
final Object[] sendArgs = new Object[] { sendAmount, aNum, bNum };
final var op = contractCall(
contract,
SEND_THEN_REVERT_NESTED_SENDS_ABI,
sendArgs
)
.gas(110_000)
.via(txn);
allRunFor(spec, op);
})
).then(
getTxnRecord(txn).logged(),
getAccountBalance(aBeneficiary).logged(),
getAccountBalance(bBeneficiary).logged()
);
}
private HapiApiSpec createFailsIfMissingSigs() {
KeyShape shape = listOf(SIMPLE, threshOf(2, 3), threshOf(1, 3));
SigControl validSig = shape.signedWith(sigs(ON, sigs(ON, ON, OFF), sigs(OFF, OFF, ON)));
SigControl invalidSig = shape.signedWith(sigs(OFF, sigs(ON, ON, OFF), sigs(OFF, OFF, ON)));
return defaultHapiSpec("CreateFailsIfMissingSigs")
.given(
fileCreate("contractFile")
.path(ContractResources.VALID_BYTECODE_PATH)
).when().then(
contractCreate("testContract")
.adminKeyShape(shape)
.bytecode("contractFile")
.sigControl(forKey("testContract", invalidSig))
.hasKnownStatus(INVALID_SIGNATURE),
contractCreate("testContract")
.adminKeyShape(shape)
.bytecode("contractFile")
.sigControl(forKey("testContract", validSig))
);
}
private HapiApiSpec rejectsInsufficientGas() {
return defaultHapiSpec("RejectsInsufficientGas")
.given(
fileCreate("simpleStorageBytecode")
.path(ContractResources.SIMPLE_STORAGE_BYTECODE_PATH)
).when().then(
contractCreate("simpleStorage")
.bytecode("simpleStorageBytecode")
.gas(0L)
.hasKnownStatus(INSUFFICIENT_GAS)
);
}
private HapiApiSpec rejectsInvalidMemo() {
return defaultHapiSpec("RejectsInvalidMemo")
.given().when().then(
contractCreate("testContract")
.entityMemo(TxnUtils.nAscii(101))
.hasPrecheck(MEMO_TOO_LONG),
contractCreate("testContract")
.entityMemo(ZERO_BYTE_MEMO)
.hasPrecheck(INVALID_ZERO_BYTE_IN_STRING)
);
}
private HapiApiSpec rejectsInsufficientFee() {
return defaultHapiSpec("RejectsInsufficientFee")
.given(
cryptoCreate("payer"),
fileCreate("contractFile")
.path(ContractResources.VALID_BYTECODE_PATH)
).when().then(
contractCreate("testContract")
.bytecode("contractFile")
.payingWith("payer")
.fee(1L)
.hasPrecheck(INSUFFICIENT_TX_FEE)
);
}
private HapiApiSpec rejectsInvalidBytecode() {
return defaultHapiSpec("RejectsInvalidBytecode")
.given(
fileCreate("contractFile")
.path(ContractResources.INVALID_BYTECODE_PATH)
).when().then(
contractCreate("testContract")
.bytecode("contractFile")
.hasKnownStatus(ERROR_DECODING_BYTESTRING)
);
}
private HapiApiSpec revertsNonzeroBalance() {
return defaultHapiSpec("RevertsNonzeroBalance")
.given(
fileCreate("contractFile")
.path(ContractResources.VALID_BYTECODE_PATH)
).when().then(
contractCreate("testContract")
.balance(1L)
.bytecode("contractFile")
.hasKnownStatus(CONTRACT_REVERT_EXECUTED)
);
}
private HapiApiSpec delegateContractIdRequiredForTransferInDelegateCall() {
final var justSendInitcode = "justSendInitcode";
final var sendInternalAndDelegateInitcode = "sendInternalAndDelegateInitcode";
final var justSend = "justSend";
final var sendInternalAndDelegate = "sendInternalAndDelegate";
final var beneficiary = "civilian";
final var totalToSend = 1_000L;
final var origKey = KeyShape.threshOf(1, SIMPLE, CONTRACT);
final var revisedKey = KeyShape.threshOf(1, SIMPLE, DELEGATE_CONTRACT);
final var newKey = "delegateContractKey";
final AtomicLong justSendContractNum = new AtomicLong();
final AtomicLong beneficiaryAccountNum = new AtomicLong();
return defaultHapiSpec("DelegateContractIdRequiredForTransferInDelegateCall")
.given(
fileCreate(justSendInitcode)
.path(ContractResources.JUST_SEND_BYTECODE_PATH),
fileCreate(sendInternalAndDelegateInitcode)
.path(ContractResources.SEND_INTERNAL_AND_DELEGATE_BYTECODE_PATH),
contractCreate(justSend)
.bytecode(justSendInitcode)
.gas(300_000L)
.exposingNumTo(justSendContractNum::set),
contractCreate(sendInternalAndDelegate)
.bytecode(sendInternalAndDelegateInitcode)
.gas(300_000L)
.balance(2 * totalToSend)
).when(
cryptoCreate(beneficiary)
.balance(0L)
.keyShape(origKey.signedWith(sigs(ON, sendInternalAndDelegate)))
.receiverSigRequired(true)
.exposingCreatedIdTo(id -> beneficiaryAccountNum.set(id.getAccountNum()))
).then(
/* Without delegateContractId permissions, the second send via delegate call will
* fail, so only half of totalToSend will make it to the beneficiary. (Note the entire
* call doesn't fail because exceptional halts in "raw calls" don't automatically
* propagate up the stack like a Solidity revert does.) */
sourcing(() -> contractCall(
sendInternalAndDelegate,
SEND_REPEATEDLY_ABI,
justSendContractNum.get(),
beneficiaryAccountNum.get(),
totalToSend / 2)),
getAccountBalance(beneficiary).hasTinyBars(totalToSend / 2),
/* But now we update the beneficiary to have a delegateContractId */
newKeyNamed(newKey).shape(revisedKey.signedWith(sigs(ON, sendInternalAndDelegate))),
cryptoUpdate(beneficiary).key(newKey),
sourcing(() -> contractCall(
sendInternalAndDelegate,
SEND_REPEATEDLY_ABI,
justSendContractNum.get(),
beneficiaryAccountNum.get(),
totalToSend / 2)),
getAccountBalance(beneficiary).hasTinyBars(3 * (totalToSend / 2))
);
}
private HapiApiSpec receiverSigReqTransferRecipientMustSignWithFullPubKeyPrefix() {
final var justSendInitcode = "justSendInitcode";
final var sendInternalAndDelegateInitcode = "sendInternalAndDelegateInitcode";
final var justSend = "justSend";
final var sendInternalAndDelegate = "sendInternalAndDelegate";
final var beneficiary = "civilian";
final var balanceToDistribute = 1_000L;
final AtomicLong justSendContractNum = new AtomicLong();
final AtomicLong beneficiaryAccountNum = new AtomicLong();
return defaultHapiSpec("ReceiverSigReqTransferRecipientMustSignWithFullPubKeyPrefix")
.given(
cryptoCreate(beneficiary)
.balance(0L)
.receiverSigRequired(true)
.exposingCreatedIdTo(id -> beneficiaryAccountNum.set(id.getAccountNum())),
fileCreate(justSendInitcode)
.path(ContractResources.JUST_SEND_BYTECODE_PATH),
fileCreate(sendInternalAndDelegateInitcode)
.path(ContractResources.SEND_INTERNAL_AND_DELEGATE_BYTECODE_PATH)
).when(
contractCreate(justSend)
.bytecode(justSendInitcode)
.gas(300_000L)
.exposingNumTo(justSendContractNum::set),
contractCreate(sendInternalAndDelegate)
.bytecode(sendInternalAndDelegateInitcode)
.gas(300_000L)
.balance(balanceToDistribute)
).then(
/* Sending requires receiver signature */
sourcing(() -> contractCall(
sendInternalAndDelegate,
SEND_REPEATEDLY_ABI,
justSendContractNum.get(),
beneficiaryAccountNum.get(),
balanceToDistribute / 2)
.hasKnownStatus(INVALID_SIGNATURE)),
/* But it's not enough to just sign using an incomplete prefix */
sourcing(() -> contractCall(
sendInternalAndDelegate,
SEND_REPEATEDLY_ABI,
justSendContractNum.get(),
beneficiaryAccountNum.get(),
balanceToDistribute / 2)
.signedBy(DEFAULT_PAYER, beneficiary)
.hasKnownStatus(INVALID_SIGNATURE)),
/* We have to specify the full prefix so the sig can be verified async */
getAccountInfo(beneficiary).logged(),
sourcing(() -> contractCall(
sendInternalAndDelegate,
SEND_REPEATEDLY_ABI,
justSendContractNum.get(),
beneficiaryAccountNum.get(),
balanceToDistribute / 2)
.alsoSigningWithFullPrefix(beneficiary)),
getAccountBalance(beneficiary).logged()
);
}
private HapiApiSpec getsInsufficientPayerBalanceIfSendingAccountCanPayEverythingButServiceFee() {
final var initcode = "initcode";
final var firstContract = "firstContract";
final var secondContract = "secondContract";
final var civilian = "civilian";
final var creation = "creation";
final AtomicLong baseCreationFee = new AtomicLong();
return defaultHapiSpec("GetsInsufficientPayerBalanceIfSendingAccountCanPayEverythingButServiceFee")
.given(
cryptoCreate(civilian).balance(ONE_HUNDRED_HBARS),
fileCreate(initcode)
.path(ContractResources.MULTIPURPOSE_BYTECODE_PATH)
).when(
contractCreate(firstContract)
.bytecode(initcode)
.gas(80_000L)
.payingWith(civilian)
.balance(0L)
.via(creation),
getTxnRecord(creation).providingFeeTo(baseCreationFee::set).logged()
).then(
sourcing(() -> contractCreate(secondContract)
.bytecode(initcode)
.gas(80_000L)
.payingWith(civilian)
.balance(ONE_HUNDRED_HBARS - 2 * baseCreationFee.get())
.hasKnownStatus(INSUFFICIENT_PAYER_BALANCE))
);
}
private HapiApiSpec cannotCreateTooLargeContract() {
ByteString contents;
try {
contents =
ByteString.copyFrom(Files.readAllBytes(Path.of(ContractResources.LARGE_CONTRACT_CRYPTO_KITTIES)));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
final var FILE_KEY = "fileKey";
final var KEY_LIST = "keyList";
final var ACCOUNT = "acc";
return defaultHapiSpec("cannotCreateLargeContract")
.given(
newKeyNamed(FILE_KEY),
newKeyListNamed(KEY_LIST, List.of(FILE_KEY)),
cryptoCreate(ACCOUNT).balance(ONE_HUNDRED_HBARS * 10).key(FILE_KEY),
fileCreate("bytecode")
.path(ContractResources.LARGE_CONTRACT_CRYPTO_KITTIES)
.hasPrecheck(TRANSACTION_OVERSIZE)
)
.when(
fileCreate("bytecode").contents("").key(KEY_LIST),
UtilVerbs.updateLargeFile(ACCOUNT, "bytecode", contents)
)
.then(
contractCreate("contract")
.bytecode("bytecode")
.payingWith(ACCOUNT)
.hasKnownStatus(INSUFFICIENT_GAS)
);
}
private HapiApiSpec maxRefundIsMaxGasRefundConfiguredWhenTXGasPriceIsSmaller() {
return defaultHapiSpec("MaxRefundIsMaxGasRefundConfiguredWhenTXGasPriceIsSmaller")
.given(
UtilVerbs.overriding("contracts.maxRefundPercentOfGasLimit", "5"),
fileCreate("contractFile").path(ContractResources.VALID_BYTECODE_PATH)
).when(
contractCreate("testContract").bytecode("contractFile").gas(300_000L).via("createTX")
).then(
withOpContext((spec, ignore) -> {
final var subop01 = getTxnRecord("createTX").saveTxnRecordToRegistry("createTXRec");
CustomSpecAssert.allRunFor(spec, subop01);
final var gasUsed = spec.registry().getTransactionRecord("createTXRec")
.getContractCreateResult().getGasUsed();
assertEquals(285_000L, gasUsed);
}),
UtilVerbs.resetAppPropertiesTo("src/main/resource/bootstrap.properties")
);
}
private HapiApiSpec minChargeIsTXGasUsedByContractCreate() {
return defaultHapiSpec("MinChargeIsTXGasUsedByContractCreate")
.given(
UtilVerbs.overriding("contracts.maxRefundPercentOfGasLimit", "100"),
fileCreate("contractFile").path(ContractResources.VALID_BYTECODE_PATH)
).when(
contractCreate("testContract").bytecode("contractFile").gas(300_000L).via("createTX")
).then(
withOpContext((spec, ignore) -> {
final var subop01 = getTxnRecord("createTX").saveTxnRecordToRegistry("createTXRec");
CustomSpecAssert.allRunFor(spec, subop01);
final var gasUsed = spec.registry().getTransactionRecord("createTXRec")
.getContractCreateResult().getGasUsed();
Assertions.assertTrue(gasUsed > 0L);
}),
UtilVerbs.resetAppPropertiesTo("src/main/resource/bootstrap.properties")
);
}
private HapiApiSpec gasLimitOverMaxGasLimitFailsPrecheck() {
return defaultHapiSpec("GasLimitOverMaxGasLimitFailsPrecheck")
.given(
UtilVerbs.overriding("contracts.maxGas", "100"),
fileCreate("contractFile").path(ContractResources.VALID_BYTECODE_PATH)
).when().then(
contractCreate("testContract").bytecode("contractFile").gas(101L).hasPrecheck(
MAX_GAS_LIMIT_EXCEEDED),
UtilVerbs.resetAppPropertiesTo("src/main/resource/bootstrap.properties")
);
}
HapiApiSpec vanillaSuccess() {
return defaultHapiSpec("VanillaSuccess")
.given(
fileCreate("parentDelegateBytecode").path(ContractResources.DELEGATING_CONTRACT_BYTECODE_PATH),
contractCreate("parentDelegate").bytecode("parentDelegateBytecode").adminKey(THRESHOLD),
getContractInfo("parentDelegate").logged().saveToRegistry("parentInfo"),
upMaxGasTo(1_000_000L)
).when(
contractCall("parentDelegate", ContractResources.CREATE_CHILD_ABI)
.gas(1_000_000L)
.via("createChildTxn"),
contractCall("parentDelegate", ContractResources.GET_CHILD_RESULT_ABI)
.gas(1_000_000L)
.via("getChildResultTxn"),
contractCall("parentDelegate", ContractResources.GET_CHILD_ADDRESS_ABI)
.gas(1_000_000L)
.via("getChildAddressTxn")
).then(
getTxnRecord("createChildTxn")
.saveCreatedContractListToRegistry("createChild")
.logged(),
getTxnRecord("getChildResultTxn")
.hasPriority(recordWith().contractCallResult(
resultWith().resultThruAbi(
ContractResources.GET_CHILD_RESULT_ABI,
isLiteralResult(new Object[] { BigInteger.valueOf(7L) })))),
getTxnRecord("getChildAddressTxn")
.hasPriority(recordWith().contractCallResult(
resultWith()
.resultThruAbi(
ContractResources.GET_CHILD_ADDRESS_ABI,
isContractWith(contractWith()
.nonNullContractId()
.propertiesInheritedFrom("parentInfo")))
.logs(inOrder()))),
contractListWithPropertiesInheritedFrom(
"createChildCallResult", 1, "parentInfo"),
restoreDefaultMaxGas()
);
}
private HapiSpecOperation upMaxGasTo(final long amount) {
return fileUpdate(APP_PROPERTIES)
.fee(ONE_HUNDRED_HBARS)
.payingWith(EXCHANGE_RATE_CONTROL)
.overridingProps(Map.of(
"contracts.maxGas", "" + amount
));
}
private HapiSpecOperation restoreDefaultMaxGas() {
return fileUpdate(APP_PROPERTIES)
.fee(ONE_HUNDRED_HBARS)
.payingWith(EXCHANGE_RATE_CONTROL)
.overridingProps(Map.of(
"contracts.maxGas", defaultMaxGas
));
}
@Override
protected Logger getResultsLogger() {
return log;
}
}
| 39.796657 | 115 | 0.731189 |
bb6527c910a475ce98a3e3e01bb19c60a19c9bf8 | 14,067 | import com.sun.source.tree.AssertTree;
import java.awt.dnd.InvalidDnDOperationException;
import java.util.Random;
/**
* Created by Stas on 04/04/2015.
*/
public class BigIntTests
{
public static void allTests()
{
CPrint.blue("============== isValid tests ==============\n");
isValidTests();
CPrint.blue("============== toString tests ==============\n");
toStringTests();
CPrint.blue("============== equals tests ==============\n");
equalsTests();
CPrint.blue("============== compareTo tests ==============\n");
compareToTests();
CPrint.blue("============== plus tests ==============\n");
plusTests();
CPrint.blue("============== minus tests ==============\n");
minusTests();
CPrint.blue("============== multiply tests ==============\n");
multiplyTests();
CPrint.blue("============== divide tests ==============\n");
divideTests();
}
private static void isValidTests()
{
isValidTest("0000000000333", true);
isValidTest("not a number", false);
isValidTest("9239392392x", false);
isValidTest("", false);
isValidTest("323323232", true);
isValidTest("-333000333", true);
isValidTest("+9", true);
isValidTest("+", false);
isValidTest("-", false);
isValidTest("+-3", false);
isValidTest("4554-", false);
isValidTest(" 455 ", true);
isValidTest(" - 343434430 ", true);
isValidTest("+0", true);
isValidTest("343443433443843894389027094720934709237409237409237490273940374020", true);
isValidTest("-3434434334438443434409472093470923740923997409237490273940374020", true);
isValidTest("3.149509", false);
isValidTest("343434343,43434,3443.", false);
}
private static void isValidTest(String input, Boolean shouldBeValid)
{
try
{
BigInt num1 = new BigInt(input);
if (shouldBeValid)
{
assertTrue(true, "'" + input + "' is a valid number");
}
else
{
assertTrue(false, "'" + input + "' Should be an invalid number but is a valid instead");
}
}
catch (IllegalArgumentException ex)
{
if (shouldBeValid)
{
assertTrue(false, "'" + input + "' Should be a valid number");
}
else
{
assertTrue(true, "'" + input + "' is an invalid number");
}
}
catch (Exception ex)
{
assertTrue(false, "Got exception while create BigInt: " + ex.getMessage());
}
}
private static void toStringTests()
{
BigInt num1 = new BigInt("1234567890667");
assertEquals(num1.toString(), "1234567890667", "toString test 1");
BigInt num2 = new BigInt("-987");
assertEquals(num2.toString(), "-987", "toString test 2");
BigInt num3 = new BigInt("+9966637383");
assertEquals(num3.toString(), "9966637383", "toString test 3");
BigInt num4 = new BigInt("0000000000000");
assertEquals(num4.toString(), "0", "toString test 4");
BigInt num5 = new BigInt("-0013");
assertEquals(num5.toString(), "-13", "toString test 5");
BigInt num6 = new BigInt(" 449980 ");
assertEquals(num6.toString(), "449980", "toString test 6");
BigInt num7 = new BigInt("-929283998723929283998723879234784932894239824328943723767842358461971000099999988879234784932894239824328943723767842358461971000099999988");
assertEquals(num7.toString(), "-929283998723929283998723879234784932894239824328943723767842358461971000099999988879234784932894239824328943723767842358461971000099999988", "toString test 7");
BigInt num8 = new BigInt("-0000000000000");
assertEquals(num8.toString(), "0", "toString test 8");
}
private static void plusTests()
{
plusTest("123", "321", "444", "plus test 1");
plusTest("999", "22", "1021", "plus test 2");
plusTest("9999999913213123131312312312319", "10001", "9999999913213123131312312322320", "plus test 3");
plusTest("0", "0", "0", "plus test 4");
plusTest("0", "55", "55", "plus test 5");
plusTest("100000000100000000100000000", "100000000100000000100000000", "200000000200000000200000000", "plus test 6");
plusTest("198889", "-999", "197890", "plus test 7");
plusTest("-110", "-220", "-330", "plus test 8");
plusTest("100", "-9990", "-9890", "plus test 9");
plusTest("-8744443433434334432211100000000000000000000000000090000", "+8744443433434334432211100000000000000000000000000090000", "0", "plus test 10");
//RANDOM tests
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
long rnd1 = rnd.nextLong() / 10;
long rnd2 = rnd.nextLong() / 10;
plusTest("" + rnd1, "" + rnd2, "" + (rnd1 + rnd2), "random plus test #" + i);
}
}
private static void minusTests()
{
minusTest("1000000", "1", "999999", "minus test 1");
minusTest("-1000000", "-1", "-999999", "minus test 2");
minusTest("10", "5", "5", "minus test 3");
minusTest("104", "104", "0", "minus test 4");
minusTest("104", "0", "104", "minus test 5");
//RANDOM tests
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
long rnd1 = rnd.nextLong() / 10;
long rnd2 = rnd.nextLong() / 10;
minusTest("" + rnd1, "" + rnd2, "" + (rnd1 - rnd2), "random minus test #" + i);
}
}
private static void multiplyTests()
{
multiplyTest("2", "2", "4", "multiply test 1");
multiplyTest("234", "41", "9594", "multiply test 2");
multiplyTest("55", "0", "0", "multiply test 3");
multiplyTest("2323234569938811391023232345699388113910", "10000", "23232345699388113910232323456993881139100000", "multiply test 4");
multiplyTest("55", "0", "0", "multiply test 5");
multiplyTest("54544", "-1", "-54544", "multiply test 6");
multiplyTest("999999", "-99", "-98999901", "multiply test 7");
multiplyTest("-25", "-25", "625", "multiply test 8");
multiplyTest("-99", "22", "-2178", "multiply test 9");
multiplyTest("22", "-99", "-2178", "multiply test 10");
multiplyTest("2", "-1111111", "-2222222", "multiply test 11");
multiplyTest("22", "-13313", "-292886", "multiply test 12");
multiplyTest("-0", "233203", "0", "multiply test 13");
multiplyTest("2332323232323232231122299", "1", "2332323232323232231122299", "multiply test 14");
multiplyTest("123456", "123456", "15241383936", "multiply test 15");
}
private static void divideTests()
{
devideTest("100", "25", "4", "divide test 1");
devideTest("100", "1", "100", "divide test 2");
devideTest("0", "4654641", "0", "divide test 3");
devideTest("55", "10", "5", "divide test 4");
devideTest("-88", "16", "-5", "divide test 5");
devideTest("1545454543434343434334344343435454", "5554554546464566664645645645666", "278", "divide test 6");
devideTest("1", "146446", "0", "divide test 7");
devideTest("17788", "17788", "1", "divide test 8");
devideTest("17788", "17789", "0", "divide test 9");
devideTest("17788", "-17788", "-1", "divide test 10");
devideTest("-17788", "17788", "-1", "divide test 11");
devideTest("6", "3", "2", "divide test 12");
devideTest("-6", "-3", "2", "divide test 13");
devideTest("7", "6", "1", "divide test 14");
devideTest("-1222222222", "-100000", "12222", "divide test 15");
}
private static void plusTest(String num1, String num2, String expectedSum, String msg)
{
BigInt bigNum1 = new BigInt(num1);
BigInt bigNum2 = new BigInt(num2);
BigInt expectedBigSum = new BigInt(expectedSum);
assertEquals(bigNum1.plus(bigNum2).toString(), expectedBigSum.toString(), msg);
}
private static void minusTest(String num1, String num2, String expectedSum, String msg)
{
BigInt bigNum1 = new BigInt(num1);
BigInt bigNum2 = new BigInt(num2);
BigInt expectedBigSum = new BigInt(expectedSum);
assertEquals(bigNum1.minus(bigNum2).toString(), expectedBigSum.toString(), msg);
}
private static void multiplyTest(String num1, String num2, String expectedSum, String msg)
{
BigInt bigNum1 = new BigInt(num1);
BigInt bigNum2 = new BigInt(num2);
BigInt expectedBigSum = new BigInt(expectedSum);
assertEquals(bigNum1.multiply(bigNum2).toString(), expectedBigSum.toString(), msg);
}
private static void devideTest(String num1, String num2, String expectedSum, String msg)
{
BigInt bigNum1 = new BigInt(num1);
BigInt bigNum2 = new BigInt(num2);
BigInt expectedBigSum = new BigInt(expectedSum);
assertEquals(bigNum1.divide(bigNum2).toString(), expectedBigSum.toString(), msg);
}
private static void equalsTests()
{
assertEquals(new BigInt("123456789"), new BigInt("123456789"), "equals test 1");
assertEquals(new BigInt("-1113232131"), new BigInt("-1113232131"), "equals test 2");
assertEquals(new BigInt("0000000000000"), new BigInt("0"), "equals test 3");
assertEquals(new BigInt("+0000000"), new BigInt("-000"), "equals test 4");
assertEquals(new BigInt("+0014"), new BigInt("14"), "equals test 5");
assertNotEquals(new BigInt("1828289"), new BigInt("-1828289"), "equals test 6");
assertNotEquals(new BigInt("+18282894"), new BigInt("-18282894"), "equals test 7");
assertEquals(new BigInt("280012931883488490100891209129890091889280012931883488490100891209129890091889319877112231987711222800129318834884901008912091298900918893198771122"), new BigInt("280012931883488490100891209129890091889280012931883488490100891209129890091889319877112231987711222800129318834884901008912091298900918893198771122"), "equals test 8");
assertEquals(new BigInt(" + 9999999999 "), new BigInt("9999999999"), "equals test 9");
assertEquals(new BigInt(" - 4444 "), new BigInt("-0004444"), "equals test 10");
assertEquals(new BigInt("-992389239289383923289893298238923982398239823323211"), new BigInt("-992389239289383923289893298238923982398239823323211"), "equals test 11");
assertEquals(new BigInt("-00000001"), new BigInt("-1"), "equals test 12");
assertEquals(new BigInt("4"), new BigInt("4"), "equals test 13");
assertEquals(new BigInt("004"), new BigInt("04"), "equals test 14");
assertEquals(new BigInt("+030"), new BigInt("30"), "equals test 15");
assertNotEquals(new BigInt("546464"), new BigInt("646333"), "equals test 16");
assertNotEquals(new BigInt("-646322"), new BigInt("-646333"), "equals test 17");
}
private static void compareToTests()
{
assertEquals(new BigInt("0").compareTo(new BigInt("0")), 0, "equals test 0");
assertEquals(new BigInt("2234234324324324124141491914941491249").compareTo(new BigInt("2234234324324324124141491914941491248")), 1, "equals test 1");
assertEquals(new BigInt("1123112113209494538543845374537543999").compareTo(new BigInt("1123112113209494538543845374537544000")), -1, "equals test 2");
assertEquals(new BigInt("2332323232323245467654546576879654393").compareTo(new BigInt("2332323232323245467654546576879654393")), 0, "equals test 3");
assertEquals(new BigInt("-1000").compareTo(new BigInt("-1001")), 1, "equals test 4");
assertEquals(new BigInt("-1000").compareTo(new BigInt("-999")), -1, "equals test 5");
assertEquals(new BigInt("-99993").compareTo(new BigInt("-99993")), 0, "equals test 6");
assertEquals(new BigInt("0").compareTo(new BigInt("1")), -1, "equals test 7");
assertEquals(new BigInt("-1").compareTo(new BigInt("1")), -1, "equals test 8");
assertEquals(new BigInt("1").compareTo(new BigInt("-1")), 1, "equals test 9");
assertEquals(new BigInt("99").compareTo(new BigInt("100")), -1, "equals test 10");
assertEquals(new BigInt("100").compareTo(new BigInt("99")), 1, "equals test 11");
assertEquals(new BigInt("-999").compareTo(new BigInt("-1000")), 1, "equals test 12");
assertEquals(new BigInt("-3223323232323232").compareTo(new BigInt("0")), -1, "equals test 13");
assertEquals(new BigInt("0").compareTo(new BigInt("3232323233232")), -1, "equals test 14");
assertEquals(new BigInt("9999").compareTo(new BigInt("99999")), -1, "equals test 15");
assertEquals(new BigInt("09999").compareTo(new BigInt("99999")), -1, "equals test 16");
assertEquals(new BigInt("000000").compareTo(new BigInt("000")), 0, "equals test 17");
assertEquals(new BigInt("-0").compareTo(new BigInt("+0")), 0, "equals test 18");
}
public static void assertEquals(Object o1, Object o2, String desc)
{
if (o1.equals(o2))
{
CPrint.green("[PASS] ");
System.out.println(desc + "\t(" + o1 + " is equal to " + o2 + ")");
}
else
{
CPrint.red("[FAIL] ");
CPrint.red(desc + "\t(" + o1 + " is not equal to " + o2 + ")\n");
}
}
public static void assertNotEquals(Object o1, Object o2, String desc)
{
if (o1.equals(o2))
{
CPrint.red("[FAIL] ");
CPrint.red(desc + "\t(" + o1 + " shouldn't be equal to " + o2 + ")\n");
}
else
{
CPrint.green("[PASS] ");
System.out.println(desc + "\t(" + o1 + " is not equal to " + o2 + ")");
}
}
public static void assertTrue(Boolean condition, String desc)
{
assertEquals(condition, true, desc);
}
}
| 45.086538 | 364 | 0.594085 |
e2ca3b1c91dce0dee005c130ccb4fbace63c7877 | 26,822 | package net.noyark.www.xml;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import cn.gulesberry.www.exception.IllegalMappingException;
import cn.gulesberry.www.exception.IndexLengthException;
import cn.gulesberry.www.helper.InstanceQueryer;
import net.noyark.www.annotations.Param;
import net.noyark.www.core.Assert;
import net.noyark.www.core.LazyInstance;
import net.noyark.www.core.NoyarkApplicationContext;
import net.noyark.www.core.ProtoTypeInstance;
import net.noyark.www.exception.AliasException;
import net.noyark.www.exception.AttributeException;
import net.noyark.www.exception.NoSuchBeanException;
import net.noyark.www.exception.NoneStaticException;
import net.noyark.www.interf.XMLDomFile;
public class XMLHandler {
private List<String> scanPackage = new ArrayList<>();
private Map<String, Object> objPool = new HashMap<String, Object>();
private Map<Object, Method> obj_despory = new HashMap<Object, Method>();
private Map<Object,Map<Object,Object>> properties_pool = new HashMap<>();
private String file;
public XMLHandler(String file,boolean... isStream) throws Exception{
this.file = file;
readBeanXML(isStream);
}
void readBeanXML(boolean... isStream) throws Exception {
XMLDomFile xdf = InstanceQueryer.getDefaultXml(file,this,isStream);
xdf.clearMapping();
parsePropertiesFile(xdf);//properties file
parseCommonBean(xdf);//解析只有id和name的bean
parseFactoryBean(xdf);//解析有工厂方法的
parseOtherBeanFactoryBean(xdf);//对象工厂
alias(xdf);//别名
parseScope(xdf);//scope
initAndDesporyBean(xdf);//despory
autowiredBean(xdf);
setProperty(xdf);//property
lazyInstance(xdf);//lazy
addSet(xdf);//set
addMap(xdf);//map
setListArray(xdf);//list and array
setProps(xdf);//props
parseConstructor(xdf);//constructor
parsePackageScan(xdf);
}
//普通的bean
private void parseCommonBean(XMLDomFile xdf) throws IllegalMappingException, IndexLengthException, DocumentException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
List<Element> list = xdf.getElementsByAttributesAndNameOnlyThese("bean","id","class");
list.addAll(xdf.getElementsByAttributesAndNameOnlyThese("bean","name","class"));
for(Element e:list) {
Attribute id = e.attribute("id")==null?e.attribute("name"):e.attribute("id");
String idValue = id.getValue();
Attribute clazz = e.attribute("class");
String clazzValue = clazz.getValue();
Object instance = Class.forName(clazzValue).newInstance();
Assert.notRepeat(objPool, idValue);
objPool.put(idValue, instance);
}
}
//factory-method
private void parseFactoryBean(XMLDomFile xdf) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
List<Element> list = xdf.getElementsByAttributesAndNameOnlyThese("bean","id","class","factory-method");
list.addAll(xdf.getElementsByAttributesAndNameOnlyThese("bean","name","class","factory-method"));
for(Element e:list) {
Attribute id = e.attribute("id")==null?e.attribute("name"):e.attribute("id");
Attribute clazzAttr = e.attribute("class");
String clazzValue = clazzAttr.getValue();
Attribute factory = e.attribute("factory-method");
String factoryValue = factory.getValue();
Class<?> clz = Class.forName(clazzValue);
Method factoryMethod = clz.getDeclaredMethod(factoryValue);
try {
Assert.notRepeat(objPool, id.getValue());
Object o = factoryMethod.invoke(null);
objPool.put(id.getValue(),o);
}catch(Exception ex){
throw new NoneStaticException("the factory method is not static");
}
}
}
//factory-class method
private void parseOtherBeanFactoryBean(XMLDomFile xdf) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
List<Element> list = xdf.getElementsByAttributesAndNameOnlyThese("bean","id","factory-bean","factory-method");
list.addAll(xdf.getElementsByAttributesAndNameOnlyThese("bean","name","factory-bean","factory-method"));
for(Element e:list) {
Attribute id = e.attribute("id")==null?e.attribute("name"):e.attribute("id");
String factoryBean = e.attribute("factory-bean").getValue();
Attribute factoryMethod = e.attribute("factory-method");
Object factory_bean = objPool.get(factoryBean);
if(factory_bean==null) {
throw new NoSuchBeanException("no "+factoryBean+" bean");
}
Assert.notRepeat(objPool, id.getValue());
Method factory_method = factory_bean.getClass().getDeclaredMethod(factoryMethod.getValue());
Object bean = factory_method.invoke(factory_bean);
objPool.put(id.getValue(),bean);
}
}
private void alias(XMLDomFile xdf) {
List<Element> aliases = xdf.getElementsByAttributesAndNameOnlyThese("alias");
for(Element alias:aliases) {
Attribute id = alias.attribute("id")==null?alias.attribute("name"):alias.attribute("id");
if(id==null) {
throw new AliasException("the alias don't have the default id");
}
Attribute aliasAttr = alias.attribute("alias");
if(aliasAttr==null) {
throw new AliasException("the alias don't have the alias mapping");
}
objPool.put(aliasAttr.getValue(),objPool.get(id.getValue()));
}
}
//作用域
private void parseScope(XMLDomFile xdf) throws ClassNotFoundException {
List<Element> elements = xdf.getElementsByAttributesAndNameOnlyThese("bean","id","class","scope");
elements.addAll(xdf.getElementsByAttributesAndNameOnlyThese("bean","name","class","scope"));
for(Element e:elements) {
Attribute id = e.attribute("id");
if(id==null) {
id = e.attribute("name");
}
String clazz = e.attribute("class").getValue();
String scope = e.attribute("scope").getValue();
Assert.notRepeat(objPool, id.getValue());
if(scope.equals("prototype")) {
objPool.put(id.getValue(),new ProtoTypeInstance(Class.forName(clazz)));
}
}
}
private void initAndDesporyBean(XMLDomFile xdf) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
List<Element> list = xdf.getElementsByAttributesAndNameOnlyThese("bean","id","class","init-method","despory-method");
for(Element e:list) {
Attribute id = e.attribute("id")==null?e.attribute("name"):e.attribute("id");
String clazz = e.attributeValue("class");
String init_method = e.attributeValue("init-method");
String despory_method = e.attributeValue("despory-method");
Class<?> objClazz = Class.forName(clazz);
Object o = objClazz.newInstance();
Method m = objClazz.getDeclaredMethod(init_method);
m.invoke(o);
Assert.notRepeat(objPool, id.getValue());
objPool.put(id.getValue(),o);
obj_despory.put(o,objClazz.getDeclaredMethod(despory_method));
}
}
@SuppressWarnings("unchecked")
private void setProperty(XMLDomFile xdf) throws Exception {
List<Element> allElements = xdf.getElementsByAttributesAndName("bean","id");
allElements.addAll(xdf.getElementsByAttributesAndName("bean","name"));
for(Element e:allElements) {
String id = e.attributeValue("id");
if(id==null) {
id = e.attributeValue("name");
}
Object instance = objPool.get(id);
List<Element> propertys = e.elements("property");
if(instance!=null) {
Class<?> clz = instance.getClass();
for(Element p:propertys) {
String name = p.attributeValue("name");
Field field = clz.getDeclaredField(name);
field.setAccessible(true);
Object value = p.attributeValue("value");
if(value==null) {
value = objPool.get(p.attributeValue("ref"));
}
if(value!=null) {
if(value.toString().startsWith("#{")) {
Object result = parseExpressions(value+"", xdf);
if(result!= value+"") {
value = result;
}
}
}
if(value!=null&&value.getClass().equals(String.class)) {
String val = (String)value;
Class<?> type = field.getType();
if(type.equals(int.class)||type.equals(Integer.class)) {
value = Integer.parseInt(val);
}else if(type.equals(boolean.class)||type.equals(Boolean.class)) {
value = Boolean.parseBoolean(val);
}else if(type.equals(byte.class)||type.equals(Boolean.class)) {
value = Byte.parseByte(val);
}else if(type.equals(short.class)||type.equals(Short.class)) {
value = Short.parseShort(val);
}else if(type.equals(char.class)||type.equals(Character.class)) {
value = val.charAt(0);
}else if(type.equals(long.class)||type.equals(Long.class)) {
value = Long.parseLong(val);
}else if(type.equals(double.class)||type.equals(Double.class)) {
value = Double.parseDouble(val);
}else if(type.equals(float.class)||type.equals(Float.class)) {
value = Float.parseFloat(val);
}
}
field.set(instance,value);
addInPool(name, value, instance);
}
}
}
}
public void addInPool(Object name,Object value,Object instance) {
Map<Object, Object> property = properties_pool.get(instance)==null?new HashMap<>():properties_pool.get(instance);
property.put(name, value);
properties_pool.put(instance,property);
}
public void setListArray(XMLDomFile xdf) throws Exception{
addCollection(xdf, "list","array",List.class);
}
public void lazyInstance(XMLDomFile xdf) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException {
List<Element> list = xdf.getElementsByAttributesAndName("bean","id","class","lazy-init");
list.addAll(xdf.getElementsByAttributesAndName("bean","name","class","lazy-init"));
for(Element e:list) {
String id = e.attributeValue("id")==null?e.attributeValue("name"):e.attributeValue("id");
Class<?> clz = Class.forName(e.attributeValue("class"));
boolean isLazy = Boolean.parseBoolean(e.attributeValue("lazy-init"));
if(isLazy) {
String initMethod = e.attributeValue("init-method");
String factoryMethod = e.attributeValue("factory-method");
String factoryBean = e.attributeValue("factory-bean");
String desportyMethod = e.attributeValue("despory-method");
if(initMethod!=null&&factoryMethod!=null&&factoryMethod!=null) {
Method init = clz.getMethod(initMethod);
Method despory = clz.getMethod(desportyMethod);
Object bean = objPool.get(factoryBean);
Method method = null;
if(factoryBean!=null) {
method = bean.getClass().getDeclaredMethod(factoryMethod);
}
objPool.put(id,new LazyInstance(clz, init,despory, method, bean));
}
if(initMethod!=null) {
Method init = clz.getMethod(initMethod);
objPool.put(id, new LazyInstance(clz, init,clz.getDeclaredMethod(desportyMethod),null,null));
return;
}
if(factoryBean!=null) {
Object bean = objPool.get(factoryBean);
Method method = null;
if(factoryBean!=null) {
method = bean.getClass().getDeclaredMethod(factoryMethod);
}
objPool.put(id,new LazyInstance(clz, null, null, method, bean));
}
objPool.put(id,new LazyInstance(clz,null,null,null,null));
}else {
objPool.put(id, clz.newInstance());
}
}
}
private void addSet(XMLDomFile xdf) throws Exception {
addCollection(xdf,"set","set",Set.class);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addMap(XMLDomFile xdf) throws Exception {
List<Element> allElements = xdf.getElementsByAttributesAndName("bean","id");
allElements.addAll(xdf.getElementsByAttributesAndName("bean","name"));
Map map;
for(Element e:allElements) {
String id = e.attributeValue("id")==null?e.attributeValue("name"):e.attributeValue("id");
String classname = e.attributeValue("class");
Class<?> cls;
if(classname!=null) {
cls = Class.forName(classname);
}else {
cls = objPool.get(id).getClass();
}
List<Element> properties = e.elements("property");
for(Element property:properties) {
if(property.attributeValue("value")==null||property.attributeValue("ref")==null) {
String listName = property.attributeValue("name");
Field field = cls.getDeclaredField(listName);
field.setAccessible(true);
Element list = property.element("map");
if(list!=null) {
String keyType = property.attributeValue("key-type");
String valType = property.attributeValue("value-type");
List<Element> values = list.elements("entry");//entry节点
//不指定类型就是默认String-String类型
if(keyType==null) {
map = new LinkedHashMap<String,String>();
for(Element entry:values) {
String key = entry.attributeValue("key");
String value = entry.attributeValue("value");
if(value==null) {
value = entry.element("value").getText();
}
map.put(key, value);
}
}else {
map = getMap(Class.forName(keyType),Class.forName(valType));
for(Element entry:values) {
Object key = entry.attributeValue("key");
Object value = entry.attributeValue("ref");
if(value!=null) {
Object[] vals = {key,value};
for(Object val:vals) {
if(val.toString().startsWith("#{")) {
Object result = parseExpressions(val+"", xdf);
if(result!= val+"") {
val = result;
}
}
}
}
if(keyType.equals("java.lang.String")) {
map.put(key, objPool.get(value));
}else {
map.put(objPool.get(key),objPool.get(value));
}
}
}
field.set(objPool.get(id),map);
}
}
}
}
}
//动态map泛型
private <K,V> Map<K, V> getMap(Class<K> key,Class<V> value) {
return new LinkedHashMap<K,V>();
}
//动态list泛型
public <T> List<T> getList(Class<T> cls){
return new ArrayList<T>();
}
//动态Set泛型
private <S> Set<S> getSet(Class<S> cls){
return new LinkedHashSet<S>();
}
//泛型类型为Object
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addCollection(XMLDomFile xdf,String type1,String type2,Class<?> type) throws Exception {
List<Element> allElements = xdf.getElementsByAttributesAndName("bean","id");
allElements.addAll(xdf.getElementsByAttributesAndName("bean","name"));
for(Element e:allElements) {
List<Element> properties = e.elements("property");
String classname = e.attributeValue("class");
Class<?> clazz;
String id = e.attributeValue("id")==null?e.attributeValue("name"):e.attributeValue("id");
if(classname!=null) {
clazz = Class.forName(classname);
}else {
clazz = objPool.get(id).getClass();
}
for(Element property:properties) {
if(property.attributeValue("value")==null||property.attributeValue("ref")==null) {
String listName = property.attributeValue("name");
Element ele = property.element(type1);
if(ele==null) {
ele = property.element(type2);
}
if(ele!=null) {
List<Element> values = ele.elements("value");//有value子节点
//获取values且每个value都有ref属性,type='type'
String valueType = property.attributeValue("type");//有ref
if(valueType!=null) {
Collection listObject;
if(type.equals(List.class)) {
listObject = getList(Class.forName(valueType));
}else {
listObject = getSet(Class.forName(valueType));
}
Field f = clazz.getDeclaredField(listName);
f.setAccessible(true);
for(Element val:values) {
Object value = val.attributeValue("ref");
if(value.toString().startsWith("#{")) {
Object result = parseExpressions(value+"", xdf);
if(result!= value+"") {
value = result;
}
}
Object o = objPool.get(value);
listObject.add(o);
}
f.set(objPool.get(id),listObject);
addInPool(listName, listObject, objPool.get(id));
}else {
setValue(type, clazz, listName,values,id);//直接找
}
}
}
}
}
}
//设XMLDomFile xdf,String type1,String type2,Class<?> type置value
private void setValue(Class<?> type,Class<?> clazz,String listName,List<Element> values,String id) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchFieldException, SecurityException {
//当value==null
Collection<String> listObject = null;
if(type.equals(List.class)) {
listObject = new ArrayList<>();
}else {
listObject = new LinkedHashSet<>();
}
for(Element value:values) {
listObject.add(value.getText());
}
Field f = clazz.getDeclaredField(listName);
if(f.getType().isArray()) {
f.setAccessible(true);
f.set(objPool.get(id),listObject.toArray());
addInPool(listName,listObject.toArray(), objPool.get(id));
}else {
f.set(objPool.get(id),listObject);
addInPool(listName,listObject, objPool.get(id));
}
}
//Properties
@SuppressWarnings("unchecked")
private void setProps(XMLDomFile xdf) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<Element> beans = xdf.getElementsByAttributesAndName("bean","id");
beans.addAll(xdf.getElementsByAttributesAndName("bean","name"));
for(Element bean:beans) {
String classname = bean.attributeValue("class");
String id = bean.attributeValue("id");
if(id==null) {
id = bean.attributeValue("name");
}
Class<?> clz;
if(classname!=null) {
clz= Class.forName(classname);
}else {
clz = objPool.get(id).getClass();
}
List<Element> properties = bean.elements("property");
for(Element property:properties) {
String propertyName = property.attributeValue("name");
Field field = clz.getDeclaredField(propertyName);
field.setAccessible(true);
Element property_props = property.element("props");
if(property_props!=null) {
Properties propObject = new Properties();
List<Element> props_prop = property_props.elements("prop");
for(Element prop:props_prop) {
String value = prop.getText();
String key = prop.attributeValue("key");
propObject.put(key, value);
}
field.set(objPool.get(id), propObject);
addInPool(propertyName,propObject, objPool.get(id));
}
}
}
}
private void parsePropertiesFile(XMLDomFile xdf) throws Exception {
List<Element> properties = xdf.getElementsByNameSpace("http://www.noyark.net:8081/util",true);
for(Element e:properties) {
if(e.getName().equals("properties")) {
String location = e.attributeValue("location");
String filename = location.substring("classpath:".length());
if(location.startsWith("classpath:")) {
location = (this.getClass().getResource("/").getPath()+location.substring("classpath:".length())).replaceAll("test-classes", "classes");
}
Assert.notNull(location,new AttributeException("No location attribute->util:properties"));
String id = e.attributeValue("name");
if(id ==null) {
id = filename;
}
Properties props = new Properties();
props.load(new FileInputStream(location));
objPool.put(id,props);
}
}
}
@SuppressWarnings({ "unchecked"})
private Object parseExpressions(String value,XMLDomFile xdf) throws Exception {
if(value.startsWith("#{")&&value.endsWith("}")) {
String string = value.substring(value.indexOf("{")+1,value.indexOf("}"));
String propertyPoint = null;
if(string.indexOf("!")!=-1) {
String before = string;
string = string.substring(0,string.indexOf("!")-1);
propertyPoint = before.substring(before.indexOf("!")+1,before.lastIndexOf("!"));
}
String[] expressions = string.split("\\.");
String id = expressions[0];
List<Element> elements = xdf.getElementsByAttribut("id",id);
if(elements.size()==0) {
elements = xdf.getElementsByAttribut("name",id);
}
//属性
Element theBeanXML = null;
for(Element e:elements) {
if(e.getName().equals("bean")&&(id.equals(e.attributeValue("id"))||id.equals(e.attributeValue("name")))) {
theBeanXML = e;
}
}
String property = null;
if(expressions.length>1) {
property = expressions[1];
}
List<Element> es = xdf.getElementsByNameSpace("http://www.noyark.net:8081/util",true);
for(Element e:es) {
String propId = e.attributeValue("name")==null?e.attributeValue("id"):e.attributeValue("name");
if(e.getName().equals("properties")&&id.equals(propId)) {
Properties object = (Properties)objPool.get(propId);
if(propertyPoint!=null) {
return object.getProperty(propertyPoint);
}
return object.getProperty(property);
}
}
Assert.notNull(theBeanXML, new NoSuchBeanException("no bean named "+id));
List<Element> properties = theBeanXML.elements("property");
for(Element prop:properties) {
if(property.equals(prop.attributeValue("name"))) {
String val = prop.attributeValue("value");
if(val!=null) {
value = val;
return value;
}else {
String ref = prop.attributeValue("ref");
if(ref!=null) {
Object o = objPool.get(ref);//获取ref指向的
return o;
}else {
String entryName = expressions[2];
//不指向ref也不指向value,但没有[],就是map或者props
Object informationMap = getMapInformation(prop, entryName, "map", "entry");
if(informationMap==null) {
Object informationProperties = getMapInformation(prop, entryName, "props", "prop");
if(informationProperties!=null) {
return informationProperties;
}
}else{
return informationMap;
}
}
}
}else if(property.indexOf("[")!=-1&&property.substring(0,property.indexOf("[")).equals(prop.attributeValue("name"))) {
Integer index = Integer.parseInt(property.substring(property.indexOf("[")+1,property.indexOf("]")));
Element element = prop.element("list");
if(element == null) {
element = prop.element("array");
}
if(element == null) {
element = prop.element("set");
}
Object object = getListOrSet(element, index);
if(object!=null) {
return object;
}
}
}
}
return value;
}
@SuppressWarnings("null")
private Object getMapInformation(Element prop,String entryName,String parent,String child) throws Exception {
Element map = prop.element(parent);//map
if(map!=null) {
@SuppressWarnings("unchecked")
List<Element> entrys = map.elements(child);//entry
for(Element entry:entrys) {//entry节点
String entryNameTruly =entry.attributeValue("name");
if(entryNameTruly==null) {
entryNameTruly = entry.attributeValue("key");
}
if(entryName.equals(entryNameTruly)) {
String entryText = entry.getTextTrim();
if(entryText!=null||!entryText.equals("")) {
return entryText;
}
String entryValue = entry.attributeValue("value");
if(entryValue==null) {
String entryRef = entry.attributeValue("ref");
if(entryRef!=null) {//entryRef
Object bean = objPool.get(entryRef);
Assert.notNull(bean, new NoSuchBeanException("no such bean named "+entryRef));
return bean;
}else {//那就是在下一个标签里
String bean = entry.element("value").getText();
return bean;
}
}else {
return entryValue;
}
}
}
}
return null;
}
@SuppressWarnings("unchecked")
private Object getListOrSet(Element element,int index) throws Exception {
List<Element> values = element.elements("value");
int i = 0;
for(Element val:values) {
if(i == index) {
if(val.attribute("ref")==null) {
return val.getText();
}else {
String ref = val.attributeValue("ref");
Object bean = objPool.get(ref);
Assert.notNull(bean, new NoSuchBeanException("the bean named "+ref+" is not found"));
return bean;
}
}
i++;
}
return null;
}
@SuppressWarnings("unchecked")
private void parseConstructor(XMLDomFile xdf) throws Exception {
List<Element> elements = xdf.EPathSelector("bean [name]");
for(Element e:elements) {
String id = e.attributeValue("id")==null?e.attributeValue("name"):e.attributeValue("id");
Object object = objPool.get(id);
Class<?> objCls = object.getClass();
List<Element> values = e.elements("constructor-value");
List<Object> keys = new ArrayList<>();
Map<Object,Class<?>> vals = new HashMap<>();
for(Element val:values) {
Object value = val.attributeValue("value");
if(value==null) {
value = objPool.get(val.attributeValue("ref"));
}
if(value!=null) {
if(value.toString().startsWith("#{")) {
Object result = parseExpressions(value+"", xdf);
if(result!= value+"") {
value = result;
}
}
}
vals.put(value,Class.forName(val.attributeValue("type")));
keys.add(value);
}
Class<?>[] clzs = vals.values().toArray(new Class<?>[vals.size()]);
Constructor<?> constructor = objCls.getConstructor(clzs);
Parameter[] parameter = constructor.getParameters();
int i = 0;
for(Parameter p:parameter) {
String fieldName = p.getAnnotation(Param.class).value();
Field f = objCls.getDeclaredField(fieldName);
f.setAccessible(true);
f.set(object,keys.get(i));
i++;
}
}
}
private void autowiredBean(XMLDomFile xdf) {
List<Element> elements = xdf.EPathSelector("bean autowired [key]");
for(Element e:elements) {
String id = e.attributeValue("id")==null?e.attributeValue("name"):e.attributeValue("id");
String autowired = e.attributeValue("autowried");
if(autowired.equals("getByname")) {
Map<String, XMLHandler> all = NoyarkApplicationContext.getHandlers();
Collection<XMLHandler> coll = all.values();
for(XMLHandler xh:coll) {
Object obj = xh.getBeans().get(id);
objPool.put(id,obj);
}
}else if(autowired.equals("getByType")){
Collection<Object> collection = objPool.values();
for(Object o:collection) {
if(o.getClass().getName().equals(e.attributeValue("class"))) {
objPool.put(id,o);
}
}
}
}
}
private void parsePackageScan(XMLDomFile xdf) {
List<Element> list = xdf.getElementsByNameSpace("http://www.noyark.net:8081/context",true);
for(Element e:list) {
if(e.getName().equals("component-scan")) {
scanPackage.add(e.attributeValue("base-package"));
}
}
}
public Map<String, Object> getBeans(){
return objPool;
}
public Map<Object, Method> getDesporyMethod(){
return obj_despory;
}
public List<String> getPackage() {
return scanPackage;
}
}
| 38.04539 | 223 | 0.681008 |
3117d019aa6a7c04ba1691958b783cf69de56848 | 5,939 | package lumien.randomthings.block;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockContactButton extends BlockBase
{
public static final PropertyDirection FACING = PropertyDirection.create("facing");
public static final PropertyBool POWERED = PropertyBool.create("powered");
public BlockContactButton()
{
super("contactButton", Material.ROCK);
this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH).withProperty(POWERED, Boolean.valueOf(false)));
this.setTickRandomly(true);
this.setHardness(1.5F);
}
@Override
public int tickRate(World worldIn)
{
return 20;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
if (state.getValue(POWERED).booleanValue())
{
this.notifyNeighbors(worldIn, pos, state.getValue(FACING));
}
super.breakBlock(worldIn, pos, state);
}
@Override
public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return blockState.getValue(POWERED).booleanValue() ? 15 : 0;
}
@Override
public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return blockState.getValue(POWERED).booleanValue() ? 15 : 0;
}
@Override
public boolean canProvidePower(IBlockState state)
{
return true;
}
@Override
public boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side)
{
return true;
}
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (!worldIn.isRemote)
{
if (state.getValue(POWERED).booleanValue())
{
worldIn.setBlockState(pos, state.withProperty(POWERED, Boolean.valueOf(false)));
this.notifyNeighbors(worldIn, pos, state.getValue(FACING));
worldIn.playSound(null, pos.add(0.5, 0.5, 0.5), SoundEvents.UI_BUTTON_CLICK, SoundCategory.BLOCKS, 0.3F, 0.5F);
worldIn.markBlockRangeForRenderUpdate(pos, pos);
}
}
}
private void notifyNeighbors(World worldIn, BlockPos pos, EnumFacing facing)
{
worldIn.notifyNeighborsOfStateChange(pos, this, false);
for (EnumFacing f : EnumFacing.values())
{
worldIn.notifyNeighborsOfStateChange(pos.offset(f), this, false);
}
}
@Override
public IBlockState getStateFromMeta(int meta)
{
EnumFacing enumfacing;
boolean powered = false;
;
int facing = meta;
if (facing >= 6)
{
facing -= 6;
powered = true;
}
return this.getDefaultState().withProperty(FACING, EnumFacing.values()[facing]).withProperty(POWERED, powered);
}
@Override
public int getMetaFromState(IBlockState state)
{
int i;
i = state.getValue(FACING).ordinal();
if (state.getValue(POWERED).booleanValue())
{
i += 6;
}
return i;
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] { FACING, POWERED });
}
private void setDefaultFacing(World worldIn, BlockPos pos, IBlockState state)
{
if (!worldIn.isRemote)
{
IBlockState iblockstate = worldIn.getBlockState(pos.north());
IBlockState iblockstate1 = worldIn.getBlockState(pos.south());
IBlockState iblockstate2 = worldIn.getBlockState(pos.west());
IBlockState iblockstate3 = worldIn.getBlockState(pos.east());
EnumFacing enumfacing = state.getValue(FACING);
if (enumfacing == EnumFacing.NORTH && iblockstate.isFullBlock() && !iblockstate1.isFullBlock())
{
enumfacing = EnumFacing.SOUTH;
}
else if (enumfacing == EnumFacing.SOUTH && iblockstate1.isFullBlock() && !iblockstate.isFullBlock())
{
enumfacing = EnumFacing.NORTH;
}
else if (enumfacing == EnumFacing.WEST && iblockstate2.isFullBlock() && !iblockstate3.isFullBlock())
{
enumfacing = EnumFacing.EAST;
}
else if (enumfacing == EnumFacing.EAST && iblockstate3.isFullBlock() && !iblockstate2.isFullBlock())
{
enumfacing = EnumFacing.WEST;
}
worldIn.setBlockState(pos, state.withProperty(FACING, enumfacing), 2);
}
}
@Override
public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
return this.getDefaultState().withProperty(FACING, EnumFacing.getDirectionFromEntityLiving(pos, placer));
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
{
worldIn.setBlockState(pos, state.withProperty(FACING, EnumFacing.getDirectionFromEntityLiving(pos, placer)), 2);
}
@Override
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
super.onBlockAdded(worldIn, pos, state);
this.setDefaultFacing(worldIn, pos, state);
}
public void activate(World world, BlockPos pos, EnumFacing fromFacing)
{
IBlockState state = world.getBlockState(pos);
if (state.getValue(POWERED).booleanValue())
{
return;
}
else
{
world.setBlockState(pos, state.withProperty(POWERED, Boolean.valueOf(true)), 3);
world.markBlockRangeForRenderUpdate(pos, pos);
world.playSound(null, pos.offset(fromFacing).add(0.5, 0.5, 0.5), SoundEvents.UI_BUTTON_CLICK, SoundCategory.BLOCKS, 0.3F, 0.6F);
this.notifyNeighbors(world, pos, state.getValue(FACING));
world.scheduleUpdate(pos, this, this.tickRate(world));
return;
}
}
}
| 28.690821 | 159 | 0.747937 |
de7864fc5a8c9f11e9fab3b3c603d2ad179ac1c1 | 779 | /**
*
*/
package org.asnworks.apis.friendmanagement.exceptions;
import org.asnworks.apis.friendmanagement.constants.Constants;
/**
* @author sudambat This exception occurs when the request contains duplicate invitation for friend request
*/
public class DuplicateInvitaionException extends BaseException {
private static final long serialVersionUID = -3566601960277815766L;
public DuplicateInvitaionException(String message) {
super(message);
}
public DuplicateInvitaionException(String personOne, String personTwo) {
super("Invalid invitation :" + personOne + " and " + personTwo + " already friends.");
}
@Override
public String getExceptionErrorCode() {
return Constants.DUPLICATE_INVITATION_ERROR_CODE;
}
}
| 26.862069 | 107 | 0.736842 |
8ae7a0317ce622febc8f147220cfb61d26d5a9e9 | 402 | package com.intellij.gwt;
import com.intellij.codeInspection.InspectionToolProvider;
import com.intellij.gwt.inspections.GwtJavaScriptReferencesInspection;
/**
* @author VISTALL
* @since 20.08.14
*/
public class GwtJsInspectionToolProvider implements InspectionToolProvider
{
@Override
public Class[] getInspectionClasses()
{
return new Class[]{GwtJavaScriptReferencesInspection.class};
}
}
| 22.333333 | 74 | 0.803483 |
f9a561a62b8a7ffe534d2d73b6b8904d140a0f99 | 7,551 | package de.uniwue.informatik.praline.datastructure.shapes;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.uniwue.informatik.praline.datastructure.styles.ShapeStyle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.*;
import java.util.List;
/**
* Implementation of {@link Shape}.
* It is like a "normal" isosceles triangle, but its designated purpose is representing arrow heads for
* {@link de.uniwue.informatik.praline.datastructure.labels.LeaderedLabel}s -- hence the name.
* The size is specified via {@link ArrowHeadTriangle#getWidth()}, which is the length of the base side in the
* isosceles triangle, which is the length of the back side of the arrow head triangle, and by
* {@link ArrowHeadTriangle#getLength()}, which is the altitude of the isosceles triangle (a line segment
* perpendicular from the base to the apex).
* The orientation of the main axis (the line segment being the altitude of the isosceles triangle) is specified via
* The vertex angle of the triangle at the apex (which is the top of the head of the arrow head triangle) is implicitly
* defined by the former length and width.
* The position ({@link ArrowHeadTriangle#getXPosition()} + {@link ArrowHeadTriangle#getYPosition()}) is relative to
* the apex of the isosceles triangle, i. e., the pointing top vertex of the {@link ArrowHeadTriangle}.
*/
public class ArrowHeadTriangle implements Shape {
/*==========
* Default values
*==========*/
public static final double UNDEFINED_TRIANGLE_LENGTH = java.lang.Double.NaN;
public static final double UNDEFINED_TRIANGLE_WIDTH = java.lang.Double.NaN;
public static final double UNDEFINED_ORIENTATION_ANGLE = java.lang.Double.NaN;
/*==========
* Instance variables
*==========*/
private double xPosition;
private double yPosition;
private double length;
private double width;
/**
* angle in radians at the apex between the line through the apex parallel to the +x axis and the shortest the
* segment between the apex and the base (i.e. the segment with length the altitude of the triangle.
*/
private double orientationAngle;
private ShapeStyle shapeStyle;
/*==========
* Constructors
*==========*/
public ArrowHeadTriangle() {
this(UNDEFINED_POSITION, UNDEFINED_POSITION, UNDEFINED_TRIANGLE_LENGTH, UNDEFINED_TRIANGLE_WIDTH,
UNDEFINED_ORIENTATION_ANGLE, null);
}
@JsonCreator
public ArrowHeadTriangle(
@JsonProperty("xposition") final double x,
@JsonProperty("yposition") final double y,
@JsonProperty("length") final double length,
@JsonProperty("width") final double width,
@JsonProperty("orientationAngle") final double orientationAngle,
@JsonProperty("shapeStyle") final ShapeStyle shapeStyle
) {
this.xPosition = x;
this.yPosition = y;
this.length = length;
this.width = width;
this.orientationAngle = orientationAngle;
this.shapeStyle = shapeStyle == null ? ShapeStyle.DEFAULT_SHAPE_STYLE : shapeStyle;
}
/*==========
* Getters & Setters
*==========*/
@Override
public double getXPosition() {
return xPosition;
}
public void setXPosition(double x) {
this.xPosition = x;
}
@Override
public double getYPosition() {
return yPosition;
}
public void setYPosition(double y) {
this.yPosition = y;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
/**
* angle in radians at the apex between the line through the apex parallel to the +x axis and the shortest the
* segment between the apex and the base (i.e. the segment with length the altitude of the triangle.
*/
public double getOrientationAngle() {
return orientationAngle;
}
/**
* angle in radians at the apex between the line through the apex parallel to the +x axis and the shortest the
* segment between the apex and the base (i.e. the segment with length the altitude of the triangle.
*/
public void setOrientationAngle(double orientationAngle) {
this.orientationAngle = orientationAngle;
}
@Override
public Rectangle2D getBoundingBox() {
Collection<Point2D.Double> cornerPoints = getCornerPoints();
double minX = Collections.min(cornerPoints, Comparator.comparing(p -> p.x)).getX();
double minY = Collections.min(cornerPoints, Comparator.comparing(p -> p.y)).getY();
double maxX = Collections.max(cornerPoints, Comparator.comparing(p -> p.x)).getX();
double maxY = Collections.max(cornerPoints, Comparator.comparing(p -> p.y)).getY();
return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
}
@Override
public ShapeStyle getShapeStyle() {
return shapeStyle;
}
@Override
public void setShapeStyle(ShapeStyle shapeStyle) {
this.shapeStyle = shapeStyle;
}
public Collection<Point2D.Double> getCornerPoints() {
List<Point2D.Double> cornerPoints = new ArrayList<>(3);
//add apex
cornerPoints.add(new Point2D.Double(xPosition, yPosition));
//for the other corner points first determine their angle and distance to the apex corner
double distanceApexOtherCorners = Math.sqrt(Math.pow(length, 2) + Math.pow(0.5 * width, 2));
double halfInnerAngleAtApex = Math.atan(0.5 * width / length);
cornerPoints.add(new Point2D.Double(
Math.sin(orientationAngle + halfInnerAngleAtApex) * distanceApexOtherCorners,
Math.cos(orientationAngle + halfInnerAngleAtApex) * distanceApexOtherCorners));
cornerPoints.add(new Point2D.Double(
Math.sin(orientationAngle - halfInnerAngleAtApex) * distanceApexOtherCorners,
Math.cos(orientationAngle - halfInnerAngleAtApex) * distanceApexOtherCorners));
return cornerPoints;
}
/*==========
* Modifiers
*==========*/
@Override
public void translate(double xOffset, double yOffset) {
this.xPosition += xOffset;
this.yPosition += yOffset;
}
/*==========
* Clone, equals, hashCode
*==========*/
@Override
public ArrowHeadTriangle clone() {
try {
return (ArrowHeadTriangle) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArrowHeadTriangle that = (ArrowHeadTriangle) o;
return Double.compare(that.xPosition, xPosition) == 0 && Double.compare(that.yPosition, yPosition) == 0 &&
Double.compare(that.length, length) == 0 && Double.compare(that.width, width) == 0 &&
Double.compare(that.orientationAngle, orientationAngle) == 0
&& Objects.equals(shapeStyle, that.shapeStyle);
}
@Override
public int hashCode() {
return Objects.hash(xPosition, yPosition, length, width, orientationAngle, shapeStyle);
}
}
| 35.12093 | 119 | 0.659118 |
45f4148d95dc83bacd273ebe405486e4b22e2268 | 218 | package ldap;
public class Starter {
public static void main(String[] args) throws Exception {
System.out.println(
"LADP Server ldap.Starter"
);
LdapServer.start();
}
} | 19.818182 | 61 | 0.577982 |
e4a4085e89c3060fe33fd5d6cde669eb488ac826 | 4,707 | /**
* Copyright 2015, Sharad Singhal, All Rights Reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Created Dec 5, 2015 by Sharad Singhal
*/
package net.aifusion.metamodel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author Sharad Singhal
*
*/
public class OctetStringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.print("OctetString ");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("done.");
}
@Before
public void setUp() throws Exception {
System.out.print("-");
}
@After
public void tearDown() throws Exception {
System.out.print(".");
return;
}
/**
* Test method for {@link net.aifusion.metamodel.OctetString#hashCode()}.
*/
@Test
public final void testHashCode() {
OctetString o = new OctetString("0x3fff7AB6");
assertNotNull(o);
assertEquals("0x3fff7ab6".hashCode(),o.hashCode());
}
/**
* Test method for {@link net.aifusion.metamodel.OctetString#OctetString(java.lang.String)}.
*/
@Test
public final void testOctetString() {
OctetString o = new OctetString("0x3fff7AB6");
assertNotNull(o);
// does not start with 0x, odd number of nibbles, illegal character
String [] invalids = new String [] {"3fff7AB6", "0x3fff7AB", "0x3fff7ABZ" };
for(String s : invalids){
try {
o = new OctetString(s);
fail("Illegal String succeeded : "+s);
} catch (ModelException e){
assertEquals(4,e.getReason().getCode());
}
}
}
/**
* Test method for {@link net.aifusion.metamodel.OctetString#OctetString(byte[])}.
*/
@Test
public final void testOctetStringBytes() {
OctetString o = new OctetString(new byte[]{1,2,3,10,11,12});
assertNotNull(o);
assertEquals("0x0102030a0b0c",o.toString());
assertArrayEquals(new byte[]{1,2,3,10,11,12},o.getValue());
}
/**
* Test method for {@link net.aifusion.metamodel.OctetString#getValue()}.
*/
@Test
public final void testGetValue() {
byte [] expect = new byte [] {Byte.parseByte("63"),Byte.parseByte("-1"),Byte.parseByte("122"),Byte.parseByte("-74")};
OctetString o = new OctetString("0x3fff7AB6");
assertNotNull(o);
assertArrayEquals(expect, o.getValue());
}
/**
* Test method for {@link net.aifusion.metamodel.OctetString#equals(java.lang.Object)}.
*/
@Test
public final void testEqualsObject() {
OctetString o = new OctetString("0x3fff7AB6");
assertNotNull(o);
assertEquals(new OctetString("0x3fff7AB6"),o);
assertNotEquals(new OctetString("0x3fff7AB7"), o);
}
/**
* Test method for {@link net.aifusion.metamodel.OctetString#toString()}.
*/
@Test
public final void testToString() {
OctetString o = new OctetString("0x3fff7AB6");
assertNotNull(o);
assertEquals("0x3fff7ab6",o.toString());
}
}
| 32.916084 | 120 | 0.703208 |
bb94c7d1ffc69e12998b1c5aef49a39bd27a3f7d | 1,427 | package com.learning.algorithms.lectures.stack;
import java.util.ArrayList;
import java.util.Stack;
/**
* Created by admin on 16/11/9.
*
* 请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),
* 要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
* 给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,
* 请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。
*
* 测试样例:
* [1,2,3,4,5]
* 返回:[5,4,3,2,1]
*/
public class TwoStacks {
public ArrayList<Integer> twoStacksSort(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return null;
}
Stack<Integer> stack = new Stack<Integer>();
for (int i = numbers.length - 1; i >= 0; i--) {
stack.push(numbers[i]);
}
ArrayList<Integer> res = new ArrayList<Integer>();
Stack<Integer> help = new Stack<Integer>();
while (!stack.isEmpty()) {
int current = stack.pop();
while (!help.isEmpty() && help.peek() > current) {
stack.push(help.pop());
}
help.push(current);
}
while (!help.isEmpty()) {
res.add(help.pop());
}
return res;
}
public static void main(String[] args) {
TwoStacks sr = new TwoStacks();
int[] a = {1, 2, 3, 4, 5};
ArrayList<Integer> b = sr.twoStacksSort(a);
for (int i : b) {
System.out.print(i + ",");
}
System.out.println();
}
}
| 24.603448 | 62 | 0.53609 |
f7af3f7874919c75569ac0aba808b5569b659f8c | 25,654 | /*
* Copyright (c) 2021 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.workers.temporal.scheduling;
import io.airbyte.config.FailureReason.FailureOrigin;
import io.airbyte.config.StandardSyncInput;
import io.airbyte.scheduler.models.IntegrationLauncherConfig;
import io.airbyte.scheduler.models.JobRunConfig;
import io.airbyte.workers.temporal.TemporalJobType;
import io.airbyte.workers.temporal.scheduling.activities.ConfigFetchActivity;
import io.airbyte.workers.temporal.scheduling.activities.ConfigFetchActivity.GetMaxAttemptOutput;
import io.airbyte.workers.temporal.scheduling.activities.ConfigFetchActivity.ScheduleRetrieverOutput;
import io.airbyte.workers.temporal.scheduling.activities.ConnectionDeletionActivity;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivity.SyncInput;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivity.SyncOutput;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivityImpl;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptCreationOutput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptFailureInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobCreationOutput;
import io.airbyte.workers.temporal.scheduling.state.WorkflowState;
import io.airbyte.workers.temporal.scheduling.state.listener.TestStateListener;
import io.airbyte.workers.temporal.scheduling.state.listener.WorkflowStateChangedListener.ChangedStateEvent;
import io.airbyte.workers.temporal.scheduling.state.listener.WorkflowStateChangedListener.StateField;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.DbtFailureSyncWorkflow;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.EmptySyncWorkflow;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.NormalizationFailureSyncWorkflow;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.PersistFailureSyncWorkflow;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.ReplicateFailureSyncWorkflow;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.SleepingSyncWorkflow;
import io.airbyte.workers.temporal.scheduling.testsyncworkflow.SourceAndDestinationFailureSyncWorkflow;
import io.temporal.client.WorkflowClient;
import io.temporal.client.WorkflowOptions;
import io.temporal.testing.TestWorkflowEnvironment;
import io.temporal.worker.Worker;
import java.time.Duration;
import java.util.Queue;
import java.util.UUID;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
public class ConnectionManagerWorkflowTest {
private final ConfigFetchActivity mConfigFetchActivity =
Mockito.mock(ConfigFetchActivity.class, Mockito.withSettings().withoutAnnotations());
private final ConnectionDeletionActivity mConnectionDeletionActivity =
Mockito.mock(ConnectionDeletionActivity.class, Mockito.withSettings().withoutAnnotations());
private final GenerateInputActivityImpl mGenerateInputActivityImpl =
Mockito.mock(GenerateInputActivityImpl.class, Mockito.withSettings().withoutAnnotations());
private final JobCreationAndStatusUpdateActivity mJobCreationAndStatusUpdateActivity =
Mockito.mock(JobCreationAndStatusUpdateActivity.class, Mockito.withSettings().withoutAnnotations());
private TestWorkflowEnvironment testEnv;
private Worker worker;
private WorkflowClient client;
private ConnectionManagerWorkflow workflow;
@BeforeEach
public void setUp() {
Mockito.reset(mConfigFetchActivity);
Mockito.reset(mConnectionDeletionActivity);
Mockito.reset(mGenerateInputActivityImpl);
Mockito.reset(mJobCreationAndStatusUpdateActivity);
Mockito.when(mConfigFetchActivity.getTimeToWait(Mockito.any()))
.thenReturn(new ScheduleRetrieverOutput(
Duration.ofMinutes(1l)));
Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any()))
.thenReturn(new JobCreationOutput(
1L));
Mockito.when(mJobCreationAndStatusUpdateActivity.createNewAttempt(Mockito.any()))
.thenReturn(new AttemptCreationOutput(
1));
Mockito.when(mGenerateInputActivityImpl.getSyncWorkflowInput(Mockito.any(SyncInput.class)))
.thenReturn(
new SyncOutput(
new JobRunConfig(),
new IntegrationLauncherConfig(),
new IntegrationLauncherConfig(),
new StandardSyncInput()));
}
public void tearDown() {
testEnv.shutdown();
}
@Nested
@DisplayName("Test which without a long running child workflow")
class AsynchronousWorkflow {
@BeforeEach
public void setup() {
testEnv = TestWorkflowEnvironment.newInstance();
worker = testEnv.newWorker(TemporalJobType.CONNECTION_UPDATER.name());
// Register your workflow implementations
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, EmptySyncWorkflow.class);
client = testEnv.getWorkflowClient();
worker.registerActivitiesImplementations(mConfigFetchActivity, mConnectionDeletionActivity,
mGenerateInputActivityImpl, mJobCreationAndStatusUpdateActivity);
testEnv.start();
workflow = client
.newWorkflowStub(
ConnectionManagerWorkflow.class,
WorkflowOptions.newBuilder()
.setTaskQueue(TemporalJobType.CONNECTION_UPDATER.name())
.build());
}
@Test
@DisplayName("Test that a successful workflow retries and wait")
public void runSuccess() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(124L));
Mockito.verify(mConfigFetchActivity, Mockito.atLeast(2)).getTimeToWait(Mockito.any());
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RUNNING && changedStateEvent.isValue())
.hasSize(2);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() != StateField.RUNNING && changedStateEvent.isValue())
.isEmpty();
testEnv.shutdown();
}
@Test
@DisplayName("Test workflow do not wait to run after a failure")
public void retryAfterFail() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
true,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(50L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RUNNING && changedStateEvent.isValue())
.hasSize(1);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() != StateField.RUNNING && changedStateEvent.isValue())
.isEmpty();
testEnv.shutdown();
}
@Test
@DisplayName("Test workflow which recieved a manual run signal stop waiting")
public void manualRun() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(30L));
workflow.submitManualSync();
testEnv.sleep(Duration.ofSeconds(20L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RUNNING && changedStateEvent.isValue())
.hasSize(1);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.SKIPPED_SCHEDULING && changedStateEvent.isValue())
.hasSize(1);
Assertions.assertThat(events)
.filteredOn(
changedStateEvent -> (changedStateEvent.getField() != StateField.RUNNING
&& changedStateEvent.getField() != StateField.SKIPPED_SCHEDULING)
&& changedStateEvent.isValue())
.isEmpty();
testEnv.shutdown();
}
@Test
@DisplayName("Test workflow which recieved an update signal stop waiting, don't run and don't update the job status")
public void updatedSignalRecieved() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(30L));
workflow.connectionUpdated();
testEnv.sleep(Duration.ofSeconds(20L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RUNNING && changedStateEvent.isValue())
.isEmpty();
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.UPDATED && changedStateEvent.isValue())
.hasSize(1);
Assertions.assertThat(events)
.filteredOn(
changedStateEvent -> changedStateEvent.getField() != StateField.UPDATED && changedStateEvent.isValue())
.isEmpty();
Mockito.verifyNoInteractions(mJobCreationAndStatusUpdateActivity);
testEnv.shutdown();
}
@Test
@DisplayName("Test that cancelling a non running workflow don't do anything")
public void cancelNonRunning() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(30L));
workflow.cancelJob();
testEnv.sleep(Duration.ofSeconds(20L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RUNNING && changedStateEvent.isValue())
.isEmpty();
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.CANCELLED && changedStateEvent.isValue())
.isEmpty();
Assertions.assertThat(events)
.filteredOn(
changedStateEvent -> changedStateEvent.getField() != StateField.CANCELLED && changedStateEvent.isValue())
.isEmpty();
Mockito.verifyNoInteractions(mJobCreationAndStatusUpdateActivity);
testEnv.shutdown();
}
@Test
@DisplayName("test that the sync is properly delete")
public void deleteSync() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(30L));
workflow.deleteConnection();
testEnv.sleep(Duration.ofMinutes(20L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RUNNING && changedStateEvent.isValue())
.isEmpty();
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.DELETED && changedStateEvent.isValue())
.hasSize(1);
Assertions.assertThat(events)
.filteredOn(
changedStateEvent -> changedStateEvent.getField() != StateField.DELETED && changedStateEvent.isValue())
.isEmpty();
Mockito.verify(mConnectionDeletionActivity).deleteConnection(Mockito.any());
testEnv.shutdown();
}
}
@Nested
@DisplayName("Test which without a long running child workflow")
class SynchronousWorkflow {
@BeforeEach
public void setup() {
testEnv = TestWorkflowEnvironment.newInstance();
worker = testEnv.newWorker(TemporalJobType.CONNECTION_UPDATER.name());
// Register your workflow implementations
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, SleepingSyncWorkflow.class);
client = testEnv.getWorkflowClient();
worker.registerActivitiesImplementations(mConfigFetchActivity, mConnectionDeletionActivity,
mGenerateInputActivityImpl, mJobCreationAndStatusUpdateActivity);
testEnv.start();
workflow = client
.newWorkflowStub(
ConnectionManagerWorkflow.class,
WorkflowOptions.newBuilder()
.setTaskQueue(TemporalJobType.CONNECTION_UPDATER.name())
.build());
}
@Test
@DisplayName("Test workflow which recieved a manual while running does nothing")
public void manualRun() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofMinutes(2L));
workflow.submitManualSync();
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.SKIPPED_SCHEDULING && changedStateEvent.isValue())
.isEmpty();
testEnv.shutdown();
}
@Test
@DisplayName("Test that cancelling a running workflow cancel the sync")
public void cancelRunning() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
workflow.submitManualSync();
testEnv.sleep(Duration.ofSeconds(30L));
workflow.cancelJob();
testEnv.sleep(Duration.ofMinutes(1L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.CANCELLED && changedStateEvent.isValue())
.hasSizeGreaterThanOrEqualTo(1);
Mockito.verify(mJobCreationAndStatusUpdateActivity).jobCancelled(Mockito.any());
testEnv.shutdown();
}
@Test
@DisplayName("Test that resetting a-non running workflow starts a reset")
public void resetStart() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofSeconds(30L));
workflow.resetConnection();
testEnv.sleep(Duration.ofSeconds(90L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RESET && changedStateEvent.isValue())
.hasSizeGreaterThanOrEqualTo(1);
Mockito.verify(mJobCreationAndStatusUpdateActivity).jobSuccess(Mockito.any());
testEnv.shutdown();
}
@Test
@DisplayName("Test that resetting a running workflow starts cancel the running workflow")
public void resetCancelRunningWorkflow() {
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(
UUID.randomUUID(),
1L,
1,
false,
1,
workflowState,
false);
WorkflowClient.start(workflow::run, input);
workflow.submitManualSync();
testEnv.sleep(Duration.ofSeconds(30L));
workflow.resetConnection();
testEnv.sleep(Duration.ofSeconds(30L));
final Queue<ChangedStateEvent> events = testStateListener.events(testId);
Assertions.assertThat(events)
.filteredOn(changedStateEvent -> changedStateEvent.getField() == StateField.RESET && changedStateEvent.isValue())
.hasSizeGreaterThanOrEqualTo(1);
Mockito.verify(mJobCreationAndStatusUpdateActivity).jobCancelled(Mockito.any());
testEnv.shutdown();
}
}
@Nested
@DisplayName("Test that sync workflow failures are recorded")
class SyncWorkflowReplicationFailuresRecorded {
private static final long JOB_ID = 111L;
private static final int ATTEMPT_ID = 222;
@BeforeEach
public void setup() {
testEnv = TestWorkflowEnvironment.newInstance();
worker = testEnv.newWorker(TemporalJobType.CONNECTION_UPDATER.name());
client = testEnv.getWorkflowClient();
worker.registerActivitiesImplementations(mConfigFetchActivity, mConnectionDeletionActivity, mGenerateInputActivityImpl,
mJobCreationAndStatusUpdateActivity);
workflow = client.newWorkflowStub(ConnectionManagerWorkflow.class,
WorkflowOptions.newBuilder().setTaskQueue(TemporalJobType.CONNECTION_UPDATER.name()).build());
Mockito.when(mConfigFetchActivity.getMaxAttempt()).thenReturn(new GetMaxAttemptOutput(1));
}
@Test
@DisplayName("Test that source and destination failures are recorded")
public void testSourceAndDestinationFailuresRecorded() {
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, SourceAndDestinationFailureSyncWorkflow.class);
testEnv.start();
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(UUID.randomUUID(), JOB_ID, ATTEMPT_ID, false, 1, workflowState, false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofMinutes(2L));
workflow.submitManualSync();
Mockito.verify(mJobCreationAndStatusUpdateActivity).attemptFailure(Mockito.argThat(new HasFailureFromSource(FailureOrigin.SOURCE)));
Mockito.verify(mJobCreationAndStatusUpdateActivity).attemptFailure(Mockito.argThat(new HasFailureFromSource(FailureOrigin.DESTINATION)));
testEnv.shutdown();
}
@Test
@DisplayName("Test that normalization failure is recorded")
public void testNormalizationFailure() {
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, NormalizationFailureSyncWorkflow.class);
testEnv.start();
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(UUID.randomUUID(), JOB_ID, ATTEMPT_ID, false, 1, workflowState, false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofMinutes(2L));
workflow.submitManualSync();
Mockito.verify(mJobCreationAndStatusUpdateActivity).attemptFailure(Mockito.argThat(new HasFailureFromSource(FailureOrigin.NORMALIZATION)));
testEnv.shutdown();
}
@Test
@DisplayName("Test that dbt failure is recorded")
public void testDbtFailureRecorded() {
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, DbtFailureSyncWorkflow.class);
testEnv.start();
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(UUID.randomUUID(), JOB_ID, ATTEMPT_ID, false, 1, workflowState, false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofMinutes(2L));
workflow.submitManualSync();
Mockito.verify(mJobCreationAndStatusUpdateActivity).attemptFailure(Mockito.argThat(new HasFailureFromSource(FailureOrigin.DBT)));
testEnv.shutdown();
}
@Test
@DisplayName("Test that persistence failure is recorded")
public void testPersistenceFailureRecorded() {
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, PersistFailureSyncWorkflow.class);
testEnv.start();
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(UUID.randomUUID(), JOB_ID, ATTEMPT_ID, false, 1, workflowState, false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofMinutes(2L));
workflow.submitManualSync();
Mockito.verify(mJobCreationAndStatusUpdateActivity).attemptFailure(Mockito.argThat(new HasFailureFromSource(FailureOrigin.PERSISTENCE)));
testEnv.shutdown();
}
@Test
@DisplayName("Test that replication worker failure is recorded")
public void testReplicationFailureRecorded() {
worker.registerWorkflowImplementationTypes(ConnectionManagerWorkflowImpl.class, ReplicateFailureSyncWorkflow.class);
testEnv.start();
final UUID testId = UUID.randomUUID();
final TestStateListener testStateListener = new TestStateListener();
final WorkflowState workflowState = new WorkflowState(testId, testStateListener);
final ConnectionUpdaterInput input = new ConnectionUpdaterInput(UUID.randomUUID(), JOB_ID, ATTEMPT_ID, false, 1, workflowState, false);
WorkflowClient.start(workflow::run, input);
testEnv.sleep(Duration.ofMinutes(2L));
workflow.submitManualSync();
Mockito.verify(mJobCreationAndStatusUpdateActivity).attemptFailure(Mockito.argThat(new HasFailureFromSource(FailureOrigin.REPLICATION_WORKER)));
testEnv.shutdown();
}
}
private class HasFailureFromSource implements ArgumentMatcher<AttemptFailureInput> {
private final FailureOrigin expectedFailureOrigin;
public HasFailureFromSource(final FailureOrigin failureOrigin) {
this.expectedFailureOrigin = failureOrigin;
}
@Override
public boolean matches(final AttemptFailureInput arg) {
return arg.getAttemptFailureSummary().getFailures().stream().anyMatch(f -> f.getFailureOrigin().equals(expectedFailureOrigin));
}
}
}
| 39.2263 | 150 | 0.724487 |
09a914239c9ffe5eeb3ff79ccc22e55b07bd9914 | 1,205 | package br.sprintdev.controller.form;
import br.sprintdev.model.entity.User;
import br.sprintdev.model.service.UserService;
public class UpdateUserForm {
private String firstName;
private String lastName;
private String username;
private String email;
private String bgColor;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User update(Long id, UserService service) {
User user = service.findById(id);
user.setFirstName(this.firstName);
user.setLastName(this.lastName);
user.setUsername(this.username);
user.setEmail(this.email);
user.setBgColor(this.bgColor);
return user;
}
}
| 17.214286 | 51 | 0.727801 |
0506dd2fc745a2e4a340746b15f317a7311cbdf9 | 874 | import java.util.Arrays;
public class Merger {
public static void main(String[] args) {
// int[] array1 = {1, 2, 3, 3, 3, 4, 5};
// int[] array2 = {1, 2, 3, 3};
int[] array1 = {1,3,5,6,7};
int[] array2 = {1,2,3,4,6,8,9};
System.out.println(Arrays.toString(sort(array1, array2)));
}
public static int[] sort(int[] array1, int[] array2) {
int[] array = new int[array1.length + array2.length];
int i = 0;
int j = 0;
while (i < array1.length && j < array2.length) {
array[i + j] = array1[i] < array2[j] ? array1[i++] : array2[j++];
}
if (i != array1.length) {
System.arraycopy(array1, i, array, i + j, array1.length - i);
} else {
System.arraycopy(array2, j, array, i + j, array2.length - j);
}
return array;
}
}
| 31.214286 | 77 | 0.5 |
05612d9194a7e6311740755068c77ef26d5cc486 | 3,637 | /*
* ePerf: Earnstone Performance Counters.
*
* Copyright 2011 Corey Hulen, Earnstone 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.
*/
package com.earnstone.perf;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLongArray;
/**
* A performance counter for averaging over a sample. The focus is on
* performance and being able to add raw values quickly to the sample. Under
* high loads values can be missed. This class is considered thread safe.
*
* @author Corey Hulen
*
*/
public class AvgCounter extends Counter {
protected AtomicInteger index = new AtomicInteger();
protected AtomicLongArray items;
public static final int DefaultSampleSize = 128;
public AvgCounter() {
items = new AtomicLongArray(DefaultSampleSize);
initializeArray(items);
}
/**
* Resizes the samples size to save. This will remove all the existing data
* and reset the array. This method is not considered thread safe but since
* it's not called often or only on initialize we still allow it.
*
* @param sampleSize
* The size of the new sample to hold in memory.
*/
public void setSampleSize(int sampleSize) {
AtomicLongArray newArray = new AtomicLongArray(sampleSize);
initializeArray(newArray);
items = newArray;
index.set(0);
}
public int getSampleSize() {
return items.length();
}
private void initializeArray(AtomicLongArray initArray) {
for (int i = 0; i < initArray.length(); i++) {
initArray.set(i, Long.MIN_VALUE);
}
}
@Override
public String getDisplayValue() {
synchronized (PerfUtils.Formatter) {
return PerfUtils.Formatter.format(getValue());
}
}
@Override
public double getValue() {
return PerfUtils.round(average());
}
/**
* Adds a value to the sample. Increments the index and adds the value to
* the array.
*
* Under high load some samples may be missed. Increasing the sampleSize
* decreases the chance a sample will be missed.
*
* @param raw
* The value to add into the sample
*/
public void addValue(long raw) {
int tempIndex = index.incrementAndGet();
if (tempIndex <= items.length()) {
items.set(tempIndex - 1, raw);
}
else {
tempIndex = index.getAndSet(0);
// If this thread won it should be zero.
if (tempIndex == 0) {
index.incrementAndGet();
items.set(0, raw);
}
else {
// recursion makes the most sense so we
// don't miss any values something like
// addValue(raw) but in reality missing
// a sample or two is better than the
// recursion endlessly looping.
// If the method is hammered so hard we went
// threw the array twice then missing samples
// is the least of our worries.
tempIndex = index.incrementAndGet();
if (tempIndex <= items.length()) {
items.set(tempIndex - 1, raw);
}
}
}
}
public double average() {
double sum = 0;
long raw = 0;
int i = 0;
for (i = 0; i < items.length(); i++) {
raw = items.get(i);
if (raw != Long.MIN_VALUE)
sum += raw;
else
break;
}
return i == 0 ? 0 : sum / i;
}
}
| 25.978571 | 76 | 0.682156 |
123e300ed197b2c2ab10310a3bd809091a5efb43 | 1,038 | package com.example.maguoqing.androiddemo.fragment;
import android.os.Bundle;
import android.widget.TextView;
import com.example.maguoqing.androiddemo.R;
import com.example.maguoqing.androiddemo.annotation.ViewId;
import com.example.maguoqing.androiddemo.base.BaseFragment;
import com.umeng.analytics.MobclickAgent;
/**
* Created by magq on 16/2/18.
*/
public class HomeFragment extends BaseFragment {
@ViewId(R.id.text)
private TextView textView;
@Override
protected int getLayoutId() {
return R.layout.fragment_home;
}
@Override
protected void readIntent() {
}
@Override
protected void initControls(Bundle savedInstanceState) {
textView.setText("Home");
}
@Override
protected void setListeners() {
}
public void onResume() {
super.onResume();
MobclickAgent.onPageStart(HomeFragment.class.getName());
}
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd(HomeFragment.class.getName());
}
}
| 21.183673 | 64 | 0.692678 |
6e0fab78a6937ad18a187c22c4d02d8b31a9b493 | 4,267 | /*
* Copyright 2021 EPAM Systems, Inc
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.epam.deltix.qsrv.hf.codec.cg;
import com.epam.deltix.qsrv.hf.codec.CodecUtils;
import com.epam.deltix.qsrv.hf.pub.codec.AlphanumericCodec;
import com.epam.deltix.qsrv.hf.pub.md.IntegerDataType;
import com.epam.deltix.util.jcg.JCompoundStatement;
import com.epam.deltix.util.jcg.JExpr;
import com.epam.deltix.util.jcg.JVariable;
import static com.epam.deltix.qsrv.hf.tickdb.lang.compiler.cg.QCGHelpers.CTXT;
/**
*
*/
public class QBAlphanumericType extends QBoundType<QAlphanumericType> {
private JExpr codec = null;
public QBAlphanumericType(QAlphanumericType qType, Class<?> javaType, QAccessor accessor, QVariableContainerLookup lookupContainer) {
super(qType, javaType, accessor);
initHelperMembers(lookupContainer);
}
private void initHelperMembers(QVariableContainerLookup lookupContainer) {
final int len = qType.dt.getLength();
final String name = "codec_" + len;
JVariable var = lookupContainer.lookupVar(name);
if (var == null) {
var = lookupContainer.addVar(AlphanumericCodec.class, name, CTXT.newExpr(AlphanumericCodec.class, CTXT.intLiteral(len)));
}
codec = lookupContainer.access(var);
}
@Override
public void decode(JExpr input, JCompoundStatement addTo) {
if (codec == null)
throw new IllegalStateException("codec variable was not set");
final JExpr value;
if (javaBaseType == long.class)
value = codec.call("readLong", input);
else if (javaBaseType == String.class || javaBaseType == CharSequence.class)
value = CTXT.staticCall(CodecUtils.class, "getString", codec.call("readCharSequence", input));
else
throw new IllegalStateException("unexpected bound type " + javaBaseType);
addTo.add(accessor.write(value));
}
@Override
public void encode(JExpr output, JCompoundStatement addTo) {
if (codec == null)
throw new IllegalStateException("codec variable was not set");
final String function;
if (javaBaseType == long.class)
function = "writeLong";
else if (javaBaseType == String.class || javaBaseType == CharSequence.class)
function = "writeCharSequence";
else
throw new IllegalStateException("unexpected bound type " + javaBaseType);
addTo.add(codec.call(function, getEncodeValue(getNullLiteral()), output));
}
@Override
protected JExpr getNullLiteralImpl() {
return getNullLiteral4BoundType();
}
private JExpr getNullLiteral4BoundType() {
if (javaBaseType == String.class || javaBaseType == CharSequence.class )
return CTXT.nullLiteral();
else if (javaBaseType == long.class)
return CTXT.staticVarRef(IntegerDataType.class, "INT64_NULL");
else
throw new UnsupportedOperationException("unexpected bound type " + javaBaseType.getName());
}
@Override
protected JExpr makeConstantExpr(Object obj) {
if (javaBaseType == String.class || javaBaseType == CharSequence.class)
return CTXT.stringLiteral((String) obj);
else if (javaBaseType == long.class) {
if (obj instanceof String)
return codec.call("encodeToLong", CTXT.stringLiteral((String) obj));
else
throw new UnsupportedOperationException();
} else
throw new UnsupportedOperationException("unexpected bound type " + javaBaseType.getName());
}
}
| 39.146789 | 137 | 0.682447 |
3600b496aa6e418f2fecfe1f967101b3c71967f6 | 2,276 | // Copyright 2017 The Bazel 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
package com.google.devtools.build.lib.rules.config;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.packages.RuleClass;
/** Rule definition for Android's config_feature_flag rule. */
public final class ConfigFeatureFlagRule implements RuleDefinition {
@Override
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) {
return builder
.setUndocumented(/* It's unusable as yet, as there are no ways to interact with it. */)
.requiresConfigurationFragments(ConfigFeatureFlagConfiguration.class)
.add(
attr("allowed_values", STRING_LIST)
.mandatory()
.nonEmpty()
.orderIndependent()
.nonconfigurable("policy decision; this is defining an element of configuration"))
.add(
attr("default_value", STRING)
.mandatory()
.nonconfigurable("policy decision; this is defining an element of configuration"))
.build();
}
@Override
public RuleDefinition.Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("config_feature_flag")
.ancestors(BaseRuleClasses.BaseRule.class)
.factoryClass(ConfigFeatureFlag.class)
.build();
}
}
| 40.642857 | 98 | 0.721002 |
177d44ea131e6a7575d4f526f133c4735e56e0aa | 1,133 | package fr.paragoumba.threedlab.components;
import fr.paragoumba.threedlab.materials.Material;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import static fr.paragoumba.threedlab.components.BlueprintPanel.PIXEL_SIZE;
public abstract class MaterialButton extends JButton {
public MaterialButton(String text, Material material, boolean canSetMaterial){
super(text);
setToolTipText(text);
setBorder(null);
Dimension size = new Dimension(8 * PIXEL_SIZE, 8 * PIXEL_SIZE);
setMinimumSize(size);
setMaximumSize(size);
setPreferredSize(size);
if (canSetMaterial){
addActionListener(actionEvent -> BlueprintPanel.setCurrentMaterial(material));
}
}
@Override
public JToolTip createToolTip(){
ToolTip toolTip = new ToolTip();
toolTip.setToolTipText(getText());
return toolTip;
}
@Override
public Point getToolTipLocation(MouseEvent event){
return new Point(0, getHeight() / 2);
}
@Override
protected void paintComponent(Graphics g){}
}
| 20.232143 | 90 | 0.677846 |
e9aca338654fdea51c09e84cd8af4bb393526660 | 311 | package de.onyxbits.raccoon.proto;
import com.google.protobuf.ByteString;
import com.google.protobuf.MessageOrBuilder;
public interface ServerCommandsOrBuilder extends MessageOrBuilder {
boolean hasDisplayErrorMessage();
String getDisplayErrorMessage();
ByteString getDisplayErrorMessageBytes();
}
| 23.923077 | 67 | 0.823151 |
1daae4d9a4623be60d1ee060bb252df12d907ea0 | 1,205 | /*
* Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package io.proleap.cobol.asg.metamodel.procedure.use.impl;
import io.proleap.cobol.CobolParser.UseDebugOnContext;
import io.proleap.cobol.asg.metamodel.ProgramUnit;
import io.proleap.cobol.asg.metamodel.call.Call;
import io.proleap.cobol.asg.metamodel.impl.CobolDivisionElementImpl;
import io.proleap.cobol.asg.metamodel.procedure.use.DebugOn;
public class DebugOnImpl extends CobolDivisionElementImpl implements DebugOn {
protected UseDebugOnContext ctx;
protected DebugOnType debugOnType;
protected Call onCall;
public DebugOnImpl(final ProgramUnit programUnit, final UseDebugOnContext ctx) {
super(programUnit, ctx);
this.ctx = ctx;
}
@Override
public DebugOnType getDebugOnType() {
return debugOnType;
}
@Override
public Call getOnCall() {
return onCall;
}
@Override
public void setOnCall(final Call onCall) {
this.onCall = onCall;
}
@Override
public void setType(final DebugOnType debugOnType) {
this.debugOnType = debugOnType;
}
}
| 23.173077 | 81 | 0.774274 |
d4d5a4b5562abc55920c569c43b5d3b615303eb7 | 2,105 | package us.dontcareabout.ahCool.client.data;
import java.util.ArrayList;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import us.dontcareabout.ahCool.client.data.BasicDataReadyEvent.BasicDataReadyHandler;
import us.dontcareabout.ahCool.client.data.InputDataReadyEvent.InputDataReadyHandler;
import us.dontcareabout.gwt.client.google.Sheet;
import us.dontcareabout.gwt.client.google.SheetHappen;
import us.dontcareabout.gwt.client.google.SheetHappen.Callback;
public class DataCenter {
private final static SimpleEventBus eventBus = new SimpleEventBus();
public static ArrayList<BasicData> basicDataList;
public static BasicData findBasic(InputData input) {
for (BasicData bd : basicDataList) {
if (!input.getArea().equals(bd.getArea())) { continue; }
if (!input.getSection().equals(bd.getSection())) { continue; }
if (!input.getBlock().equals(bd.getBlock())) { continue; }
if (!input.getNumber().equals(bd.getNumber())) { continue; }
return bd;
}
return null;
}
public static void wantBasicData(String sheetId) {
SheetHappen.get(sheetId, new Callback<BasicData>() {
@Override
public void onSuccess(Sheet<BasicData> gs) {
basicDataList = gs.getEntry();
eventBus.fireEvent(new BasicDataReadyEvent());
}
@Override
public void onError(Throwable exception) {}
});
}
public static HandlerRegistration addBasicDataReady(BasicDataReadyHandler handler) {
return eventBus.addHandler(BasicDataReadyEvent.TYPE, handler);
}
public static ArrayList<InputData> inputDataList;
public static void wantInputData(String sheetId) {
SheetHappen.get(sheetId, new Callback<InputData>() {
@Override
public void onSuccess(Sheet<InputData> gs) {
inputDataList = gs.getEntry();
eventBus.fireEvent(new InputDataReadyEvent());
}
@Override
public void onError(Throwable exception) {}
});
}
//FIXME 搬到 DataCenter 去
public static HandlerRegistration addInputDataReady(InputDataReadyHandler handler) {
return eventBus.addHandler(InputDataReadyEvent.TYPE, handler);
}
}
| 30.507246 | 85 | 0.761045 |
fbb3374cbc3a0ff864a42efcaefc5a528496e79c | 3,659 | package com.pbs.middleware.server.features.ssh.shell;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import static java.util.Optional.ofNullable;
@Slf4j
@RequiredArgsConstructor
abstract class JschShell implements CloseableShell {
protected final String pbsHost;
protected final String login;
private final String sshHost;
protected Session session = null;
protected ChannelExec channel;
protected InputStream stdout = null;
protected InputStream stderr = null;
protected abstract void initSshSession() throws ShellException;
protected void createSession(JSch jSch) throws JSchException {
String[] host = this.sshHost.split(":");
this.session = jSch.getSession(this.login, host[0], host.length > 1 ? Integer.parseInt(host[1]) : 22);
}
@Override
public Result executeCommand(String command) throws ShellException {
try {
log.debug("Executing shell command: " + command);
this.initSshSession();
session.connect(3000); // todo move to app. properties
this.channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
ofNullable(pbsHost).ifPresent(pbsHost -> channel.setEnv("PBS_SERVER", pbsHost));
channel.setInputStream(null);
stdout = channel.getInputStream();
stderr = channel.getErrStream();
channel.connect();
Result result = new Result(channel.getExitStatus(), IOUtils.toString(new InputStreamReader(stdout)), IOUtils.toString(new InputStreamReader(stderr)));
log.debug("Sell command response:" + result.toString());
return result;
} catch (JSchException exception) {
throw new ShellException("SSH channel exception: " + exception.getLocalizedMessage());
} catch (IOException exception) {
throw new ShellException("SSH IO exception: " + exception.getLocalizedMessage());
}
}
@Override
public InputStream getInputStream() throws ShellException {
try {
return channel != null ? channel.getInputStream() : null;
} catch (IOException exception) {
throw new ShellException("SSH IO exception: " + exception.getLocalizedMessage());
}
}
@Override
public OutputStream getOutputStream() throws ShellException {
try {
return channel != null ? channel.getOutputStream() : null;
} catch (IOException exception) {
throw new ShellException("SSH IO exception: " + exception.getLocalizedMessage());
}
}
@Override
public void close() {
ofNullable(channel).filter(Channel::isConnected).ifPresent(Channel::disconnect);
ofNullable(session).filter(Session::isConnected).ifPresent(Session::disconnect);
ofNullable(stdout).ifPresent(stream -> {
try {
stream.close();
} catch (IOException e) {
log.error("STDOUT stream closing exception", e);
}
});
ofNullable(stderr).ifPresent(stream -> {
try {
stream.close();
} catch (IOException e) {
log.error("STDERR stream closing exception", e);
}
});
}
}
| 34.847619 | 162 | 0.649358 |
0fec5f7e9fa7ded87719faf934b6ff86a971815f | 659 | package JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
class InseirPessoa {
public static void main(String[] args) throws SQLException {
Connection conexao = FabricaConexao.getConexao();//
Scanner input = new Scanner(System.in);
System.out.println("Digite seu nome: ");
String nome = input.nextLine();
String sql = "insert into pessoa (nome) value (?)";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setString(1, nome);
stmt.execute();
conexao.close();
input.close();
}
}
| 25.346154 | 64 | 0.652504 |
8d46c7ca83961a638fadf5105299f8e34e38caa1 | 10,499 | package org.jailbreak.service.base.events;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.jailbreak.api.representations.Representations.Checkin;
import org.jailbreak.api.representations.Representations.Donate;
import org.jailbreak.api.representations.Representations.Event;
import org.jailbreak.api.representations.Representations.Facebook;
import org.jailbreak.api.representations.Representations.Instagram;
import org.jailbreak.api.representations.Representations.Link;
import org.jailbreak.api.representations.Representations.Twitter;
import org.jailbreak.api.representations.Representations.Vine;
import org.jailbreak.api.representations.Representations.Youtube;
import org.jailbreak.api.representations.Representations.Event.EventType;
import org.jailbreak.api.representations.Representations.Event.EventsFilters;
import org.jailbreak.api.representations.Representations.Team;
import org.jailbreak.service.core.CheckinsManager;
import org.jailbreak.service.core.TeamsManager;
import org.jailbreak.service.core.events.DonateEventsManager;
import org.jailbreak.service.core.events.EventsManager;
import org.jailbreak.service.core.events.FacebookEventsManager;
import org.jailbreak.service.core.events.InstagramEventsManager;
import org.jailbreak.service.core.events.LinkEventsManager;
import org.jailbreak.service.core.events.TwitterEventsManager;
import org.jailbreak.service.core.events.VineEventsManager;
import org.jailbreak.service.core.events.YoutubeEventsManager;
import org.jailbreak.service.db.dao.events.EventsDAO;
import org.jailbreak.service.errors.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.newrelic.deps.com.google.common.collect.Sets;
public class EventsManagerImpl implements EventsManager {
private final EventsDAO dao;
private final TeamsManager teamsManager;
private final CheckinsManager checkinsManager;
private final DonateEventsManager donatesManager;
private final LinkEventsManager linksManager;
private final YoutubeEventsManager youtubesManager;
private final FacebookEventsManager facebookManager;
private final TwitterEventsManager twitterManager;
private final InstagramEventsManager instagramManager;
private final VineEventsManager vineManager;
private final Logger LOG = LoggerFactory.getLogger(EventsManagerImpl.class);
@Inject
public EventsManagerImpl(EventsDAO dao,
TeamsManager teamsManager,
CheckinsManager checkinsManager,
YoutubeEventsManager youtubesManager,
DonateEventsManager donatesManager,
LinkEventsManager linksManager,
FacebookEventsManager facebookManager,
TwitterEventsManager twitterManager,
InstagramEventsManager instagramManager,
VineEventsManager vineManager) {
this.dao = dao;
this.teamsManager = teamsManager;
this.checkinsManager = checkinsManager;
this.youtubesManager = youtubesManager;
this.donatesManager = donatesManager;
this.linksManager = linksManager;
this.facebookManager = facebookManager;
this.twitterManager = twitterManager;
this.instagramManager = instagramManager;
this.vineManager = vineManager;
}
@Override
public Event createEvent(Event event) {
int newId = dao.insert(event);
return getEvent(newId).get();
}
@Override
public boolean updateEvent(Event event) {
int result = dao.update(event);
if (result == 1) {
return true;
} else {
return false;
}
}
@Override
public Optional<Event> getRawEvent(int id) {
return dao.getEvent(id);
}
@Override
public Optional<Event> getEvent(int id) {
Optional<Event> maybeEvent = dao.getEvent(id);
if (maybeEvent.isPresent()) {
List<Event> es = Lists.newArrayList(maybeEvent.get());
Event annotatedEvent = annotateEvents(es).get(0);
maybeEvent = Optional.of(annotatedEvent);
}
return maybeEvent;
}
@Override
public List<Event> getEvents(int limit, EventsFilters filters) {
try {
List<Event> rawEvents = dao.getFilteredEvents(limit, filters);
return annotateEvents(rawEvents);
} catch (SQLException e) {
throw new AppException("Database error retrieving events", e);
}
}
private List<Event> annotateEvents(List<Event> events) {
List<Event.Builder> builders = annotateEventsObjects(events);
Collections.sort(builders, new Comparator<Event.Builder>() {
@Override
public int compare(Event.Builder e1, Event.Builder e2) {
Long time1 = Long.valueOf(e1.getTime());
Long time2 = Long.valueOf(e2.getTime());
return time2.compareTo(time1);
}
});
// Annotate any events with a team id with their team data
HashMap<Integer, Team> teamsMap = teamsManager.getLimitedTeams(getTeamIds(events));
List<Event> finalEvents = Lists.newArrayListWithCapacity(events.size());
LOG.debug("Annotating " + events.size() + " events with the data from " + teamsMap.size() + " teams.");
for (Event.Builder event : builders) {
if (event.hasTeamId()) {
int teamId = event.getTeamId();
switch(event.getType().getNumber()) {
case EventType.CHECKIN_VALUE:
Checkin.Builder checkin = event.getCheckin().toBuilder();
if (teamsMap.containsKey(teamId)) {
checkin.setTeam(teamsMap.get(teamId));
}
event.setCheckin(checkin);
break;
case EventType.DONATE_VALUE:
Donate.Builder donate = event.getDonate().toBuilder();
if (teamsMap.containsKey(teamId)) {
donate.setTeam(teamsMap.get(teamId));
}
event.setDonate(donate);
break;
case EventType.TWITTER_VALUE:
Twitter.Builder twitter = event.getTwitter().toBuilder();
if (teamsMap.containsKey(teamId)) {
twitter.setTeam(teamsMap.get(teamId));
}
event.setTwitter(twitter);
break;
case EventType.FACEBOOK_VALUE:
Facebook.Builder facebook = event.getFacebook().toBuilder();
if (teamsMap.containsKey(teamId)) {
facebook.setTeam(teamsMap.get(teamId));
}
event.setFacebook(facebook);
break;
case EventType.VINE_VALUE:
Vine.Builder vine = event.getVine().toBuilder();
if (teamsMap.containsKey(teamId)) {
vine.setTeam(teamsMap.get(teamId));
}
event.setVine(vine);
break;
case EventType.INSTAGRAM_VALUE:
Instagram.Builder insta = event.getInstagram().toBuilder();
if (teamsMap.containsKey(teamId)) {
insta.setTeam(teamsMap.get(teamId));
}
event.setInstagram(insta);
break;
case EventType.YOUTUBE_VALUE:
Youtube.Builder youtube = event.getYoutube().toBuilder();
if (teamsMap.containsKey(teamId)) {
youtube.setTeam(teamsMap.get(teamId));
}
event.setYoutube(youtube);
break;
}
}
finalEvents.add(event.build());
}
return finalEvents;
}
private List<Event.Builder> annotateEventsObjects(List<Event> events) {
LOG.debug("Annotating " + events.size() + " events with their full object data");
HashMap<Integer, Checkin> checkins = checkinsManager.getCheckins(getObjectIds(events, EventType.CHECKIN));
HashMap<Integer, Donate> donates = donatesManager.getDonateEvents(getObjectIds(events, EventType.DONATE));
HashMap<Integer, Link> links = linksManager.getLinkEvents(getObjectIds(events, EventType.LINK));
HashMap<Integer, Facebook> facebooks = facebookManager.getFacebookEvents(getObjectIds(events, EventType.FACEBOOK));
HashMap<Integer, Twitter> twitters = twitterManager.getTwitterEvents(getObjectIds(events, EventType.TWITTER));
HashMap<Integer, Instagram> instagrams = instagramManager.getInstagramEvents(getObjectIds(events, EventType.INSTAGRAM));
HashMap<Integer, Vine> vines = vineManager.getVineEvents(getObjectIds(events, EventType.VINE));
HashMap<Integer, Youtube> youtubes = youtubesManager.getYoutubeEvents(getObjectIds(events, EventType.YOUTUBE));
List<Event.Builder> builders = Lists.newArrayListWithCapacity(events.size());
for (Event event : events) {
switch(event.getType().getNumber()) {
case EventType.LINK_VALUE:
if (links.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setLink(links.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.CHECKIN_VALUE:
if (checkins.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setCheckin(checkins.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.DONATE_VALUE:
if (donates.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setDonate(donates.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.TWITTER_VALUE:
if (twitters.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setTwitter(twitters.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.FACEBOOK_VALUE:
if (facebooks.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setFacebook(facebooks.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.VINE_VALUE:
if (vines.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setVine(vines.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.INSTAGRAM_VALUE:
if (instagrams.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setInstagram(instagrams.get(event.getObjectId()));
builders.add(builder);
}
break;
case EventType.YOUTUBE_VALUE:
if (youtubes.containsKey(event.getObjectId())) {
Event.Builder builder = event.toBuilder().setYoutube(youtubes.get(event.getObjectId()));
builders.add(builder);
}
break;
default:
builders.add(event.toBuilder());
}
}
return builders;
}
private Set<Integer> getTeamIds(List<Event> events) {
Set<Integer> ids = Sets.newHashSet();
for (Event event : events) {
if (event.hasTeamId()) {
ids.add(event.getTeamId());
}
}
return ids;
}
private Set<Integer> getObjectIds(List<Event> events, EventType type) {
Set<Integer> ids = Sets.newHashSet();
for (Event event : events) {
if (event.getType() == type) {
ids.add(event.getObjectId());
}
}
return ids;
}
}
| 33.977346 | 122 | 0.736832 |
75634cb907d2e657b4e41df5693928381764c27f | 14,600 | /*
* Copyright (c) 2002-2016, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jdk.internal.org.jline.terminal.impl.jna.win;
import java.io.IOException;
import java.io.Writer;
//import com.sun.jna.Pointer;
//import com.sun.jna.ptr.IntByReference;
import jdk.internal.org.jline.utils.AnsiWriter;
import jdk.internal.org.jline.utils.Colors;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_BLUE;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_GREEN;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_INTENSITY;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_RED;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.FOREGROUND_BLUE;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.FOREGROUND_GREEN;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.FOREGROUND_INTENSITY;
import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.FOREGROUND_RED;
/**
* A Windows ANSI escape processor, uses JNA to access native platform
* API's to change the console attributes.
*
* @since 1.0
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
* @author Joris Kuipers
*/
public final class WindowsAnsiWriter extends AnsiWriter {
private static final short FOREGROUND_BLACK = 0;
private static final short FOREGROUND_YELLOW = (short) (FOREGROUND_RED|FOREGROUND_GREEN);
private static final short FOREGROUND_MAGENTA = (short) (FOREGROUND_BLUE|FOREGROUND_RED);
private static final short FOREGROUND_CYAN = (short) (FOREGROUND_BLUE|FOREGROUND_GREEN);
private static final short FOREGROUND_WHITE = (short) (FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
private static final short BACKGROUND_BLACK = 0;
private static final short BACKGROUND_YELLOW = (short) (BACKGROUND_RED|BACKGROUND_GREEN);
private static final short BACKGROUND_MAGENTA = (short) (BACKGROUND_BLUE|BACKGROUND_RED);
private static final short BACKGROUND_CYAN = (short) (BACKGROUND_BLUE|BACKGROUND_GREEN);
private static final short BACKGROUND_WHITE = (short) (BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE);
private static final short ANSI_FOREGROUND_COLOR_MAP[] = {
FOREGROUND_BLACK,
FOREGROUND_RED,
FOREGROUND_GREEN,
FOREGROUND_YELLOW,
FOREGROUND_BLUE,
FOREGROUND_MAGENTA,
FOREGROUND_CYAN,
FOREGROUND_WHITE,
};
private static final short ANSI_BACKGROUND_COLOR_MAP[] = {
BACKGROUND_BLACK,
BACKGROUND_RED,
BACKGROUND_GREEN,
BACKGROUND_YELLOW,
BACKGROUND_BLUE,
BACKGROUND_MAGENTA,
BACKGROUND_CYAN,
BACKGROUND_WHITE,
};
private final static int MAX_ESCAPE_SEQUENCE_LENGTH = 100;
private final Pointer console;
private final Kernel32.CONSOLE_SCREEN_BUFFER_INFO info = new Kernel32.CONSOLE_SCREEN_BUFFER_INFO();
private final short originalColors;
private boolean negative;
private boolean bold;
private boolean underline;
private short savedX = -1;
private short savedY = -1;
public WindowsAnsiWriter(Writer out, Pointer console) throws IOException {
super(out);
this.console = console;
getConsoleInfo();
originalColors = info.wAttributes;
}
private void getConsoleInfo() throws IOException {
out.flush();
Kernel32.INSTANCE.GetConsoleScreenBufferInfo(console, info);
if( negative ) {
info.wAttributes = invertAttributeColors(info.wAttributes);
}
}
private void applyAttribute() throws IOException {
out.flush();
short attributes = info.wAttributes;
// bold is simulated by high foreground intensity
if (bold) {
attributes |= FOREGROUND_INTENSITY;
}
// underline is simulated by high foreground intensity
if (underline) {
attributes |= BACKGROUND_INTENSITY;
}
if( negative ) {
attributes = invertAttributeColors(attributes);
}
Kernel32.INSTANCE.SetConsoleTextAttribute(console, attributes);
}
private short invertAttributeColors(short attributes) {
// Swap the the Foreground and Background bits.
int fg = 0x000F & attributes;
fg <<= 4;
int bg = 0X00F0 & attributes;
bg >>= 4;
attributes = (short) ((attributes & 0xFF00) | fg | bg);
return attributes;
}
private void applyCursorPosition() throws IOException {
info.dwCursorPosition.X = (short) Math.max(0, Math.min(info.dwSize.X - 1, info.dwCursorPosition.X));
info.dwCursorPosition.Y = (short) Math.max(0, Math.min(info.dwSize.Y - 1, info.dwCursorPosition.Y));
Kernel32.INSTANCE.SetConsoleCursorPosition(console, info.dwCursorPosition);
}
protected void processEraseScreen(int eraseOption) throws IOException {
getConsoleInfo();
IntByReference written = new IntByReference();
switch(eraseOption) {
case ERASE_SCREEN:
Kernel32.COORD topLeft = new Kernel32.COORD();
topLeft.X = 0;
topLeft.Y = info.srWindow.Top;
int screenLength = info.srWindow.height() * info.dwSize.X;
Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', screenLength, topLeft, written);
Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, screenLength, topLeft, written);
break;
case ERASE_SCREEN_TO_BEGINING:
Kernel32.COORD topLeft2 = new Kernel32.COORD();
topLeft2.X = 0;
topLeft2.Y = info.srWindow.Top;
int lengthToCursor = (info.dwCursorPosition.Y - info.srWindow.Top) * info.dwSize.X + info.dwCursorPosition.X;
Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', lengthToCursor, topLeft2, written);
Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, lengthToCursor, topLeft2, written);
break;
case ERASE_SCREEN_TO_END:
int lengthToEnd = (info.srWindow.Bottom - info.dwCursorPosition.Y) * info.dwSize.X +
(info.dwSize.X - info.dwCursorPosition.X);
Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', lengthToEnd, info.dwCursorPosition, written);
Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, lengthToEnd, info.dwCursorPosition, written);
}
}
protected void processEraseLine(int eraseOption) throws IOException {
getConsoleInfo();
IntByReference written = new IntByReference();
switch(eraseOption) {
case ERASE_LINE:
Kernel32.COORD leftColCurrRow = new Kernel32.COORD((short) 0, info.dwCursorPosition.Y);
Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', info.dwSize.X, leftColCurrRow, written);
Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, info.dwSize.X, leftColCurrRow, written);
break;
case ERASE_LINE_TO_BEGINING:
Kernel32.COORD leftColCurrRow2 = new Kernel32.COORD((short) 0, info.dwCursorPosition.Y);
Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', info.dwCursorPosition.X, leftColCurrRow2, written);
Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, info.dwCursorPosition.X, leftColCurrRow2, written);
break;
case ERASE_LINE_TO_END:
int lengthToLastCol = info.dwSize.X - info.dwCursorPosition.X;
Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', lengthToLastCol, info.dwCursorPosition, written);
Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, lengthToLastCol, info.dwCursorPosition, written);
}
}
protected void processCursorUpLine(int count) throws IOException {
getConsoleInfo();
info.dwCursorPosition.X = 0;
info.dwCursorPosition.Y -= count;
applyCursorPosition();
}
protected void processCursorDownLine(int count) throws IOException {
getConsoleInfo();
info.dwCursorPosition.X = 0;
info.dwCursorPosition.Y += count;
applyCursorPosition();
}
protected void processCursorLeft(int count) throws IOException {
getConsoleInfo();
info.dwCursorPosition.X -= count;
applyCursorPosition();
}
protected void processCursorRight(int count) throws IOException {
getConsoleInfo();
info.dwCursorPosition.X += count;
applyCursorPosition();
}
protected void processCursorDown(int count) throws IOException {
getConsoleInfo();
int nb = Math.max(0, info.dwCursorPosition.Y + count - info.dwSize.Y + 1);
if (nb != count) {
info.dwCursorPosition.Y += count;
applyCursorPosition();
}
if (nb > 0) {
Kernel32.SMALL_RECT scroll = new Kernel32.SMALL_RECT(info.srWindow);
scroll.Top = 0;
Kernel32.COORD org = new Kernel32.COORD();
org.X = 0;
org.Y = (short)(- nb);
Kernel32.CHAR_INFO info = new Kernel32.CHAR_INFO(' ', originalColors);
Kernel32.INSTANCE.ScrollConsoleScreenBuffer(console, scroll, scroll, org, info);
}
}
protected void processCursorUp(int count) throws IOException {
getConsoleInfo();
info.dwCursorPosition.Y -= count;
applyCursorPosition();
}
protected void processCursorTo(int row, int col) throws IOException {
getConsoleInfo();
info.dwCursorPosition.Y = (short) (info.srWindow.Top + row - 1);
info.dwCursorPosition.X = (short) (col - 1);
applyCursorPosition();
}
protected void processCursorToColumn(int x) throws IOException {
getConsoleInfo();
info.dwCursorPosition.X = (short) (x - 1);
applyCursorPosition();
}
@Override
protected void processSetForegroundColorExt(int paletteIndex) throws IOException {
int color = Colors.roundColor(paletteIndex, 16);
info.wAttributes = (short) ((info.wAttributes & ~0x0007) | ANSI_FOREGROUND_COLOR_MAP[color & 0x07]);
info.wAttributes = (short) ((info.wAttributes & ~FOREGROUND_INTENSITY) | (color >= 8 ? FOREGROUND_INTENSITY : 0));
applyAttribute();
}
protected void processSetBackgroundColorExt(int paletteIndex) throws IOException {
int color = Colors.roundColor(paletteIndex, 16);
info.wAttributes = (short)((info.wAttributes & ~0x0070 ) | ANSI_BACKGROUND_COLOR_MAP[color & 0x07]);
info.wAttributes = (short) ((info.wAttributes & ~BACKGROUND_INTENSITY) | (color >= 8 ? BACKGROUND_INTENSITY : 0));
applyAttribute();
}
protected void processDefaultTextColor() throws IOException {
info.wAttributes = (short)((info.wAttributes & ~0x000F ) | (originalColors & 0x000F));
applyAttribute();
}
protected void processDefaultBackgroundColor() throws IOException {
info.wAttributes = (short)((info.wAttributes & ~0x00F0 ) | (originalColors & 0x00F0));
applyAttribute();
}
protected void processAttributeRest() throws IOException {
info.wAttributes = (short)((info.wAttributes & ~0x00FF ) | originalColors);
this.negative = false;
this.bold = false;
this.underline = false;
applyAttribute();
}
protected void processSetAttribute(int attribute) throws IOException {
switch(attribute) {
case ATTRIBUTE_INTENSITY_BOLD:
bold = true;
applyAttribute();
break;
case ATTRIBUTE_INTENSITY_NORMAL:
bold = false;
applyAttribute();
break;
case ATTRIBUTE_UNDERLINE:
underline = true;
applyAttribute();
break;
case ATTRIBUTE_UNDERLINE_OFF:
underline = false;
applyAttribute();
break;
case ATTRIBUTE_NEGATIVE_ON:
negative = true;
applyAttribute();
break;
case ATTRIBUTE_NEGATIVE_OFF:
negative = false;
applyAttribute();
break;
}
}
protected void processSaveCursorPosition() throws IOException {
getConsoleInfo();
savedX = info.dwCursorPosition.X;
savedY = info.dwCursorPosition.Y;
}
protected void processRestoreCursorPosition() throws IOException {
// restore only if there was a save operation first
if (savedX != -1 && savedY != -1) {
out.flush();
info.dwCursorPosition.X = savedX;
info.dwCursorPosition.Y = savedY;
applyCursorPosition();
}
}
@Override
protected void processInsertLine(int optionInt) throws IOException {
getConsoleInfo();
Kernel32.SMALL_RECT scroll = new Kernel32.SMALL_RECT(info.srWindow);
scroll.Top = info.dwCursorPosition.Y;
Kernel32.COORD org = new Kernel32.COORD();
org.X = 0;
org.Y = (short)(info.dwCursorPosition.Y + optionInt);
Kernel32.CHAR_INFO info = new Kernel32.CHAR_INFO(' ', originalColors);
Kernel32.INSTANCE.ScrollConsoleScreenBuffer(console, scroll, scroll, org, info);
}
@Override
protected void processDeleteLine(int optionInt) throws IOException {
getConsoleInfo();
Kernel32.SMALL_RECT scroll = new Kernel32.SMALL_RECT(info.srWindow);
scroll.Top = info.dwCursorPosition.Y;
Kernel32.COORD org = new Kernel32.COORD();
org.X = 0;
org.Y = (short)(info.dwCursorPosition.Y - optionInt);
Kernel32.CHAR_INFO info = new Kernel32.CHAR_INFO(' ', originalColors);
Kernel32.INSTANCE.ScrollConsoleScreenBuffer(console, scroll, scroll, org, info);
}
protected void processChangeWindowTitle(String label) {
Kernel32.INSTANCE.SetConsoleTitle(label);
}
}
| 41.242938 | 139 | 0.655959 |
e94e7aa94bd56dd6620092b1702d2dea65edc637 | 1,454 | package com.eldermoraes.ch10.async.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author eldermoraes
*/
@WebServlet(name = "UserServlet", urlPatterns = {"/UserServlet"}, asyncSupported = true)
public class UserServlet extends HttpServlet {
@Inject
private UserBean userBean;
private final Jsonb jsonb = JsonbBuilder.create();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AsyncContext ctx = req.startAsync();
ctx.start(() -> {
try (PrintWriter writer = ctx.getResponse().getWriter()) {
writer.write(jsonb.toJson(userBean.getUser()));
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
ctx.complete();
});
}
@Override
public void destroy() {
try {
jsonb.close();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}
| 27.961538 | 113 | 0.673315 |
110d60927c7edf48b90eee083092f66285a4b176 | 2,083 | package com.example.screentime;
import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import static com.example.screentime.MainActivity.blockedList;
public class MyAccessibilityService extends AccessibilityService {
private Context context;
@RequiresApi (api = Build.VERSION_CODES.Q)
@Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
// if (accessibilityEvent.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
// if (accessibilityEvent.getPackageName().toString().equals(blockedList.get(accessibilityEvent.getPackageName().toString()))) {
// Intent serviceIntent = new Intent(MyAccessibilityService.this,AfterEvent.class);
// System.out.println("OK if condition + " + blockedList.get(accessibilityEvent.getPackageName().toString()));
// serviceIntent.putExtra("package_name", accessibilityEvent.getPackageName().toString());
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(serviceIntent);
// }
// }
final int eventType = accessibilityEvent.getEventType();
blockedList.get(accessibilityEvent.getPackageName().toString());
if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (accessibilityEvent.getPackageName().equals("com.google.android.youtube")) {
System.out.println("Youtube");
Toast toast = Toast.makeText(getApplicationContext(), "Youtube", Toast.LENGTH_LONG);
toast.show();
Intent intent = new Intent(MyAccessibilityService.this,AfterEvent.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
@Override
public void onInterrupt() {
}
}
| 42.510204 | 139 | 0.695631 |
37cbff97f46c03462092d11f625e4375b1ba1808 | 3,480 | /*-
* * Copyright 2016 Skymind,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 org.deeplearning4j.arbiter.optimize.parameter;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.deeplearning4j.arbiter.optimize.api.ParameterSpace;
import org.deeplearning4j.arbiter.optimize.parameter.continuous.ContinuousParameterSpace;
import org.deeplearning4j.arbiter.optimize.parameter.discrete.DiscreteParameterSpace;
import org.deeplearning4j.arbiter.optimize.parameter.integer.IntegerParameterSpace;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestParameterSpaces {
@Test
public void testContinuousParameterSpace() {
ContinuousParameterSpace cps = new ContinuousParameterSpace(0, 1);
cps.setIndices(0);
for (int i = 0; i < 10; i++) {
double d = i / 10.0;
assertEquals(d, cps.getValue(new double[] {d}), 0.0);
}
cps = new ContinuousParameterSpace(10, 20);
cps.setIndices(0);
for (int i = 0; i < 10; i++) {
double d = i / 10.0;
double exp = d * 10 + 10;
assertEquals(exp, cps.getValue(new double[] {d}), 0.0);
}
cps = new ContinuousParameterSpace(new NormalDistribution(0, 1));
NormalDistribution nd = new NormalDistribution(0, 1);
cps.setIndices(0);
for (int i = 0; i < 11; i++) {
double d = i / 10.0;
assertEquals(nd.inverseCumulativeProbability(d), cps.getValue(new double[] {d}), 1e-4);
}
}
@Test
public void testDiscreteParameterSpace() {
ParameterSpace<Integer> dps = new DiscreteParameterSpace<>(0, 1, 2, 3, 4);
dps.setIndices(0);
for (int i = 0; i < 5; i++) {
double d = i / 5.0 + 0.1; //Center
double dEdgeLower = i / 5.0 + 1e-8; //Edge case: just above split threshold
double dEdgeUpper = (i + 1) / 5.0 - 1e-8; //Edge case: just below split threshold
assertEquals(i, (int) dps.getValue(new double[] {d}));
assertEquals(i, (int) dps.getValue(new double[] {dEdgeLower}));
assertEquals(i, (int) dps.getValue(new double[] {dEdgeUpper}));
}
}
@Test
public void testIntegerParameterSpace() {
ParameterSpace<Integer> ips = new IntegerParameterSpace(0, 4);
ips.setIndices(0);
for (int i = 0; i < 5; i++) {
double d = i / 5.0 + 0.1; //Center
double dEdgeLower = i / 5.0 + 1e-8; //Edge case: just above split threshold
double dEdgeUpper = (i + 1) / 5.0 - 1e-8; //Edge case: just below split threshold
assertEquals(i, (int) ips.getValue(new double[] {d}));
assertEquals(i, (int) ips.getValue(new double[] {dEdgeLower}));
assertEquals(i, (int) ips.getValue(new double[] {dEdgeUpper}));
}
}
}
| 37.826087 | 99 | 0.618678 |
5957047f07d5fcdfcf836333e1409a9a98c22ac1 | 11,369 | package controllers.api;
import org.jetbrains.annotations.NotNull;
import play.Logger;
import play.libs.F;
import usecases.models.DataPoint;
import usecases.models.Metric;
import usecases.models.StatisticalValue;
import usecases.models.Value;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class DataPointMapper {
private static final String BYTES_UPLOADED = "BytesUploaded";
private static final String BYTES_DOWNLOADED = "BytesDownloaded";
private static final String APP_PACKAGE = "AppPackage";
private static final String DEVICE_MODEL = "DeviceModel";
private static final String SCREEN_DENSITY = "ScreenDensity";
private static final String SCREEN_SIZE = "ScreenSize";
private static final String INSTALLATION_UUID = "InstallationUUID";
private static final String NUMBER_OF_CORES = "NumberOfCores";
private static final String VERSION_NAME = "VersionName";
private static final String ANDROID_OS_VERSION = "AndroidOSVersion";
static final String IOS_VERSION = "IOSVersion";
private static final String BATTERY_SAVER_ON = "BatterySaverOn";
private static final String SCREEN_NAME = "ScreenName";
private static final String FRAMES_PER_SECOND = "FramesPerSecond";
private static final String FRAME_TIME = "FrameTime";
private static final String CONSUMPTION = "Consumption";
private static final String INTERNAL_STORAGE_WRITTEN_BYTES = "InternalStorageWrittenBytes";
private static final String SHARED_PREFERENCES_WRITTEN_BYTES = "SharedPreferencesWrittenBytes";
private static final String USER_DEFAULTS_WRITTEN_BYTES = "UserDefaultsWrittenBytes";
private static final String BYTES_ALLOCATED = "BytesAllocated";
private static final String ON_ACTIVITY_CREATED_TIME = "OnActivityCreatedTime";
private static final String ON_ACTIVITY_STARTED_TIME = "OnActivityStartedTime";
private static final String ON_ACTIVITY_RESUMED_TIME = "OnActivityResumedTime";
private static final String ACTIVITY_VISIBLE_TIME = "ActivityTime";
private static final String ON_ACTIVITY_PAUSED_TIME = "OnActivityPausedTime";
private static final String ON_ACTIVITY_STOPPED_TIME = "OnActivityStoppedTime";
private static final String ON_ACTIVITY_DESTROYED_TIME = "OnActivityDestroyedTime";
private static final AndroidAPI MIN_CPU_API_SUPPORTED = new AndroidAPI(19);
private static final long MIN_FRAME_TIME_ALLOWED = TimeUnit.MILLISECONDS.toNanos(16);
@NotNull
public List<Metric> mapMetrics(ReportRequest reportRequest) {
List<Metric> metrics = new ArrayList<>();
metrics.add(new Metric("network_data", this.mapNetwork(reportRequest)));
metrics.add(new Metric("ui_data", this.mapUi(reportRequest)));
metrics.add(new Metric("cpu_data", this.mapCpu(reportRequest)));
metrics.add(new Metric("gpu_data", this.mapGpu(reportRequest)));
metrics.add(new Metric("memory_data", this.mapMemory(reportRequest)));
metrics.add(new Metric("disk_data", this.mapDisk(reportRequest)));
return metrics;
}
public List<DataPoint> mapNetwork(ReportRequest reportRequest) {
List<DataPoint> dataPoints = new ArrayList<>();
reportRequest.getNetwork().forEach((network) -> {
List<F.Tuple<String, Value>> measurements = new ArrayList<>();
measurements.add(new F.Tuple<>(BYTES_UPLOADED, Value.toBasicValue(network.getBytesUploaded())));
measurements.add(new F.Tuple<>(BYTES_DOWNLOADED, Value.toBasicValue(network.getBytesDownloaded())));
List<F.Tuple<String, String>> tags = new ArrayList<>();
addReportLevelTags(tags, reportRequest);
addDataPointLevelTags(tags, network);
dataPoints.add(new DataPoint(new Date(network.getTimestamp()), measurements, tags));
});
return dataPoints;
}
public List<DataPoint> mapUi(ReportRequest reportRequest) {
List<DataPoint> dataPoints = new ArrayList<>();
reportRequest.getUi().forEach((ui) -> {
List<F.Tuple<String, Value>> measurements = new ArrayList<>();
StatisticalValue frameTime = ui.getFrameTime();
if (frameTime != null && frameTime.getMean() >= MIN_FRAME_TIME_ALLOWED) {
measurements.add(new F.Tuple<>(FRAME_TIME, frameTime));
measurements.add(new F.Tuple<>(FRAMES_PER_SECOND, computeFramesPerSecond(frameTime)));
} else {
Logger.error("Invalid frame time metric detected " + reportRequest);
}
measurements.add(new F.Tuple<>(ON_ACTIVITY_CREATED_TIME, ui.getOnActivityCreatedTime()));
measurements.add(new F.Tuple<>(ON_ACTIVITY_STARTED_TIME, ui.getOnActivityStartedTime()));
measurements.add(new F.Tuple<>(ON_ACTIVITY_RESUMED_TIME, ui.getOnActivityResumedTime()));
measurements.add(new F.Tuple<>(ACTIVITY_VISIBLE_TIME, ui.getActivityVisibleTime()));
measurements.add(new F.Tuple<>(ON_ACTIVITY_PAUSED_TIME, ui.getOnActivityPausedTime()));
measurements.add(new F.Tuple<>(ON_ACTIVITY_STOPPED_TIME, ui.getOnActivityStoppedTime()));
measurements.add(new F.Tuple<>(ON_ACTIVITY_DESTROYED_TIME, ui.getOnActivityDestroyedTime()));
List<F.Tuple<String, String>> tags = new ArrayList<>();
addReportLevelTags(tags, reportRequest);
addDataPointLevelTags(tags, ui);
tags.add(new F.Tuple<>(SCREEN_NAME, ui.getScreen()));
dataPoints.add(new DataPoint(new Date(ui.getTimestamp()), measurements, tags));
});
return dataPoints;
}
private StatisticalValue computeFramesPerSecond(StatisticalValue frameTime) {
if (frameTime == null) {
return null;
}
return new StatisticalValue(
frameTimeToFramePerSecond(frameTime.getMean()),
frameTimeToFramePerSecond(frameTime.getP10()),
frameTimeToFramePerSecond(frameTime.getP90())
);
}
private double frameTimeToFramePerSecond(double value) {
if (value == 0.0) return 1000000000.0;
return (1.0 / value) * 1000000000.0;
}
public List<DataPoint> mapCpu(ReportRequest reportRequest) {
List<DataPoint> dataPoints = new ArrayList<>();
reportRequest.getCpu().forEach((cpu) -> {
mapProcessingUnit(reportRequest, dataPoints, cpu, MIN_CPU_API_SUPPORTED);
});
return dataPoints;
}
public List<DataPoint> mapGpu(ReportRequest reportRequest) {
List<DataPoint> dataPoints = new ArrayList<>();
reportRequest.getGpu().forEach((gpu) -> {
mapProcessingUnit(reportRequest, dataPoints, gpu);
});
return dataPoints;
}
public List<DataPoint> mapMemory(ReportRequest reportRequest) {
List<DataPoint> dataPoints = new ArrayList<>();
reportRequest.getMemory().forEach((memory) -> {
mapMemory(reportRequest, dataPoints, memory);
});
return dataPoints;
}
public List<DataPoint> mapDisk(ReportRequest reportRequest) {
List<DataPoint> dataPoints = new ArrayList<>();
reportRequest.getDisk().forEach((disk) -> {
mapDisk(reportRequest, dataPoints, disk);
});
return dataPoints;
}
private void addDataPointLevelTags(List<F.Tuple<String, String>> tags, DatapointTags datapointTags) {
tags.add(new F.Tuple<>(VERSION_NAME, datapointTags.getAppVersionName()));
tags.add(new F.Tuple<>(ANDROID_OS_VERSION, datapointTags.getAndroidOSVersion()));
tags.add(new F.Tuple<>(IOS_VERSION, datapointTags.getIOSVersion()));
tags.add(new F.Tuple<>(BATTERY_SAVER_ON, Boolean.toString(datapointTags.isBatterySaverOn())));
}
private void addReportLevelTags(List<F.Tuple<String, String>> tags, ReportRequest reportRequest) {
tags.add(new F.Tuple<>(APP_PACKAGE, reportRequest.getAppPackage()));
tags.add(new F.Tuple<>(DEVICE_MODEL, reportRequest.getDeviceModel()));
tags.add(new F.Tuple<>(SCREEN_DENSITY, reportRequest.getScreenDensity()));
tags.add(new F.Tuple<>(SCREEN_SIZE, reportRequest.getScreenSize()));
tags.add(new F.Tuple<>(INSTALLATION_UUID, reportRequest.getInstallationUUID()));
tags.add(new F.Tuple<>(NUMBER_OF_CORES, Integer.toString(reportRequest.getNumberOfCores())));
}
private void mapProcessingUnit(ReportRequest reportRequest, List<DataPoint> dataPoints, ProcessingUnit processingUnit) {
mapProcessingUnit(reportRequest, dataPoints, processingUnit, null);
}
private void mapProcessingUnit(ReportRequest reportRequest, List<DataPoint> dataPoints, ProcessingUnit processingUnit, AndroidAPI minAPISupported) {
/* We have noticed a bug in the Android SDK and the client is reporting CPU consumption as 0 % always.
* Based on this bug we have decided to don't store some data points if the host API is not supported.
* In the case of the CPU metric, the min API supported is 19.
*/
if (processingUnit.isAndroid()) {
AndroidAPI metricAndroidAPI = AndroidAPI.fromString(processingUnit.getAndroidOSVersion());
if (minAPISupported != null && metricAndroidAPI.compareTo(minAPISupported) > 0) {
return;
}
}
List<F.Tuple<String, Value>> measurements = new ArrayList<>();
measurements.add(new F.Tuple<>(CONSUMPTION, Value.toBasicValue(processingUnit.getConsumption())));
List<F.Tuple<String, String>> tags = new ArrayList<>();
addReportLevelTags(tags, reportRequest);
addDataPointLevelTags(tags, processingUnit);
dataPoints.add(new DataPoint(new Date(processingUnit.getTimestamp()), measurements, tags));
}
private void mapMemory(ReportRequest reportRequest, List<DataPoint> dataPoints, ReportRequest.Memory memory) {
List<F.Tuple<String, Value>> measurements = new ArrayList<>();
measurements.add(new F.Tuple<>(CONSUMPTION, Value.toBasicValue(memory.getConsumption())));
measurements.add(new F.Tuple<>(BYTES_ALLOCATED, Value.toBasicValue(memory.getBytesAllocated())));
List<F.Tuple<String, String>> tags = new ArrayList<>();
addReportLevelTags(tags, reportRequest);
addDataPointLevelTags(tags, memory);
dataPoints.add(new DataPoint(new Date(memory.getTimestamp()), measurements, tags));
}
private void mapDisk(ReportRequest reportRequest, List<DataPoint> dataPoints, ReportRequest.Disk disk) {
List<F.Tuple<String, Value>> measurements = new ArrayList<>();
measurements.add(new F.Tuple<>(INTERNAL_STORAGE_WRITTEN_BYTES, Value.toBasicValue(disk.getInternalStorageWrittenBytes())));
measurements.add(new F.Tuple<>(SHARED_PREFERENCES_WRITTEN_BYTES, Value.toBasicValue(disk.getSharedPreferencesWrittenBytes())));
measurements.add(new F.Tuple<>(USER_DEFAULTS_WRITTEN_BYTES, Value.toBasicValue(disk.getUserDefaultsWrittenBytes())));
List<F.Tuple<String, String>> tags = new ArrayList<>();
addReportLevelTags(tags, reportRequest);
addDataPointLevelTags(tags, disk);
dataPoints.add(new DataPoint(new Date(disk.getTimestamp()), measurements, tags));
}
}
| 49.864035 | 152 | 0.702348 |
53e3c6447d6ebae99f7f58c6fa713e95221a39fb | 288 | package net.xfunction.java.api.modules.activity.mapper.xfunction;
import net.xfunction.java.api.core.utils.XfunMapper;
import net.xfunction.java.api.modules.activity.model.xfunction.XfuActivityLottery;
public interface XfuActivityLotteryMapper extends XfunMapper<XfuActivityLottery> {
} | 41.142857 | 82 | 0.854167 |
b852f54af0d672bbdfe9f0bb9a96dc14bf0bc6f5 | 452 | package de.unibi.agbi.biodwh2.drugbank.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public final class Enzyme extends Interactant {
@JacksonXmlProperty(isAttribute = true)
public int position;
@JsonProperty("inhibition-strength")
public String inhibitionStrength;
@JsonProperty("induction-strength")
public String inductionStrength;
}
| 32.285714 | 74 | 0.794248 |
3b13558d1b8d71d5c8ff716efaf0c9b42e46576d | 1,827 | /*!
* mifmi-commons4j
* https://github.com/mifmi/mifmi-commons4j
*
* Copyright (c) 2015 mifmi.org and other contributors
* Released under the MIT license
* https://opensource.org/licenses/MIT
*/
package org.mifmi.commons4j.valuefilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class TypicalValueFilters<T, U> implements ValueFilter<T, U> {
private List<ValueFilter<T, U>> filters;
public TypicalValueFilters() {
this.filters = new ArrayList<ValueFilter<T, U>>();
}
public TypicalValueFilters(int capacity) {
this.filters = new ArrayList<ValueFilter<T, U>>(capacity);
}
public TypicalValueFilters(Collection<ValueFilter<T, U>> filters) {
if (filters == null) {
throw new NullPointerException();
}
this.filters = new ArrayList<ValueFilter<T, U>>(filters);
}
public TypicalValueFilters(ValueFilter<T, U>... filters) {
if (filters == null) {
throw new NullPointerException();
}
this.filters = new ArrayList<ValueFilter<T, U>>(filters.length);
for (ValueFilter<T, U> filter : filters) {
this.filters.add(filter);
}
}
public TypicalValueFilters<T, U> add(ValueFilter<T, U> filter) {
this.filters.add(filter);
return this;
}
public TypicalValueFilters<T, U> addAll(Collection<ValueFilter<T, U>> filters) {
this.filters.addAll(filters);
return this;
}
public TypicalValueFilters<T, U> remove(ValueFilter<T, U> filter) {
this.filters.remove(filter);
return this;
}
public int size() {
return this.filters.size();
}
public <R extends U> R filter(T value) {
@SuppressWarnings("unchecked")
R r = (R)filterObject(value);
return r;
}
public Object filterObject(Object value) {
Object v = value;
for (ValueFilter<T, U> filter : this.filters) {
v = filter.filterObject(v);
}
return v;
}
}
| 23.727273 | 81 | 0.698413 |
b077366e6697a1a0832ee489495085ae26f554eb | 2,807 | /* Copyright 2018 The TensorFlow 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.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.core;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.PrimitiveOp;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.types.family.TType;
/**
* Destroys the temporary variable and returns its final value.
* <p>
* Sets output to the value of the Tensor pointed to by 'ref', then destroys
* the temporary variable called 'var_name'.
* All other uses of 'ref' <i>must</i> have executed before this op.
* This is typically achieved by chaining the ref through each assign op, or by
* using control dependencies.
* <p>
* Outputs the final value of the tensor pointed to by 'ref'.
*
* @param <T> data type for {@code value()} output
*/
@Operator
public final class DestroyTemporaryVariable<T extends TType> extends PrimitiveOp implements Operand<T> {
/**
* Factory method to create a class wrapping a new DestroyTemporaryVariable operation.
*
* @param scope current scope
* @param ref A reference to the temporary variable tensor.
* @param varName Name of the temporary variable, usually the name of the matching
* 'TemporaryVariable' op.
* @return a new instance of DestroyTemporaryVariable
*/
public static <T extends TType> DestroyTemporaryVariable<T> create(Scope scope, Operand<T> ref, String varName) {
OperationBuilder opBuilder = scope.env().opBuilder("DestroyTemporaryVariable", scope.makeOpName("DestroyTemporaryVariable"));
opBuilder.addInput(ref.asOutput());
opBuilder = scope.applyControlDependencies(opBuilder);
opBuilder.setAttr("var_name", varName);
return new DestroyTemporaryVariable<T>(opBuilder.build());
}
/**
*/
public Output<T> value() {
return value;
}
@Override
public Output<T> asOutput() {
return value;
}
private Output<T> value;
private DestroyTemporaryVariable(Operation operation) {
super(operation);
int outputIdx = 0;
value = operation.output(outputIdx++);
}
}
| 34.654321 | 129 | 0.724261 |
853cf847e2d82503c53c588217011a250802d38d | 98 | package us.nineworlds.serenity.common.media.model;
public interface IDirector extends ICrew {
}
| 16.333333 | 50 | 0.806122 |
678f339ecaecb2b0667e95b9f0d1a912173f305c | 6,751 | /*
* 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 visual;
/**
*
* @author Usuario
*/
public class JpArchivoTxt extends javax.swing.JPanel {
JfInicio ventInicio;
public JpArchivoTxt(JfInicio ventInicio) {
initComponents();
this.ventInicio = ventInicio;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txtContenido = new java.awt.TextArea();
lblIconTxt = new javax.swing.JLabel();
txtTitulo = new javax.swing.JTextField();
btnSave = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
setBackground(new java.awt.Color(102, 102, 255));
setMaximumSize(new java.awt.Dimension(1366, 768));
setMinimumSize(new java.awt.Dimension(1366, 768));
txtContenido.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
txtContenido.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
lblIconTxt.setIcon(new javax.swing.ImageIcon("C:\\Users\\Usuario\\Documents\\NetBeansProjects\\ProyectoSistemasOper\\src\\main\\java\\image\\iconTxt.png")); // NOI18N
txtTitulo.setBackground(new java.awt.Color(255, 255, 255));
txtTitulo.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
txtTitulo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txtTitulo.setText(".MiTxt");
txtTitulo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTituloActionPerformed(evt);
}
});
btnSave.setIcon(new javax.swing.ImageIcon("C:\\Users\\Usuario\\Documents\\NetBeansProjects\\ProyectoSistemasOper\\src\\main\\java\\image\\iconSave.png")); // NOI18N
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnCancel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Usuario\\Documents\\NetBeansProjects\\ProyectoSistemasOper\\src\\main\\java\\image\\iconCancel.png")); // NOI18N
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtContenido, javax.swing.GroupLayout.PREFERRED_SIZE, 1319, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(lblIconTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(391, 391, 391)
.addComponent(txtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(79, 79, 79)))
.addContainerGap(23, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblIconTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
.addComponent(txtTitulo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtContenido, javax.swing.GroupLayout.PREFERRED_SIZE, 596, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60))
);
}// </editor-fold>//GEN-END:initComponents
private void txtTituloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTituloActionPerformed
}//GEN-LAST:event_txtTituloActionPerformed
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
String titulo, cajaTexto;
cajaTexto = txtContenido.getText();
titulo = txtContenido.getText();
System.out.println("titulo: "+titulo+"/n"+"contenido"+cajaTexto);
//FALTA crear archivo txt
//this.setVisible(false);
}//GEN-LAST:event_btnSaveActionPerformed
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnSave;
private javax.swing.JLabel lblIconTxt;
private java.awt.TextArea txtContenido;
private javax.swing.JTextField txtTitulo;
// End of variables declaration//GEN-END:variables
}
| 51.143939 | 176 | 0.673974 |
d600c36b43aecbd2fc38b894b642f2eb1a793bfc | 7,524 | package com.nitsilchar.hp.passwordStorage.activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseNetworkException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
import com.nitsilchar.hp.passwordStorage.model.AppStatus;
import com.nitsilchar.hp.passwordStorage.R;
import io.fabric.sdk.android.Fabric;
public class RegistrationActivity extends AppCompatActivity implements View.OnClickListener {
Button register;
Button existinguser;
String str_Password, str_RePassword, str_Email;
EditText edt_Password, edt_RePassword, edt_Email;
private ProgressBar progressBar;
private FirebaseAuth auth;
AppStatus appStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_registration);
auth = FirebaseAuth.getInstance();
appStatus=new AppStatus(getApplicationContext());
register = (Button) findViewById(R.id.btn_register);
existinguser = (Button) findViewById(R.id.existinguser);
edt_Password = (EditText) findViewById(R.id.edt_Rpassword);
edt_RePassword = (EditText) findViewById(R.id.edt_RRepassword);
edt_Email = (EditText) findViewById(R.id.edt_email);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
register.setOnClickListener(this);
existinguser.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v==existinguser) {
Intent go = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(go);
}
if (appStatus.isOnline()) {
str_Password = edt_Password.getText().toString();
str_RePassword = edt_RePassword.getText().toString();
str_Email = edt_Email.getText().toString();
if (str_Email.length() == 0 & str_Password.length() == 0
& str_RePassword.length() == 0) {
Toast.makeText(getApplicationContext(),
R.string.registration_all_fields_mandatory, Toast.LENGTH_LONG)
.show();
} else if (str_Password.length() == 0) {
Toast.makeText(getApplicationContext(),
R.string.registration_enterPass, Toast.LENGTH_LONG).show();
} else if (str_RePassword.length() == 0) {
Toast.makeText(getApplicationContext(),
R.string.registration_enterRePass, Toast.LENGTH_LONG).show();
} else if (str_Email.length() == 0) {
Toast.makeText(getApplicationContext(),
R.string.registration_enter_email, Toast.LENGTH_LONG).show();
} else if (str_Password.contains(str_RePassword) != str_RePassword
.contains(str_Password)) {
Toast.makeText(getApplicationContext(),
R.string.registration_pass_notmatch, Toast.LENGTH_LONG)
.show();
} else {
progressBar.setVisibility(View.VISIBLE);
SplashActivity.editor.putString("password", str_RePassword);
SplashActivity.editor.putString("email", str_Email);
SplashActivity.editor.commit();
progressBar.setVisibility(View.VISIBLE);
auth.createUserWithEmailAndPassword(str_Email, str_Password)
.addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
try {
throw task.getException();
} catch (FirebaseNetworkException e) {
Toast.makeText(RegistrationActivity.this,
R.string.registration_network_problem,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(RegistrationActivity.this,
R.string.registration_error+String.valueOf(task.getException()),Toast.LENGTH_SHORT).show();
}
Toast.makeText(RegistrationActivity.this,
R.string.registration_error+String.valueOf(task.getException()),Toast.LENGTH_SHORT).show();
if (task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(RegistrationActivity.this,
R.string.registration_email_collision, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(RegistrationActivity.this,
R.string.registration_check_email_verify, Toast.LENGTH_LONG).show();
sendVerificationEmail();
}
}
});
}
} else {
Toast.makeText(getApplicationContext(),R.string.appstatus_no_connection,Toast.LENGTH_LONG).show();
}
}
private void sendVerificationEmail(){
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent sendtoLogin = new Intent(getApplicationContext(),
LoginRegistrationActivity.class);
startActivity(sendtoLogin);
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(RegistrationActivity.this, SplashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
}
| 46.444444 | 140 | 0.577087 |
d3173cf9d8b90aeb063d2ca81199f7f764d4b752 | 13,827 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package pl.undersoft.picatch;
public final class R {
public static final class array {
public static final int doc_types=0x7f070000;
public static final int product_filter_list=0x7f070001;
}
public static final class attr {
}
public static final class color {
public static final int actionBar_background=0x7f080000;
public static final int actionBar_foreground=0x7f080001;
public static final int black_overlay=0x7f080002;
}
public static final class dimen {
public static final int activity_horizontal_margin=0x7f060000;
public static final int activity_vertical_margin=0x7f060001;
}
public static final class drawable {
public static final int celownik=0x7f020000;
public static final int dividerline=0x7f020001;
public static final int gradient_box=0x7f020002;
public static final int ic_action_add_down=0x7f020003;
public static final int ic_action_add_up=0x7f020004;
public static final int ic_action_clear_down=0x7f020005;
public static final int ic_action_clear_up=0x7f020006;
public static final int ic_action_delete_down=0x7f020007;
public static final int ic_action_delete_up=0x7f020008;
public static final int ic_action_edit_down=0x7f020009;
public static final int ic_action_edit_up=0x7f02000a;
public static final int ic_action_flash_disabled=0x7f02000b;
public static final int ic_action_info_down=0x7f02000c;
public static final int ic_action_info_up=0x7f02000d;
public static final int ic_action_menu_up=0x7f02000e;
public static final int ic_action_name=0x7f02000f;
public static final int ic_action_name2=0x7f020010;
public static final int ic_action_ok_down=0x7f020011;
public static final int ic_action_ok_up=0x7f020012;
public static final int ic_action_product_list_down=0x7f020013;
public static final int ic_action_product_list_up=0x7f020014;
public static final int ic_action_scan_down=0x7f020015;
public static final int ic_action_scan_up=0x7f020016;
public static final int ic_action_search_down=0x7f020017;
public static final int ic_action_search_up=0x7f020018;
public static final int ic_action_send_down=0x7f020019;
public static final int ic_action_send_up=0x7f02001a;
public static final int ic_options_up=0x7f02001b;
public static final int picatch_add_button=0x7f02001c;
public static final int picatch_button=0x7f02001d;
public static final int picatch_clear_button=0x7f02001e;
public static final int picatch_delete_button=0x7f02001f;
public static final int picatch_edit_button=0x7f020020;
public static final int picatch_help_button=0x7f020021;
public static final int picatch_menu_button=0x7f020022;
public static final int picatch_ok_button=0x7f020023;
public static final int picatch_product_list_button=0x7f020024;
public static final int picatch_scan_button=0x7f020025;
public static final int picatch_search_button=0x7f020026;
public static final int picatch_send_button=0x7f020027;
public static final int undersoft=0x7f020028;
}
public static final class id {
public static final int a_doc_add_b_1=0x7f0b0083;
public static final int a_doc_delete_b_1=0x7f0b0087;
public static final int a_doc_details_b_1=0x7f0b0084;
public static final int a_doc_edit_b_1=0x7f0b0085;
public static final int a_doc_send_b_1=0x7f0b0086;
public static final int add_b_1=0x7f0b000d;
public static final int assembling_b=0x7f0b005f;
public static final int barcode_t=0x7f0b002c;
public static final int button=0x7f0b0036;
public static final int button2=0x7f0b0064;
public static final int button3=0x7f0b007c;
public static final int button4=0x7f0b007d;
public static final int button5=0x7f0b007e;
public static final int button6=0x7f0b0080;
public static final int button7=0x7f0b0081;
public static final int button8=0x7f0b0074;
public static final int button9=0x7f0b0076;
public static final int cenasp_e_t=0x7f0b0051;
public static final int cenasp_t=0x7f0b0041;
public static final int cenazk_e_t=0x7f0b0052;
public static final int cenazk_t=0x7f0b0042;
public static final int clear_b_2_1=0x7f0b0037;
public static final int col_details_edit_barcode_t=0x7f0b0047;
public static final int col_details_edit_name_t=0x7f0b0018;
public static final int col_flash_b=0x7f0b0044;
public static final int collect_b_2=0x7f0b0026;
public static final int collecting_b=0x7f0b005e;
public static final int count_e_t=0x7f0b004b;
public static final int count_t=0x7f0b003b;
public static final int delete_b_1=0x7f0b0011;
public static final int delete_b_2=0x7f0b0028;
public static final int depot_autodown_t=0x7f0b006a;
public static final int depot_ip_t=0x7f0b0069;
public static final int depot_licence_t=0x7f0b0070;
public static final int depot_port_t=0x7f0b006c;
public static final int details_b_1=0x7f0b000e;
public static final int doc_date_t=0x7f0b001d;
public static final int doc_list_1_1=0x7f0b000c;
public static final int doc_type_s_1_1=0x7f0b001b;
public static final int doc_type_t=0x7f0b001a;
public static final int download_data_b=0x7f0b005b;
public static final int download_progressBar=0x7f0b0057;
public static final int editText=0x7f0b0072;
public static final int editText1_l_1=0x7f0b0078;
public static final int editText1_l_2=0x7f0b0079;
public static final int editText1_l_3=0x7f0b007a;
public static final int editText1_l_4=0x7f0b007b;
public static final int edit_b_1=0x7f0b000f;
public static final int edit_b_2=0x7f0b0025;
public static final int frameLayout=0x7f0b002d;
public static final int frameLayout1=0x7f0b0032;
public static final int frameLayout2_1=0x7f0b0030;
public static final int ilosc_e_t=0x7f0b004c;
public static final int ilosc_t=0x7f0b003c;
public static final int imageView=0x7f0b0065;
public static final int imageView2=0x7f0b0062;
public static final int imageView_2_1=0x7f0b0031;
public static final int insert_progressBar=0x7f0b0059;
public static final int layout_1=0x7f0b0077;
public static final int listView=0x7f0b007f;
public static final int listView_2=0x7f0b0024;
public static final int listView_a_doc_1=0x7f0b0082;
public static final int menu_layout=0x7f0b005d;
public static final int ok_b_2_1=0x7f0b0035;
public static final int options_b=0x7f0b0063;
public static final int options_save_b=0x7f0b006e;
public static final int pager=0x7f0b0005;
public static final int progressBar=0x7f0b005c;
public static final int reg_prod_list=0x7f0b0075;
public static final int registers_b=0x7f0b0060;
public static final int save_b=0x7f0b0015;
public static final int scan_b_2_1=0x7f0b0033;
public static final int search_b_2_1=0x7f0b0034;
public static final int sendProgress=0x7f0b0012;
public static final int sendProgress2=0x7f0b0029;
public static final int send_b_1=0x7f0b0010;
public static final int send_b_2=0x7f0b0027;
public static final int spinner_filter=0x7f0b0073;
public static final int stan_e_t=0x7f0b004d;
public static final int stan_t=0x7f0b003d;
public static final int tableLayout=0x7f0b0016;
public static final int tableLayout2=0x7f0b002f;
public static final int tableLayout3=0x7f0b0007;
public static final int tableLayout4=0x7f0b001f;
public static final int tableLayout6=0x7f0b0000;
public static final int tax_e_t=0x7f0b0053;
public static final int tax_t=0x7f0b0043;
public static final int textView=0x7f0b0008;
public static final int textView1=0x7f0b002e;
public static final int textView10=0x7f0b0038;
public static final int textView11=0x7f0b0040;
public static final int textView12=0x7f0b0039;
public static final int textView13=0x7f0b003a;
public static final int textView14=0x7f0b0067;
public static final int textView15=0x7f0b0055;
public static final int textView16=0x7f0b0009;
public static final int textView17=0x7f0b000a;
public static final int textView18=0x7f0b000b;
public static final int textView19=0x7f0b0020;
public static final int textView2=0x7f0b0066;
public static final int textView20=0x7f0b0021;
public static final int textView21=0x7f0b0022;
public static final int textView22=0x7f0b0023;
public static final int textView23=0x7f0b002a;
public static final int textView24=0x7f0b0014;
public static final int textView25=0x7f0b0045;
public static final int textView26=0x7f0b0068;
public static final int textView27=0x7f0b006d;
public static final int textView28=0x7f0b006b;
public static final int textView29=0x7f0b006f;
public static final int textView3=0x7f0b0013;
public static final int textView30=0x7f0b0071;
public static final int textView31=0x7f0b0048;
public static final int textView32=0x7f0b0049;
public static final int textView33=0x7f0b004a;
public static final int textView34=0x7f0b004e;
public static final int textView35=0x7f0b004f;
public static final int textView36=0x7f0b0050;
public static final int textView4=0x7f0b0019;
public static final int textView41=0x7f0b0001;
public static final int textView42=0x7f0b0002;
public static final int textView43=0x7f0b0003;
public static final int textView44=0x7f0b0004;
public static final int textView5=0x7f0b0017;
public static final int textView6=0x7f0b001c;
public static final int textView7=0x7f0b002b;
public static final int textView8=0x7f0b003e;
public static final int textView9=0x7f0b003f;
public static final int textView_1=0x7f0b0006;
public static final int textView_2=0x7f0b001e;
public static final int textView_dt_1=0x7f0b0056;
public static final int textView_dt_2=0x7f0b0058;
public static final int textView_dt_3=0x7f0b005a;
public static final int transfer_b=0x7f0b0061;
public static final int update_b=0x7f0b0054;
public static final int update_e_b=0x7f0b0046;
}
public static final class layout {
public static final int activity_picatch__assembling__doc=0x7f040000;
public static final int activity_picatch__collecting__doc=0x7f040001;
public static final int activity_picatch__collecting__doc_add=0x7f040002;
public static final int activity_picatch__collecting__doc_details=0x7f040003;
public static final int activity_picatch__collecting__doc_details_collecting=0x7f040004;
public static final int activity_picatch__collecting__doc_details_edit=0x7f040005;
public static final int activity_picatch__collecting__doc_edit=0x7f040006;
public static final int activity_picatch__data_transfer=0x7f040007;
public static final int activity_picatch__data_transfer2=0x7f040008;
public static final int activity_picatch__menu=0x7f040009;
public static final int activity_picatch__options=0x7f04000a;
public static final int activity_picatch__registers_products=0x7f04000b;
public static final int doc_list_elem=0x7f04000c;
public static final int doc_list_layout=0x7f04000d;
public static final int fragment_assembling_doc_after=0x7f04000e;
public static final int fragment_assembling_doc_to=0x7f04000f;
public static final int spinner_list_products=0x7f040010;
}
public static final class mipmap {
public static final int ic_action_scan_down=0x7f030000;
public static final int ic_action_scan_up=0x7f030001;
public static final int ic_launcher=0x7f030002;
}
public static final class raw {
public static final int filip21=0x7f050000;
public static final int filip22=0x7f050001;
}
public static final class string {
public static final int app_name=0x7f090000;
public static final int title_activity_picatch__assembling__doc=0x7f090001;
public static final int title_activity_picatch__collecting__doc_1=0x7f090002;
public static final int title_activity_picatch__collecting__doc_1_1=0x7f090003;
public static final int title_activity_picatch__collecting__doc_2=0x7f090004;
public static final int title_activity_picatch__collecting__doc_2_1=0x7f090005;
public static final int title_activity_picatch__collecting__doc_details_edit=0x7f090006;
public static final int title_activity_picatch__options=0x7f090007;
public static final int title_activity_picatch__registers_products=0x7f090008;
public static final int title_activity_picatch__tcp__download=0x7f090009;
}
public static final class style {
public static final int BarraProgreso=0x7f0a0000;
public static final int EnableActionBar=0x7f0a0001;
}
}
| 54.869048 | 96 | 0.745064 |
668e45392b564434da2cf21743b09ec78406ac24 | 6,078 | package ch.neukom.convenientstreams;
import com.google.common.collect.Lists;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Stream;
/**
* collection of collectors to be used on {@link Try}
*/
public class TryCollectors {
private TryCollectors() {
}
/**
* @param <P> value type of Try
* @param <E> exception type of Try
* @return a collector that returns true if no exception was caught in any Try, false otherwise
*/
public static <P, E extends Exception> Collector<Try<P, E>, HashSet<E>, Boolean> isSuccess() {
return hasState(true);
}
/**
* @param <P> value type of Try
* @param <E> exception type of Try
* @return a collector that returns true if an exception was caught in any Try, false otherwise
*/
public static <P, E extends Exception> Collector<Try<P, E>, HashSet<E>, Boolean> isFailure() {
return hasState(false);
}
private static <P, E extends Exception> Collector<Try<P, E>, HashSet<E>, Boolean> hasState(boolean isSuccess) {
return new Collector<Try<P, E>, HashSet<E>, Boolean>() {
@Override
public Supplier<HashSet<E>> supplier() {
return HashSet::new;
}
@Override
public BiConsumer<HashSet<E>, Try<P, E>> accumulator() {
return (exceptions, trying) -> {
if(isSuccess ? trying.success() : trying.failure()) {
exceptions.add(trying.getException());
}
};
}
@Override
public BinaryOperator<HashSet<E>> combiner() {
return (first, second) -> {
first.addAll(second);
return first;
};
}
@Override
public Function<HashSet<E>, Boolean> finisher() {
return HashSet::isEmpty;
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
};
}
/**
* @param <P> value type of Try
* @param <E> exception type of Try
* @return a collector that collects the values of all successfully executed functions
*/
public static <P, E extends Exception> Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<P>> collectSuccess() {
return collectList((list, trying) -> {
if(trying.success()) {
list.add(trying);
}
});
}
/**
* @param <P> value type of Try
* @param <E> exception type of Try
* @return a collector that assumes all functions where executed successfully and collects their values, throws a {@link TryCollectorException} otherwise
*/
public static <P, E extends Exception> Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<P>> collectOrThrow() {
return collectList((list, trying) -> {
if(trying.success()) {
list.add(trying);
} else {
throw new TryCollectorException(trying.getException());
}
});
}
/**
* @param <P> value type of Try
* @param <E> exception type of Try
* @return a collector that collects the values of all executed functions up until the first caught exception
*/
public static <P, E extends Exception> Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<P>> collectUntilException() {
List<Exception> exceptions = Lists.newArrayList();
return collectList((list, trying) -> {
if(exceptions.isEmpty() && trying.success()) {
list.add(trying);
} else {
exceptions.add(trying.getException());
}
});
}
/**
* @param <P> value type of Try
* @param <E> exception type of Try
* @return a collector that collects the values of all executed functions up until the first caught exception
*/
public static <P, E extends Exception> Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<E>> collectExceptions() {
return collectList((list, trying) -> {
if(trying.failure()) {
list.add(trying);
}
}, Try::getException);
}
private static <P, E extends Exception> Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<P>> collectList(BiConsumer<ArrayList<Try<P, E>>, Try<P, E>> accumulator) {
return collectList(accumulator, Try::getValue);
}
private static <P, E extends Exception, R> Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<R>> collectList(BiConsumer<ArrayList<Try<P, E>>, Try<P, E>> accumulator, Function<Try<P, E>, R> finisher) {
return new Collector<Try<P, E>, ArrayList<Try<P, E>>, Stream<R>>() {
@Override
public Supplier<ArrayList<Try<P, E>>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<ArrayList<Try<P, E>>, Try<P, E>> accumulator() {
return accumulator;
}
@Override
public BinaryOperator<ArrayList<Try<P, E>>> combiner() {
return (first, second) -> {
first.addAll(second);
return first;
};
}
@Override
public Function<ArrayList<Try<P, E>>, Stream<R>> finisher() {
return list -> list.stream().map(finisher);
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
};
}
/**
*
*/
private static class TryCollectorException extends RuntimeException {
public TryCollectorException(Throwable cause) {
super(cause);
}
}
}
| 34.534091 | 204 | 0.561862 |
fef28b7f9bb0e0f7b8fb54cadd19041895787b0b | 9,963 | package com.bizzan.ui.wallet;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.gyf.barlibrary.ImmersionBar;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import com.bizzan.R;
import com.bizzan.app.Injection;
import com.bizzan.base.BaseActivity;
import com.bizzan.entity.WalletConstract;
import com.bizzan.entity.Wallet_Coin;
import com.bizzan.utils.WonderfulCodeUtils;
import com.bizzan.utils.WonderfulToastUtils;
//划转
public class OverturnActivity extends BaseActivity implements OverturnContract.View {
@BindView(R.id.ibBack)
ImageButton ibBack;
@BindView(R.id.view_back)
View viewBack;
@BindView(R.id.ibDetail)
TextView ibDetail;
@BindView(R.id.llTitle)
LinearLayout llTitle;
@BindView(R.id.tvc)
TextView tvc;
@BindView(R.id.tvd)
TextView tvd;
@BindView(R.id.view_line)
View viewLine;
@BindView(R.id.ll_switch)
LinearLayout llSwitch;
@BindView(R.id.tv_coins)
TextView tvCoins;
@BindView(R.id.iv_arrow)
ImageView ivArrow;
@BindView(R.id.tv_all)
TextView tvAll;
@BindView(R.id.tv_coin)
TextView tvCoin;
@BindView(R.id.edit_number)
EditText editNumber;
@BindView(R.id.tv_top1)
TextView tvTop1;
@BindView(R.id.tv_top2)
TextView tvTop2;
@BindView(R.id.tv_bottom1)
TextView tvBottom1;
@BindView(R.id.tv_bottom2)
TextView tvBottom2;
@BindView(R.id.iv_top)
ImageView ivTop;
@BindView(R.id.iv_bottom)
ImageView ivBottom;
@BindView(R.id.rl_top)
RelativeLayout rlTop;
@BindView(R.id.rl_boottom)
RelativeLayout rlBoottom;
@BindView(R.id.rl_coin)
RelativeLayout rlCoin;
@BindView(R.id.tv_coin_account)
TextView tvCoinAccount;
private int switch_type = 1;//表示币币在上面 2表示币币现在在下面
private int coin_type = 0;//获取现在显示的币种是列表的第几个
private OverturnContract.Presenter presenter;
private List<WalletConstract> constracts = new ArrayList<>();
private Wallet_Coin coin;
public static void actionStart(Context context) {
Intent intent = new Intent(context, OverturnActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
protected int getActivityLayoutId() {
return R.layout.activity_overturn;
}
@Override
protected void initViews(Bundle savedInstanceState) {
new OverturnPresenter(Injection.provideTasksRepository(getApplicationContext()), this);
rlTop.setEnabled(false);
tvTop2.setText(getResources().getText(R.string.tv_balance) + ": 0.0000 USDT");
tvBottom2.setText(getResources().getText(R.string.tv_balance) + ": 0.0000 USDT");
tvCoinAccount.setText(getResources().getText(R.string.constract)+""+getResources().getText(R.string.contract)+""+getResources().getText(R.string.tv_currency));
}
@Override
protected void obtainData() {
}
@Override
protected void fillWidget() {
}
@Override
protected void loadData() {
presenter.myWalletUsdt(getToken());
presenter.myWalletList(getToken());
}
@Override
public void setPresenter(OverturnContract.Presenter presenter) {
this.presenter = presenter;
}
@Override
protected void initImmersionBar() {
super.initImmersionBar();
if (!isSetTitle) {
ImmersionBar.setTitleBar(this, llTitle);
isSetTitle = true;
}
}
//点击事件
@OnClick({R.id.ibBack, R.id.ll_switch, R.id.rl_top, R.id.rl_boottom, R.id.tv_all, R.id.rl_coin, R.id.tvOverturn})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.ibBack:
finish();
break;
case R.id.ll_switch://上下切换账户
if (switch_type == 1) {//币币切换到下面
tvTop1.setText(WonderfulToastUtils.getString(this, R.string.tv_constract_account));
tvBottom1.setText(WonderfulToastUtils.getString(this, R.string.tv_coins) + "(USDT)");
ivTop.setVisibility(View.VISIBLE);
ivBottom.setVisibility(View.GONE);
rlTop.setEnabled(true);
rlBoottom.setEnabled(false);
editNumber.setText("");
switch_type = 2;
getCoin(coin);
getConstract(constracts);
} else if (switch_type == 2) {//币币切换到上面
tvTop1.setText(WonderfulToastUtils.getString(this, R.string.tv_coins) + "(USDT)");
tvBottom1.setText(WonderfulToastUtils.getString(this, R.string.tv_constract_account));
ivTop.setVisibility(View.GONE);
ivBottom.setVisibility(View.VISIBLE);
rlTop.setEnabled(false);
rlBoottom.setEnabled(true);
editNumber.setText("");
switch_type = 1;
getCoin(coin);
getConstract(constracts);
}
break;
case R.id.rl_top:
SelectAccountActivity.actionStart(this, constracts);
break;
case R.id.rl_boottom:
SelectAccountActivity.actionStart(this, constracts);
break;
case R.id.tv_all:
//点击全部
if (switch_type == 1) {
editNumber.setText(coin.getBalance() + "");
} else if (switch_type == 2) {
for (int i = 0; i < constracts.size(); i++) {
if (constracts.get(i).getContractCoin().getCoinSymbol().equals(tvCoins.getText().toString().trim())) {
editNumber.setText(constracts.get(i).getUsdtBalance() + "");
return;
}
}
}
break;
case R.id.rl_coin:
SelectCoinActivity.actionStart(this, constracts);
break;
case R.id.tvOverturn:
String trim = editNumber.getText().toString().trim();
if (!trim.equals("")) {
if (switch_type == 1) {
presenter.RequesTrans(getToken(), "USDT", "0", "1", coin.getId() + "", constracts.get(coin_type).getId() + "", trim);
} else if (switch_type == 2) {
presenter.RequesTrans(getToken(), "USDT", "1", "0", constracts.get(coin_type).getId() + "", coin.getId() + "", trim);
}
} else {
WonderfulToastUtils.showToast(getResources().getText(R.string.tv_input_overturn_number) + "");
}
break;
}
}
// unit:USDT
// from:0
// to:1
// fromWalletId:9113
// toWalletId:504
// amount:1
@Override
public void myWalletUsdtSuccess(Wallet_Coin obj) {
coin = obj;
getCoin(coin);
}
@Override
public void myWalletListSuccess(List<WalletConstract> obj) {
constracts.addAll(obj);
tvCoins.setText(constracts.get(0).getContractCoin().getCoinSymbol());
getConstract(constracts);
}
@Override
public void myTransSuccess(String obj) {
Toast.makeText(this, "" + obj, Toast.LENGTH_SHORT).show();
editNumber.setText("");
presenter.myWalletUsdt(getToken());
presenter.myWalletList(getToken());
}
@Override
public void myWalletFail(Integer code, String toastMessage) {
WonderfulCodeUtils.checkedErrorCode(this, code, toastMessage);
}
//刷新币币资产
private void getCoin(Wallet_Coin coin) {
if (switch_type == 1) {
tvTop2.setText(getResources().getText(R.string.tv_balance) + ": " + ProcessPrice(coin.getBalance()) + " USDT");
} else if (switch_type == 2) {
tvBottom2.setText(getResources().getText(R.string.tv_balance) + ": " + ProcessPrice(coin.getBalance()) + " USDT");
}
}
//刷新其他账户资产
private void getConstract(List<WalletConstract> constracts) {
for (int i = 0; i < constracts.size(); i++) {
if (constracts.get(i).getContractCoin().getCoinSymbol().equals(tvCoins.getText().toString().trim())) {
if (switch_type == 1) {
tvBottom2.setText(getResources().getText(R.string.tv_balance) + ": " + ProcessPrice(constracts.get(i).getUsdtBalance()) + " USDT");
coin_type = i;
} else if (switch_type == 2) {
tvTop2.setText(getResources().getText(R.string.tv_balance) + ": " + ProcessPrice(constracts.get(i).getUsdtBalance()) + " USDT");
coin_type = i;
}
}
}
}
private String ProcessPrice(double Price) {
BigDecimal bigDecimal = new BigDecimal(Price);
return bigDecimal.setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
/**
* 传过来的币种
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void WalletMessage(WalletMessage coin) {
tvCoins.setText(coin.getCoin());
getConstract(constracts);
}
} | 34.003413 | 167 | 0.604336 |
1af9137b26047e41305316483065cf82d3760256 | 2,244 | package questions.leetcode844;
public class BackspaceStringCompare {
public boolean backspaceCompare(String S, String T) {
int ptr_s = S.length()-1;
int ptr_t = T.length()-1;
int count_s = 0;
int count_t = 0;
while (ptr_s >= 0 && ptr_t >= 0) {
if (S.charAt(ptr_s) == '#') {
count_s++;
ptr_s--;
while (ptr_s >= 0 && (count_s > 0 || S.charAt(ptr_s) == '#')) {
if (S.charAt(ptr_s) == '#')
count_s++;
else
count_s--;
ptr_s--;
}
}
if (T.charAt(ptr_t) == '#') {
count_t++;
ptr_t--;
while (ptr_t >= 0 && (count_t > 0 || T.charAt(ptr_t) == '#')) {
if (T.charAt(ptr_t) == '#')
count_t++;
else
count_t--;
ptr_t--;
}
}
if (ptr_s < 0 || ptr_t < 0)
break;
if (S.charAt(ptr_s) != T.charAt(ptr_t))
return false;
ptr_s--;
ptr_t--;
}
while (ptr_s >= 0) {
if (S.charAt(ptr_s) == '#') {
count_s++;
ptr_s--;
while (ptr_s >= 0 && (count_s > 0 || S.charAt(ptr_s) == '#')) {
if (S.charAt(ptr_s) == '#')
count_s++;
else
count_s--;
ptr_s--;
}
}
else
return false;
ptr_s--;
}
while (ptr_t >= 0) {
if (T.charAt(ptr_t) == '#') {
count_t++;
ptr_t--;
while (ptr_t >= 0 && (count_t > 0 || T.charAt(ptr_t) == '#')) {
if (T.charAt(ptr_t) == '#')
count_t++;
else
count_t--;
ptr_t--;
}
}
else
return false;
ptr_t--;
}
return true;
}
}
| 29.142857 | 79 | 0.306595 |
64e35811e03d7742a763a6fc596926f7b7b2443d | 1,206 | package main.java.de.baltic_online.mediknight.widgets;
import java.awt.Component;
import java.awt.Rectangle;
import java.util.EventObject;
public class JTable extends javax.swing.JTable {
private static final long serialVersionUID = 1L;
@Override
public boolean editCellAt( final int row, final int column, final EventObject e ) {
final boolean canEdit = super.editCellAt( row, column, e );
if( canEdit ) {
final Component c = getEditorComponent();
if( c instanceof javax.swing.JTextField ) {
((javax.swing.JTextField) c).select( 0, 9999 );
c.repaint();
}
}
return canEdit;
}
@Override
public void changeSelection( int row, int column, boolean toggle, boolean extend)
{
super.changeSelection(row, column, toggle, extend);
if (editCellAt(row, column))
{
Component editor = getEditorComponent();
editor.requestFocusInWindow();
}
}
public Rectangle getCellBounds( int i, double height ) {
JTable jt= new JTable();
jt.getX();
final Rectangle cellBounds= new Rectangle(jt.getX(), jt.getY(), jt.getWidth(), jt.getHeight());
return cellBounds;
}
} | 26.217391 | 97 | 0.6534 |
3c5f644e875fa6fbea0d0fb54991e7a5e9dfc5a7 | 1,123 | package com.atguigu.struts2.validation.app;
import com.opensymphony.xwork2.ActionSupport;
public class TestValidationAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer age;
private String password;
private String password2;
private Integer count;
private String idCard;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
@Override
public String execute() throws Exception {
System.out.println("age: " + age);
return SUCCESS;
}
}
| 17.015152 | 58 | 0.670525 |
2e9559f332b7ec6d5a3eb6556c43005e2a213952 | 1,021 | package com.globant.bootcamp.buildings;
import com.globant.bootcamp.abstracts.Animal;
import java.util.ArrayList;
public abstract class AnimalManager extends AnimalBox{
private ArrayList<Animal> allowedAnimals = new ArrayList<Animal>();
public ArrayList<Animal> getAllowedAnimals() {
return allowedAnimals;
}
public void setAllowedAnimals(ArrayList<Animal> allowedAnimals) {
this.allowedAnimals = allowedAnimals;
}
public boolean isAllowed(Animal animal){
return this.getAllowedAnimals().contains(animal);
}
@Override
public void addAnimal(Animal animal){
if(isAddable(animal)){
this.getAnimals().add(animal);
}
}
public void addAllowedAnimal(Animal animal){
this.allowedAnimals.add(animal);
}
public void removeAllowedAnimal(Animal animal){
this.getAllowedAnimals().remove(animal);
}
public boolean isAddable(Animal animal){
return isNotFull() && isAllowed(animal);
}
}
| 24.902439 | 71 | 0.686582 |
8b5d767f7e55409a8eb55cf2c253f7a1eec40587 | 1,068 | package com.viglia.android.pdfaudiorecorderapp.utility;
import java.io.Serializable;
/**
*This class represents a portion of the presentation.
*It states a page index and the time this page was first selected in the given portion.
*
* Ex. Frame1:(pag.1 - seconds 0) --> Frame2:(page.2 - seconds 4) --> Frame3: (pag.1 - seconds 10)
*/
public class SlideRecord implements Serializable {
private static final long serialVersionUID = 1L;
private int slide;
private long seconds;
/**
*
* @param slide the index of the pdf page
* @param seconds the time (expressed in seconds) when this page has been selected
*/
public SlideRecord(int slide, long seconds){
this.slide = slide;
this.seconds = seconds;
}
public SlideRecord(){}
public void setSlide(int slide){
this.slide = slide;
}
public void setSeconds(int seconds){
this.seconds = seconds;
}
public int getSlide(){
return slide;
}
public long getSeconds(){
return seconds;
}
}
| 23.733333 | 100 | 0.645131 |
a1b60d9a1c1ac860362af2e6eaaeb95367cc4e04 | 2,266 | /*-
* ==========================LICENSE_START=================================
* PolyGenesis Platform
* ========================================================================
* Copyright (C) 2015 - 2019 Christos Tsakostas, OREGOR 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.
* ===========================LICENSE_END==================================
*/
package com.invoiceful.genesis.contexts.invoicing;
import io.polygenesis.abstraction.data.Data;
import io.polygenesis.abstraction.data.dsl.DataBuilder;
import io.polygenesis.abstraction.thing.Thing;
import io.polygenesis.abstraction.thing.dsl.PurposeFunctionBuilder;
import io.polygenesis.abstraction.thing.dsl.ThingBuilder;
import io.polygenesis.commons.valueobjects.PackageName;
import java.util.Set;
/** @author Christos Tsakostas */
public class DocumentGroup {
public static Thing create(Thing document, PackageName rootPackageName) {
Thing documentGroup =
ThingBuilder.endToEndChildWithIdentity("documentGroup", document)
.createThing(rootPackageName);
documentGroup.addFunctions(
PurposeFunctionBuilder.forThing(documentGroup, rootPackageName.getText())
.withCrudFunction(data())
.build());
return documentGroup;
}
// ===============================================================================================
// DATA
// ===============================================================================================
private static Set<Data> data() {
return DataBuilder.create()
.withTextProperty("description")
.build()
.withBooleanProperty("done")
.build()
.build();
}
}
| 37.766667 | 100 | 0.578111 |
5e5ebf2d7c0631407cc5abb461b8b4c7938eec52 | 3,819 | package com.example.socialMedia.Services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.socialMedia.controller.UserProfileController;
import com.example.socialMedia.entity.UserFollower;
import com.example.socialMedia.exception.CustomException;
import com.example.socialMedia.repository.IUserProfileRepository;
import com.example.socialMedia.utility.StaticSetup;
@Service
public class UserProfileImpl implements IUserProfileService {
Logger logger = LoggerFactory.getLogger(UserProfileController.class);
public static String className = "UserProfileImpl";
@Autowired
IUserProfileRepository repo;
/**
* Adding the valid follower to a valid user
*/
@Override
public UserFollower addFollower(UserFollower userFollower) throws CustomException, Exception {
final String methodName = "addFollower";
//First check if the user is present in UserProfile Table
boolean isUserPresent = StaticSetup.isUserPresent(userFollower.getUserId());
logger.info("USER ID: " + userFollower.getUserId() + " is valid user " + " " +
methodName + " " + className);
boolean isFollowerPresent = StaticSetup.isUserPresent(userFollower.getFollowerId());
logger.info("USER ID: " + userFollower.getUserId() + " is valid user " + " " +
methodName + " " + className);
if(isUserPresent && isFollowerPresent) {
//Check if Already mapping is present
if(!isUserFollowerMappingPresent(userFollower.getUserId(), userFollower.getFollowerId())) {
logger.info("User and follower mapping not present, we can add " + " " +
methodName + " " + className);
//Mapping not present. We can do the mapping
UserFollower updateUser = repo.save(userFollower);
if(null != updateUser) {
return updateUser;
}
} else {
throw new CustomException("User is already following");
}
} else {
throw new CustomException("User or Follower not enrolled");
}
return null;
}
private boolean isUserFollowerMappingPresent(int userId, int followerId) {
if(!StaticSetup.userFollowerList.isEmpty()) {
return StaticSetup.userFollowerList.stream().anyMatch(p -> p.getUserId()==userId && p.getFollowerId()== followerId);
} else {
return false;
}
}
/**
* Removing the follower from valid user if the mapping is already present
*/
@Override
public UserFollower removeFollower(UserFollower userFollower) throws CustomException, Exception {
final String methodName = "removeFollower";
// First check if the user is present in UserProfile Table
boolean isUserPresent = StaticSetup.isUserPresent(userFollower.getUserId());
logger.info("USER ID: " + userFollower.getUserId() + " is valid user " + " " +
methodName + " " + className);
boolean isFollowerPresent = StaticSetup.isUserPresent(userFollower.getFollowerId());
logger.info("USER ID: " + userFollower.getUserId() + " is valid user " + " " +
methodName + " " + className);
if (isUserPresent && isFollowerPresent) {
// Check if Already mapping is present
if (isUserFollowerMappingPresent(userFollower.getUserId(), userFollower.getFollowerId())) {
logger.info("User and follower mapping present, we can remove " + " " +
methodName + " " + className);
// Mapping not present. We can do the mapping
UserFollower updateUser = repo.delete(userFollower);
if (null != updateUser) {
return updateUser;
}
} else {
throw new CustomException("User is not Following, so cannot be removed");
}
} else {
throw new CustomException("User or Follower not enrolled");
}
return null;
}
}
| 36.028302 | 121 | 0.703849 |
885fabe7db7e560552c164f72a7c9da611fd1f75 | 1,332 | package com.icegreen.greenmail.server;
import com.icegreen.greenmail.junit.GreenMailRule;
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.ServerSetup;
import org.junit.Rule;
import org.junit.Test;
import javax.mail.internet.MimeMessage;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
public class AllocateAvailablePortTest {
private static final int AnyFreePort = 0;
private final ServerSetup allocateAnyFreePortForAnSmtpServer = smtpServerAtPort(AnyFreePort);
@Rule
public final GreenMailRule greenMail = new GreenMailRule(allocateAnyFreePortForAnSmtpServer);
@Test
public void returnTheActuallyAllocatedPort() {
assertThat(greenMail.getSmtp().getPort(), not(0));
}
@Test
public void ensureThatMailCanActuallyBeSentToTheAllocatedPort() {
GreenMailUtil.sendTextEmail("to@localhost.com", "from@localhost.com", "subject", "body",
smtpServerAtPort(greenMail.getSmtp().getPort()));
MimeMessage[] emails = greenMail.getReceivedMessages();
assertThat(emails.length, is(1));
}
private ServerSetup smtpServerAtPort(int port) {
return new ServerSetup(port, null, ServerSetup.PROTOCOL_SMTP);
}
} | 32.487805 | 97 | 0.754505 |
0147c0063272d014b575d7137857ef3782523cab | 10,187 | package ru.alklimenko.calculator;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.Set;
import java.util.Stack;
/**
* A class for representing an expression in a form that is convenient for processing
*/
public class Expression extends Stack<Term> {
private boolean rpn = false;
/** Is expression is Reverse Polish notation */
public boolean isRPN() {
return rpn;
}
private void reverse() {
Collections.reverse(this);
}
/**
* Print expression to console
*/
public void print() {
System.out.print(toString());
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int idx = this.size() - 1; idx >= 0; --idx) {
sb.append(get(idx).toString());
}
return sb.toString().trim();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* We find the maximum substring in the line starting with index, which is the number
*
* @param str String
* @param index Initial index
* @return Returns the first character index after the number, so that the number is str.substring (index, returnIndex) or -1 if at the index is not a number
*/
static int numberStarts(String str, int index) {
int index2 = index + 1;
if (str.charAt(index) == '-' || str.charAt(index) == '+') { //The number can start with a sign
index2++;
}
while (index2 < str.length() && isDouble(str.substring(index, index2))) {
index2++;
if (index2 < str.length() && (str.charAt(index2) == 'E' || str.charAt(index2) == 'e')) { //The number in the exponential notation
index2++;
if (index2 < str.length() && (str.charAt(index2) == '-' || str.charAt(index2) == '+')) { //There is an exponential sign
index2++;
}
index2++;
}
}
if (index2 == str.length() && isDouble(str.substring(index, index2))) { // It if from a cycle left on a condition index2 == str.length ()
return index2;
}
index2--; // And this, if with a new index2 has already received not a number
return index2 == index ? -1 : index2;
}
/**
* We find the index in the string, that the ending a operator or -1 if there is no operator there
* @param str String
* @param index From what position do we look for the operator
* @return index
*/
static int operatorStarts(String str, int index) {
Set<String> operators = Operator.getOperators();
for(String operator : operators) {
if (str.startsWith(operator, index)) {
return index + operator.length();
}
}
return -1;
}
/**
* Parse the string in arithmetic record to Expression.
*
* @param str строка вида 5 + 7 * (3 - 1)
*/
private Expression parse(String str, int index) {
int index2;
do {
// First number must be number or open bracket
if(isEmpty()) {
if ((index2 = numberStarts(str, index)) > -1) {
Number number = new Number(Double.parseDouble(str.substring(index, index2)));
push(number);
} else if (str.charAt(index) == '(') {
push(Operator.get("("));
index2 = index + 1;
} else {
throw new InvalidExpressionException("Invalid expression! First term must be number or open bracket!");
}
} else {
if (peek().isType(Term.NUMBER)) { // Number --------------------------->
// После числа может быть только оператор
if ((index2 = operatorStarts(str, index)) > -1) { // Оператор
Operator operation = Operator.get(str.substring(index, index2));
push(operation);
} else {
throw new InvalidExpressionException("Invalid expression! After number mast be only operator!");
}
} else { // Operator ------------------------------>
if (((Operator)peek()).isCloseBracket()) { // )
// After close bracket mast be only operator!
if ((index2 = operatorStarts(str, index)) > -1) { // Оператор
Operator operation = Operator.get(str.substring(index, index2));
push(operation);
} else {
throw new InvalidExpressionException("Invalid expression! After close bracket mast be only operator!");
}
} else if (((Operator)peek()).isOpenBracket()) { // (
// After open bracket mast be number or another open bracket!
if ((index2 = numberStarts(str, index)) > -1) {
Number number = new Number(Double.parseDouble(str.substring(index, index2)));
push(number);
} else if (str.charAt(index) == '(') {
push(Operator.get("("));
index2 = index + 1;
} else {
throw new InvalidExpressionException("Invalid expression! After open bracket mast be number or another open bracket!");
}
} else if ((index2 = numberStarts(str, index)) > -1) { // After operator (not bracket) goes number
Number number = new Number(Double.parseDouble(str.substring(index, index2)));
push(number);
} else if (str.charAt(index) == '(') { // or open bracket
push(Operator.get("("));
index2 = index + 1;
} else {
throw new InvalidExpressionException("Invalid expression! Unable parse expression!");
}
}
}
index = index2;
} while (index2 != str.length());
reverse();
return this;
}
/**
* Parse string in arithmetic notation into Expression.
*
* @param str строка вида 5 + 7 * (3 - 1)
*/
public Expression parse(String str) {
clear();
rpn = false;
return parse(str.replaceAll("[ \\t]", ""), 0);
}
/**
* We transform the expression from an arithmetic notation into a reverse Polish notation
* @return this
*/
public Expression toOPN() {
if (rpn) { // Already in the RPN
return this;
}
rpn = true;
Expression p = new Expression(); // Выражение в обратной польской нотации (ОПН)
OperatorStack os = new OperatorStack(); // Стек операций
do {
Term t = pop();
if (t instanceof Number) { // Это число - добавляем в выражение ОПН
p.push(t);
} else { // Это оператор
Operator o = (Operator)t;
if (o.isCloseBracket()) { // Закрывающая скобка - берём все операции из стека до
do { // открывающей скобки и добавляем выражение ОПН
if (os.isEmpty()) {
throw new InvalidExpressionException("Invalid expression! Close bracket not found!");
}
Operator so = os.pop();
if(so.isOpenBracket()) {
break;
}
p.push(so);
} while(true);
} else {
if (!o.isOpenBracket()) {
while (!os.isEmpty() && os.peek().getPriority() >= o.getPriority()) { // Операции большего или равного приоритета из стека
p.push(os.pop()); // операций добавляем в выражение ОПН
}
}
os.push(o); // Добавляем операцию в стек операций
}
}
} while (!empty());
while(!os.isEmpty()) {
p.push(os.pop());
}
//p.reverse();
while (!p.isEmpty()) {
push(p.pop());
}
return this;
}
/**
* Calculate expression in RPN.
*/
public double calculate() {
if (!rpn) {
toOPN();
}
try {
Stack<Double> stack = new Stack<>();
Stack<Term> tmp = new Stack<>();
for (int idx = 0; idx < size(); ++idx) {
tmp.push(get(idx));
}
while (!tmp.isEmpty()) {
Term t = tmp.pop();
if (t instanceof Number) {
stack.push(((Number) t).getValue());
} else {
Operator o = (Operator) t;
double b = stack.pop();
double a = stack.pop();
double c = o.doIt(a, b);
stack.push(c);
}
}
if (stack.size() != 1) {
throw new InvalidExpressionException("Invalid expression! Only result must left on the stack!");
}
return stack.pop();
} catch (EmptyStackException e) {
throw new InvalidExpressionException("Invalid expression! Unable calculate expression! \r\n" + e.getMessage());
}
}
/**
* Вычисление арифметического выражения
* @param str Выражение вида 5 * (5 - 2) ...
* @return result
*/
public double calculate(String str) {
parse(str);
return calculate();
}
}
| 38.441509 | 161 | 0.481398 |
d0b7f69fa1cfafd40abcb6eaa6315ed94c9b7dce | 3,065 | package uk.gov.hmcts.ccd.endpoint.std;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import uk.gov.hmcts.ccd.MockUtils;
import uk.gov.hmcts.ccd.WireMockBaseTest;
import uk.gov.hmcts.ccd.auditlog.AuditRepository;
import uk.gov.hmcts.ccd.domain.model.definition.CaseDetails;
import uk.gov.hmcts.ccd.domain.model.definition.Document;
import uk.gov.hmcts.ccd.domain.service.common.TestBuildersUtil.CaseDetailsBuilder;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class CallbackEndpointIT extends WireMockBaseTest {
private static final String JURISDICTION = "PROBATE";
private static final String CASE_TYPE = "TestAddressBookCase";
@Inject
private WebApplicationContext wac;
private MockMvc mockMvc;
@SpyBean
private AuditRepository auditRepository;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void getPrintableDocumentsShouldLogAudit() throws Exception {
CaseDetails caseDetails = CaseDetailsBuilder.newCaseDetails().withReference(1535450291607660L).build();
String url = "/callback/jurisdictions/" + JURISDICTION + "/case-types/" + CASE_TYPE + "/documents";
MvcResult result = mockMvc.perform(post(url)
.contentType(JSON_CONTENT_TYPE)
.content(mapper.writeValueAsBytes(caseDetails)))
.andExpect(status().is(200))
.andReturn();
String responseAsString = result.getResponse().getContentAsString();
List<Document> documents = Arrays.asList(mapper.readValue(responseAsString, Document[].class));
assertThat(documents, hasSize(1));
assertThat(documents, hasItem(hasProperty("url", equalTo("http://localhost:3453/print/jurisdictions/PROBATE/case-types/TestAddressBookCase/cases/1535450291607660"))));
assertThat(documents, hasItem(hasProperty("name", equalTo("CCD Print"))));
assertThat(documents, hasItem(hasProperty("type", equalTo("CCD Print Type"))));
assertThat(documents, hasItem(hasProperty("description", equalTo("Printing for CCD"))));
}
}
| 42.569444 | 175 | 0.76248 |
9d0896fbba8941b5f957b1c43d2ef6eb6cbaee4b | 612 | package io.renren.api.rockmobi.payment.fortumo.service;
import io.renren.api.rockmobi.payment.fortumo.model.callback.PaymentCompleteCallBackRequet;
import io.renren.entity.MmProductOrderEntity;
public interface FortumoOrderService {
/**
* fortumo订单接口
* @param paymentCompleteCallBackRequet
*/
String createOrder(PaymentCompleteCallBackRequet paymentCompleteCallBackRequet);
/**
* 根据订单编号code更新订单状态
* @param productOrderEntity
* @return
*/
Integer updateByProductOrderCode(MmProductOrderEntity productOrderEntity,MmProductOrderEntity upProductOrderEntity);
}
| 29.142857 | 120 | 0.777778 |
fad0b00fde65a616643ce299eb17c474e0ba9854 | 1,431 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.view.accessibility;
import android.view.accessibility.AccessibilityEvent;
// Referenced classes of package android.support.v4.view.accessibility:
// AccessibilityEventCompat
static class AccessibilityEventCompat$AccessibilityEventCompatBaseImpl
{
public int getAction(AccessibilityEvent accessibilityevent)
{
return 0;
// 0 0:iconst_0
// 1 1:ireturn
}
public int getContentChangeTypes(AccessibilityEvent accessibilityevent)
{
return 0;
// 0 0:iconst_0
// 1 1:ireturn
}
public int getMovementGranularity(AccessibilityEvent accessibilityevent)
{
return 0;
// 0 0:iconst_0
// 1 1:ireturn
}
public void setAction(AccessibilityEvent accessibilityevent, int i)
{
// 0 0:return
}
public void setContentChangeTypes(AccessibilityEvent accessibilityevent, int i)
{
// 0 0:return
}
public void setMovementGranularity(AccessibilityEvent accessibilityevent, int i)
{
// 0 0:return
}
AccessibilityEventCompat$AccessibilityEventCompatBaseImpl()
{
// 0 0:aload_0
// 1 1:invokespecial #11 <Method void Object()>
// 2 4:return
}
}
| 24.672414 | 81 | 0.668763 |
55013e75c5904989bb191054930ac2341319d7b3 | 1,961 | /*
* CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE CONDITION THAT YOU
* ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT. PLEASE READ THE TERMS AND CONDITIONS OF THIS
* AGREEMENT CAREFULLY. BY DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF
* THE AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE" BUTTON AT THE
* BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency API ("Specification") Copyright
* (c) 2012-2013, Credit Suisse All rights reserved.
*/
package javax.money.format;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Tests for {@link javax.money.format.MonetaryParseException}.
*/
public class MonetaryParseExceptionTest{
@Test
public void testGetErrorIndex() throws Exception{
MonetaryParseException e = new MonetaryParseException("testInput", 5);
Assert.assertEquals(e.getErrorIndex(), 5);
e = new MonetaryParseException("message", "testInput", 5);
Assert.assertEquals(e.getErrorIndex(), 5);
Assert.assertEquals(e.getMessage(),"message");
}
@Test
public void testGetInput() throws Exception{
MonetaryParseException e = new MonetaryParseException("testInput", 5);
Assert.assertEquals(e.getInput(),"testInput");
e = new MonetaryParseException("message", "testInput", 5);
Assert.assertEquals(e.getInput(),"testInput");
Assert.assertEquals(e.getMessage(),"message");
}
@Test(expectedExceptions=IllegalArgumentException.class)
public void testCreateIllegalInput(){
//noinspection ThrowableInstanceNeverThrown
new MonetaryParseException("testInput", 500);
}
@Test(expectedExceptions=IllegalArgumentException.class)
public void testCreateIllegalInputWithMessage(){
//noinspection ThrowableInstanceNeverThrown
new MonetaryParseException("message", "testInput", 500);
}
}
| 40.854167 | 100 | 0.72463 |
1b72779ea4906d503ffb8d2210fe76255b3cd5bb | 1,380 | package cn.yiiguxing.plugin.translate.ui.form;
import cn.yiiguxing.plugin.translate.trans.Lang;
import cn.yiiguxing.plugin.translate.ui.TTSButton;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.components.labels.LinkLabel;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class InstantTranslationDialogForm extends DialogWrapper {
private JPanel mRoot;
protected ComboBox<Lang> sourceLangComboBox;
protected ComboBox<Lang> targetLangComboBox;
protected JButton swapButton;
protected JButton translateButton;
protected JTextArea inputTextArea;
protected JTextArea translationTextArea;
protected TTSButton inputTTSButton;
protected TTSButton translationTTSButton;
protected LinkLabel<Void> clearButton;
protected LinkLabel<Void> copyButton;
protected JScrollPane inputScrollPane;
protected JScrollPane translationScrollPane;
protected JPanel translationToolBar;
protected JPanel inputToolBar;
protected JPanel inputContentPanel;
protected JPanel translationContentPanel;
protected InstantTranslationDialogForm(@Nullable Project project) {
super(project);
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return mRoot;
}
}
| 32.857143 | 71 | 0.786957 |
f3f49e7e1ef8398362e2b70e8fc8ff3605a60e41 | 2,717 | package kr.co.vlink.Vlink.contoller;
import kr.co.vlink.Vlink.domain.Partners;
import kr.co.vlink.Vlink.dto.PartnersDTO;
import kr.co.vlink.Vlink.dto.ResultDTO;
import kr.co.vlink.Vlink.service.PartnersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
@RequestMapping("/admin")
public class AdminRestController {
@Autowired
private PartnersService partnersService;
@Value("${vlink.admin.id}")
private String adminId;
@Value("${vlink.admin.password}")
private String adminPassword;
@PostMapping("/login")
public boolean adminLogin(@RequestParam String id, @RequestParam String password, HttpSession session) {
if(id.equals(adminId) && password.equals(adminPassword)) {
session.setAttribute("admin", true);
return true;
}
return false;
}
@PostMapping("/allow-partners")
public boolean allowPartners(@RequestBody PartnersDTO partnersDTO, HttpSession session) throws MessagingException {
Partners partners = null;
if((Boolean) session.getAttribute("admin")) {
partners = partnersService.allowPartners(partnersDTO.getId());
}
return (partners != null) ? true : false;
}
@GetMapping("/all-partners")
public ResultDTO findAllPartners(HttpSession session) {
ResultDTO resultDTO = new ResultDTO();
List<Partners> partnersList = partnersService.findPartnersList();
if(partnersList != null) {
// if(partnersList != null && (Boolean) session.getAttribute("admin")) {
resultDTO.setCode(200);
resultDTO.setMessage("success");
resultDTO.setData(partnersList);
} else {
resultDTO.setCode(500);
resultDTO.setMessage("not found");
resultDTO.setData(null);
}
return resultDTO;
}
@GetMapping("/waiting-partners")
public ResultDTO findNotAllowedPartners(HttpSession session) {
ResultDTO resultDTO = new ResultDTO();
List<Partners> partnersList = partnersService.findPartnersListByAuthState();
if(partnersList != null && (Boolean) session.getAttribute("admin")) {
resultDTO.setCode(200);
resultDTO.setMessage("success");
resultDTO.setData(partnersList);
} else {
resultDTO.setCode(500);
resultDTO.setMessage("not found");
resultDTO.setData(null);
}
return resultDTO;
}
}
| 34.392405 | 119 | 0.66728 |
08a357480425127435c9cee4884b2b9c88535edf | 2,876 | /**
* AET
*
* Copyright (C) 2013 Cognifide Limited
*
* 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.cognifide.aet.sanity.functional;
import static org.junit.Assert.assertEquals;
import com.cognifide.aet.sanity.functional.po.ReportHomePage;
import com.cognifide.qa.bb.junit.Modules;
import com.cognifide.qa.bb.junit.TestRunner;
import com.google.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(TestRunner.class)
@Modules(GuiceModule.class)
public class HomePageTilesTest {
private static final int TESTS = 157;
private static final int EXPECTED_TESTS_SUCCESS = 93;
private static final int EXPECTED_TESTS_CONDITIONALLY_PASSED = 11;
private static final int EXPECTED_TESTS_WARN = 5;
private static final int EXPECTED_TESTS_FAIL = 59;
@Inject
private ReportHomePage page;
@Before
public void openReportPage() {
page.openAndWaitForTiles();
}
@Test
public void checkNumberOfTiles() {
int tilesAll = page.findTiles().size();
assertEquals("should render all tiles for tests", TESTS, tilesAll);
}
@Test
public void checkNumberOfSuccessTiles() {
String cssClassToSearch = TestStatus.SUCCESS.getCssClass();
int tiles = page.findTiles(cssClassToSearch).size();
assertEquals("number of tests tiles with SUCCESS status is incorrect",
EXPECTED_TESTS_SUCCESS - EXPECTED_TESTS_CONDITIONALLY_PASSED,
tiles);
}
@Test
public void checkNumberOfConditionallyPassedTiles() {
String cssClassToSearch = TestStatus.CONDITIONALLY_PASSED.getCssClass();
int tiles = page.findTiles(cssClassToSearch).size();
assertEquals("number of tests tiles with CONDITIONALLY PASSED status is incorrect",
EXPECTED_TESTS_CONDITIONALLY_PASSED,
tiles);
}
@Test
public void checkNumberOfWarningTiles() {
String cssClassToSearch = TestStatus.WARN.getCssClass();
int tiles = page.findTiles(cssClassToSearch).size();
assertEquals("number of tests tiles with WARNING status is incorrect", EXPECTED_TESTS_WARN,
tiles);
}
@Test
public void checkNumberOfErrorTiles() {
String cssClassToSearch = TestStatus.FAIL.getCssClass();
int tiles = page.findTiles(cssClassToSearch).size();
assertEquals("number of tests tiles with ERROR status is incorrect", EXPECTED_TESTS_FAIL,
tiles);
}
}
| 31.955556 | 100 | 0.749305 |
dc391fda33b2ff9518c9d670404e39b17822bc5a | 268 | package com.heji.server.file;
public class StorageException extends RuntimeException {
public StorageException(String message) {
super(message);
}
public StorageException(String message, Throwable cause) {
super(message, cause);
}
} | 22.333333 | 62 | 0.697761 |
beca18fd1548a4e252d1de1eddc0ec8e9b80e16e | 1,632 | package de.n26.n26androidsamples.base.presentation.providers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.util.Pair;
import javax.inject.Inject;
import de.n26.n26androidsamples.base.common.utils.StringUtils;
import de.n26.n26androidsamples.base.injection.qualifiers.ForApplication;
/**
Provides access to string resources to classes that have not access to Context (publishers, mappers, etc.)
*/
public class StringProvider {
@NonNull
private final Context context;
@NonNull
private final StringUtils stringUtils;
@Inject
StringProvider(@NonNull @ForApplication final Context context, @NonNull final StringUtils stringUtils) {
this.context = context;
this.stringUtils = stringUtils;
}
@NonNull
public String getString(@StringRes final int resId) {
return context.getString(resId);
}
@NonNull
public String getString(@StringRes final int resId, @NonNull final Object... formatArgs) {
return context.getString(resId, formatArgs);
}
/**
Use to replace the placeholders for strings that use the format "text {{placeholder}} text".
@param stringResId string resource id
@param substitutions substitutions
@return string
*/
@SuppressWarnings("unchecked")
public String getStringAndApplySubstitutions(@StringRes final int stringResId, @NonNull final Pair<String, String>... substitutions) {
return stringUtils.applySubstitutionsToString(context.getString(stringResId), substitutions);
}
}
| 31.384615 | 138 | 0.741422 |
8d178c50d270b92b0838fde44486408a22ecdba4 | 3,558 | package fi.riista.feature.announcement.show;
import fi.riista.feature.account.user.SystemUser;
import fi.riista.feature.account.user.UserRepository;
import fi.riista.feature.announcement.Announcement;
import fi.riista.feature.announcement.AnnouncementSubscriber;
import fi.riista.feature.announcement.AnnouncementSubscriberRepository;
import fi.riista.feature.announcement.AnnouncementSubscriber_;
import fi.riista.feature.organization.Organisation;
import fi.riista.feature.organization.OrganisationRepository;
import fi.riista.util.ListTransformer;
import fi.riista.util.jpa.CriteriaUtils;
import fi.riista.util.jpa.JpaGroupingUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
public class ListAnnouncementDTOTransformer extends ListTransformer<Announcement, ListAnnouncementDTO> {
@Resource
private OrganisationRepository organisationRepository;
@Resource
private UserRepository userRepository;
@Resource
private AnnouncementSubscriberRepository announcementSubscriberRepository;
@Nonnull
@Override
protected List<ListAnnouncementDTO> transform(@Nonnull final List<Announcement> list) {
if (list.isEmpty()) {
return Collections.emptyList();
}
final Function<Announcement, Organisation> fromOrganisationMapping = getFromOrganisationMapping(list);
final Function<Announcement, SystemUser> fromUserMapping = getFromUserMapping(list);
final Map<Announcement, List<AnnouncementSubscriber>> subscriberMapping = getSubscribersGroupedByAnnouncement(list);
final Function<Announcement, Organisation> rhySubscriberMapping = getRhySubscriberMapping(list);
return list.stream().map(announcement -> {
final Organisation fromOrganisation = fromOrganisationMapping.apply(announcement);
final SystemUser fromUser = fromUserMapping.apply(announcement);
final List<AnnouncementSubscriber> subscribers = subscriberMapping.get(announcement);
final Organisation rhyMemberSubscriber = rhySubscriberMapping.apply(announcement);
return ListAnnouncementDTO.create(announcement, subscribers, fromOrganisation, rhyMemberSubscriber, fromUser);
}).collect(Collectors.toList());
}
private Function<Announcement, Organisation> getFromOrganisationMapping(final Iterable<Announcement> announcements) {
return CriteriaUtils.singleQueryFunction(announcements, Announcement::getFromOrganisation, organisationRepository, false);
}
private Function<Announcement, Organisation> getRhySubscriberMapping(final Iterable<Announcement> announcements) {
return CriteriaUtils.singleQueryFunction(announcements, Announcement::getRhyMembershipSubscriber, organisationRepository, false);
}
private Function<Announcement, SystemUser> getFromUserMapping(final Iterable<Announcement> announcements) {
return CriteriaUtils.singleQueryFunction(announcements, Announcement::getFromUser, userRepository, false);
}
private Map<Announcement, List<AnnouncementSubscriber>> getSubscribersGroupedByAnnouncement(
final Collection<Announcement> announcements) {
return JpaGroupingUtils.groupRelations(announcements, AnnouncementSubscriber_.announcement, announcementSubscriberRepository);
}
}
| 47.44 | 137 | 0.796234 |
4ae0fe73d2aa186a0b8106409b6c6de2dba1680a | 13,388 | package com.cb.platform.yq.base.permission.test;
import com.cb.platform.yq.base.interfaces.bean.permission.Permission;
import com.cb.platform.yq.base.interfaces.bean.role.Role;
import com.cb.platform.yq.base.interfaces.constant.InterfaceConstant;
import com.ceba.base.utils.IDSDateUtils;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 系统权限 枚举
* 一级id
* 两位数
* 二级id
* 三位数
* 三级id
* 四位数
* 四级级id
* 五位数
*/
public enum SystemPermissionEnum implements CodeGenerateInterface {
ROLE_API("13","ROLE_API","云签API系统权限管理",PermissionTypeEnum.MODULE,"","云签API系统权限管理",ApplicationIdEnum.ADMIN),
//用户管理
ROLE_API_INTERFACE("000","INTERFACE","接口权限",PermissionTypeEnum.MENU,"","接口权限",ROLE_API),
ROLE_API_OPERATE("001","OPERATE","页面操作",PermissionTypeEnum.MENU,"","页面操作",ROLE_API),
ROLE_API_OPERATE_DATE("0000","DATE","日期章",PermissionTypeEnum.MENU,"","日期章",ROLE_API_OPERATE),
ROLE_API_OPERATE_CODE("0001","CODE","二维码",PermissionTypeEnum.MENU,"","二维码",ROLE_API_OPERATE),
ROLE_API_OPERATE_TITLE("0002","TITLE","自定义标题",PermissionTypeEnum.MENU,"","自定义标题",ROLE_API_OPERATE),
ROLE_API_OPERATE_UPLOAD("0003","UPLOAD","上传印章",PermissionTypeEnum.MENU,"","上传印章",ROLE_API_OPERATE),
ROLE_API_OPERATE_INFO("0004","INFO","获取签名信息接口是否有签章信息",PermissionTypeEnum.MENU,"","获取签名信息接口是否有签章信息",ROLE_API_OPERATE),
ROLE_API_OPERATE_WRITE("0005","WRITE","添加批注",PermissionTypeEnum.BUTTON,"","添加批注",ROLE_API_OPERATE),
ROLE_API_OPERATE_STAMP("0006","STAMP","无签章签名",PermissionTypeEnum.MENU,"","无签章签名",ROLE_API_OPERATE);
private String id;
private String pid;
private String code;
private String name;
private PermissionTypeEnum permissionType;//权限类型
private String permissionUrl;//权限URL
private String description;//权限说明
private CodeGenerateInterface parentCode;//父节点
private ApplicationIdEnum applicationIdEnum;
SystemPermissionEnum(String id, String code, String name, PermissionTypeEnum permissionType, String permissionUrl, String description, CodeGenerateInterface parentCode) {
this.id = id;
this.code = code;
this.name = name;
this.permissionType = permissionType;
this.permissionUrl = permissionUrl;
this.description = description;
this.parentCode = parentCode;
}
SystemPermissionEnum(String id, String code, String name, PermissionTypeEnum permissionType, String permissionUrl, String description,ApplicationIdEnum applicationIdEnum) {
this.id = id;
this.code = code;
this.name = name;
this.permissionType = permissionType;
this.permissionUrl = permissionUrl;
this.description = description;
this.parentCode = null;
this.applicationIdEnum=applicationIdEnum;
}
SystemPermissionEnum(String id, String code, String name, PermissionTypeEnum permissionType, String permissionUrl, String description, CodeGenerateInterface parentCode,ApplicationIdEnum applicationIdEnum) {
this.id = id;
this.code = code;
this.name = name;
this.permissionType = permissionType;
this.permissionUrl = permissionUrl;
this.description = description;
this.parentCode = parentCode;
this.applicationIdEnum=applicationIdEnum;
}
/**
* 当前权限code
*
* @return
*/
@Override
public String code() {
if(parentCode == null){
return this.getCode();
}
return parentCode.code()+"_"+this.getCode();
}
/**
* 父节点ID
* @return
*/
@Override
public String pid() {
if(parentCode == null){
return InterfaceConstant.PERMISSION_ROOT_ID;
}
return parentCode.id();
}
/**
* id
* @return
*/
@Override
public String id() {
if(parentCode == null){
return this.getId();
}
return parentCode.id()+this.getId();
}
/**
* 应用ID
*
* @return
*/
@Override
public String applicationId() {
if(this.getApplicationIdEnum() != null){
return this.getApplicationIdEnum().getId();
}
if(parentCode == null){
return this.getApplicationIdEnum().getId();
}else{
return parentCode.applicationId();
}
}
@Override
public CodeGenerateInterface getCodeGenerateInterface() {
return parentCode;
}
public ApplicationIdEnum getApplicationIdEnum() {
return applicationIdEnum;
}
public void setApplicationIdEnum(ApplicationIdEnum applicationIdEnum) {
this.applicationIdEnum = applicationIdEnum;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PermissionTypeEnum getPermissionType() {
return permissionType;
}
public void setPermissionType(PermissionTypeEnum permissionType) {
this.permissionType = permissionType;
}
public String getPermissionUrl() {
return permissionUrl;
}
public void setPermissionUrl(String permissionUrl) {
this.permissionUrl = permissionUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public CodeGenerateInterface getParentCode() {
return parentCode;
}
public void setParentCode(CodeGenerateInterface parentCode) {
this.parentCode = parentCode;
}
public static String sql(String tableName, Map<String,Object> paramMap){
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("INSERT INTO ");
stringBuffer.append(tableName);
stringBuffer.append("(");
int count=paramMap.keySet().size();
int index=0;
for(String key:paramMap.keySet()){
stringBuffer.append(key);
index++;
if(index != count){
stringBuffer.append(",");
}
}
index=0;
stringBuffer.append(")");
stringBuffer.append(" VALUES (");
for(String key:paramMap.keySet()){
Object value=paramMap.get(key);
if(value == null){
stringBuffer.append("null");
}else if(value instanceof String){
stringBuffer.append("'");
stringBuffer.append(value);
stringBuffer.append("'");
}else{
stringBuffer.append(value);
}
index++;
if(index != count){
stringBuffer.append(",");
}
}
stringBuffer.append(");");
return stringBuffer.toString();
}
public static Map<String,Object> toMap(SystemPermissionEnum systemPermissionEnum){
Map<String,Object> map=new LinkedHashMap<>();
map.put("id",systemPermissionEnum.id());
map.put("pid",systemPermissionEnum.pid());
map.put("name",systemPermissionEnum.getName());
map.put("code",systemPermissionEnum.code());
map.put("permission","ROLE_ADMIN");
map.put("permission_type",systemPermissionEnum.getPermissionType().flag);
map.put("permission_url",systemPermissionEnum.getPermissionUrl());
map.put("company_id",InterfaceConstant.DEFAULT_YQ_API_COMPAYID);
map.put("application_id",systemPermissionEnum.applicationId());
map.put("description",systemPermissionEnum.getDescription());
map.put("status","0");
map.put("version","1.0");
map.put("create_user_id",InterfaceConstant.SYSTEM_SUPER_ADMIN_USER_ID);
map.put("create_time", IDSDateUtils.getNowTime(null));
return map;
}
/**
* 转换为bean
* @param systemPermissionEnum
* @return
*/
public static Permission toBean(SystemPermissionEnum systemPermissionEnum){
Permission permission = new Permission();
permission.setId(systemPermissionEnum.id());
permission.setPid(systemPermissionEnum.pid());
permission.setName(systemPermissionEnum.getName());
permission.setCode(systemPermissionEnum.code());
permission.setPermission("ROLE_ADMIN");
permission.setPermissionType(systemPermissionEnum.getPermissionType().flag);
permission.setPermissionUrl(systemPermissionEnum.getPermissionUrl());
permission.setCompanyId("");
permission.setApplicationId(systemPermissionEnum.applicationId());
permission.setDescription(systemPermissionEnum.getDescription());
permission.setCreateUserId(InterfaceConstant.SYSTEM_SUPER_ADMIN_USER_ID);
permission.setCreateTime(IDSDateUtils.getNowTime(null));
permission.setStatus("0");
permission.setVersion("232");
return permission;
}
public static Map<String,Object> insertRoleSql(Role role){
Map<String,Object> map=new LinkedHashMap<>();
map.put("id",role.getId());
map.put("pid",role.getPid());
map.put("name",role.getName());
map.put("code",role.getCode());
map.put("company_id",role.getCompanyId());
map.put("application_id",role.getApplicationId());
map.put("description",role.getDescription());
map.put("create_user_id",role.getCreateUserId());
map.put("create_time",IDSDateUtils.getNowTime(null));
map.put("update_user_id",role.getUpdateUserId());
map.put("update_time",IDSDateUtils.getNowTime(null));
map.put("status","1");
map.put("version","0");
return map;
}
public static Map<String,Object> insertRolePermission(String roleId,String permisssion_id,String company_id){
Map<String,Object> map=new LinkedHashMap<>();
map.put("role_id",roleId);
map.put("permission_id",permisssion_id);
map.put("company_id",company_id);
map.put("create_user_id",InterfaceConstant.SYSTEM_SUPER_ADMIN_USER_ID);
map.put("create_time",IDSDateUtils.getNowTime(null));
map.put("update_user_id",InterfaceConstant.SYSTEM_SUPER_ADMIN_USER_ID);
map.put("update_time",IDSDateUtils.getNowTime(null));
map.put("status","1");
map.put("version","0");
return map;
}
/**
* 默认的权限
*/
public static void defaultRolePermission(Role role,List<SystemPermissionEnum> list){
System.out.println(SystemPermissionEnum.sql("u_role",insertRoleSql(role)));
for(SystemPermissionEnum systemPermissionEnum:list) {
Map<String,Object> toMap=SystemPermissionEnum.insertRolePermission(role.getId(),systemPermissionEnum.id(),role.getCompanyId());
System.out.println(SystemPermissionEnum.sql("u_role_permission",toMap));
}
/*for(SystemPermissionEnum systemPermissionEnum:list){
Map<String,Object> toMap=SystemPermissionEnum.toMap(systemPermissionEnum);
System.out.println(SystemPermissionEnum.sql("u_permission",toMap));
}*/
}
public static void defaultAdminPermission(){
//用户默认权限
Role role=new Role();
role.setId(InterfaceConstant.DEFAULT_ROLE_ID);
role.setPid(InterfaceConstant.PERMISSION_ROOT_ID);
role.setName("云签API默认权限");
role.setCode("DEFAULT_YQ_API_PERMISSION");
role.setCompanyId(InterfaceConstant.DEFAULT_YQ_API_COMPAYID);
role.setApplicationId("5");
role.setDescription("role");
role.setCreateUserId(InterfaceConstant.SYSTEM_SUPER_ADMIN_USER_ID);
role.setUpdateUserId(InterfaceConstant.SYSTEM_SUPER_ADMIN_USER_ID);
role.setUpdateTime(IDSDateUtils.getNowTime(null));
role.setCreateTime(IDSDateUtils.getNowTime(null));
role.setStatus("1");
List<SystemPermissionEnum> systemPermissionEnumList=new ArrayList<>();
for(SystemPermissionEnum systemPermissionEnum:SystemPermissionEnum.values()){
systemPermissionEnumList.add(systemPermissionEnum);
}
defaultRolePermission(role,systemPermissionEnumList);
}
public static void main(String[] agrs){
defaultAdminPermission();
SystemPermissionEnum[] systemPermissionEnumArray=SystemPermissionEnum.values();
for(SystemPermissionEnum systemPermissionEnum:systemPermissionEnumArray){
Map<String,Object> toMap=SystemPermissionEnum.toMap(systemPermissionEnum);
System.out.println(SystemPermissionEnum.sql("u_permission",toMap));
}
}
}
| 35.417989 | 211 | 0.639154 |
b2d146cb863fb5d79ad466c6929f863313df941e | 213 | package cn.bgenius.pconnect.todo.service;
import cn.bgenius.pconnect.todo.entity.TTodoes;
import cn.bgenius.pconnect.common.service.BaseService;
public interface TtodoesService extends BaseService<TTodoes> {
}
| 23.666667 | 62 | 0.826291 |
c679ee74b70a989e4e41b6231cfdbf399aa03eac | 1,765 | package com.example.loginpage;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class AddExpenseActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
Button SaveExpense;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
spinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
SaveExpense=findViewById(R.id.save_expense);
SaveExpense.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),StatisticsActivity.class);
intent.putExtra("SaveExpense",SaveExpense.getText().toString());
startActivity(intent);
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " Selected", Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} | 32.090909 | 121 | 0.717847 |
e2340c5f2f9e2d790e4342d6d67b772fb4d3d537 | 1,569 | /*
* Copyright 2020 ViiSE
*
* 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.github.viise.papka.entity;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
public class NameFolderRootTestNG {
private final String rootName = "/";
private Name name;
@BeforeClass
public void beforeClass() {
name = new NameFolderRoot();
}
@Test
public void shortName() {
assertEquals(name.shortName(), rootName);
}
@Test
public void fullName() {
assertEquals(name.fullName(), rootName);
}
@Test
public void eq() {
Name expected = new NamePure("/");
assertEquals(expected, name);
}
@Test
public void eq_wrongType() {
String expected = "/";
assertNotEquals(expected, name);
}
@Test
public void eq_no() {
Name expected = new NamePure("/music");
assertNotEquals(expected, name);
}
}
| 24.904762 | 75 | 0.671128 |
c0c481c951fab872898ae02de23d9ad7d3a1b5ed | 3,284 | package io.github.cubedtear.jcubit.math;
import io.github.cubedtear.jcubit.util.API;
/**
* 3D Vector of integers (x, y). Immutable.
*
* @author Aritz Lopez
*/
@API
public class Vec3i {
public final int x, y, z;
/**
* Creates a 0-vector. Equivalent to calling {@code new Vec3i(0, 0, 0)}.
*/
@API
public Vec3i() {
this.x = this.y = this.z = 0;
}
/**
* Creates a vector with the given coordinates.
*
* @param x The x coordinate.
* @param y The y coordinate.
* @param z The z coordinate.
*/
@API
public Vec3i(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Returns the x coordinate of this vector.
*
* @return the x coordinate of this vector.
*/
@API
public int getX() {
return x;
}
/**
* Returns the y coordinate of this vector.
*
* @return the y coordinate of this vector.
*/
@API
public int getY() {
return y;
}
/**
* Returns the z coordinate of this vector.
*
* @return the z coordinate of this vector.
*/
@API
public int getZ() {
return z;
}
/**
* Returns the result of adding two vectors.
* The result is a vector with each coordinate being the sum of the coordinates of {@code this} vector and {@code other}.
* @param other The other vector to sum with.
* @return The result of adding {@code this} with {@code other}
*/
@API
public Vec3i add(Vec3i other) {
return new Vec3i(this.x + other.x, this.y + other.y, this.z + other.z);
}
/**
* Returns the result of the dot-product between {@code this} and {@code other}.
* The dot-product of two vectors is the sum of the products of their coordinates.
*
* @param other The other vector.
* @return The dot-product of {@code this} and {@code other}.
*/
@API
public int dot(Vec3i other) {
return this.x * other.x + this.y * other.y + this.z * other.z;
}
/**
* Returns the length of this vector, calculated as the square root of the sum of the coordinates squared.
* @return the length of this vector.
*/
@API
public double length() {
return Math.sqrt(this.dot(this));
}
/**
* Multiplies {@code this} vector by a scalar. Equivalent to the vector resulting of multiplying each coordinate
* by the scalar. Be careful, the resulting coordinates are casted to ints.
* @param scalar The scalar to multiply by.
* @return {@code this} vector multiplied by {@code scalar}.
*/
@API
public Vec3i times(double scalar) {
return new Vec3i((int) (this.x * scalar), (int) (this.y * scalar), (int) (this.z * scalar));
}
/**
* Returns the vector with the negative coordinates. Also called the <i>opposite</i>.
* @return the opposite vector.
*/
@API
public Vec3i negate() {
return new Vec3i(-this.x, -this.y, -this.z);
}
/**
* Returns the cross-product of {@code this} and {@code other}.
*
* The cross-product of two vectors is a vector perpendicular to both of them.
* Two vectors are linearly independent if and only if the length of their cross-product is {@code zero}.
* @param other The other vector.
* @return the cross-product of {@code this} and {@code other}.
*/
@API
public Vec3i crossProd(Vec3i other) {
return new Vec3i(this.y * other.z - this.z * other.y, this.z * other.x - this.x * other.z, this.x * other.y - this.y * other.x);
}
}
| 24.691729 | 130 | 0.648904 |
57f55814be3b365c8267783867b8c7ccd309468a | 15,639 | package calculadora.service;
public class Motor {
private static final char MEIA_RISCA = '–';
public static String calcResultado(String formula) throws IllegalArgumentException {
String[] numeros;
String[] operadoresBasicos;
numeros = formula.replace(",", ".").split("([+]|[" + MEIA_RISCA + "])");
operadoresBasicos = new String[(numeros.length > 0) ? numeros.length - 1 : 0];
if (operadoresBasicos.length > 0) {
for (int i = 0, tamanhoNumeroAnterior = 0; i < numeros.length; i++) {
if (i < operadoresBasicos.length) {
if (formula.charAt(tamanhoNumeroAnterior + numeros[i].length()) == '+'
|| formula.charAt(tamanhoNumeroAnterior + numeros[i].length()) == MEIA_RISCA) {
operadoresBasicos[i] = String.valueOf(formula.charAt(tamanhoNumeroAnterior + numeros[i].length()));
tamanhoNumeroAnterior += numeros[i].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
if (numeros[i].contains("*") && numeros[i].contains("/")) {
String[] numerosMultiplicados;
String[] multiplicadores;
numerosMultiplicados = numeros[i].split("[*]");
multiplicadores = new String[numerosMultiplicados.length - 1];
for (int j = 0, tamanhoNumeroMultiplicadoAnterior = 0; j < numerosMultiplicados.length; j++) {
if (j < multiplicadores.length) {
if (numeros[i].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()) == '*') {
multiplicadores[j] = String.valueOf(numeros[i].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()));
tamanhoNumeroMultiplicadoAnterior += numerosMultiplicados[j].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
if (numerosMultiplicados[j].contains("/")) {
String[] numerosDivididos;
String[] divisores;
numerosDivididos = numerosMultiplicados[j].split("[/]");
divisores = new String[numerosDivididos.length - 1];
for (int k = 0, tamanhoNumeroDivididoAnterior = 0; k < numerosDivididos.length; k++) {
if (k < divisores.length) {
if (numerosMultiplicados[j].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[k].length()) == '/') {
divisores[k] = String.valueOf(numerosMultiplicados[j].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[k].length()));
tamanhoNumeroDivididoAnterior += numerosDivididos[k].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
double resultadoDivisao = 0;
for (int k = 0; k < numerosDivididos.length - 1; k++) {
double arg1, arg2 = Double.parseDouble(numerosDivididos[k + 1]);
if (k == 0) {
arg1 = Double.parseDouble(numerosDivididos[k]);
} else {
arg1 = resultadoDivisao;
}
resultadoDivisao = arg1 / arg2;
}
numerosMultiplicados[j] = String.valueOf(resultadoDivisao);
}
}
double resultadoMultiplicaco = 0;
for (int j = 0; j < numerosMultiplicados.length - 1; j++) {
double arg1, arg2 = Double.parseDouble(numerosMultiplicados[j + 1]);
if (j == 0) {
arg1 = Double.parseDouble(numerosMultiplicados[j]);
} else {
arg1 = resultadoMultiplicaco;
}
resultadoMultiplicaco = arg1 * arg2;
}
numeros[i] = String.valueOf(resultadoMultiplicaco);
} else if (numeros[i].contains("*")) {
String[] numerosMultiplicados;
String[] multiplicadores;
numerosMultiplicados = numeros[i].split("[*]");
multiplicadores = new String[numerosMultiplicados.length - 1];
for (int j = 0, tamanhoNumeroMultiplicadoAnterior = 0; j < numerosMultiplicados.length; j++) {
if (j < multiplicadores.length) {
if (numeros[i].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()) == '*') {
multiplicadores[j] = String.valueOf(numeros[i].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()));
tamanhoNumeroMultiplicadoAnterior += numerosMultiplicados[j].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
double resultadoMultiplicaco = 0;
for (int j = 0; j < numerosMultiplicados.length - 1; j++) {
double arg1, arg2 = Double.parseDouble(numerosMultiplicados[j + 1]);
if (j == 0) {
arg1 = Double.parseDouble(numerosMultiplicados[j]);
} else {
arg1 = resultadoMultiplicaco;
}
resultadoMultiplicaco = arg1 * arg2;
}
numeros[i] = String.valueOf(resultadoMultiplicaco);
} else if (numeros[i].contains("/")) {
String[] numerosDivididos;
String[] divisores;
numerosDivididos = numeros[i].split("[/]");
divisores = new String[numerosDivididos.length - 1];
for (int j = 0, tamanhoNumeroDivididoAnterior = 0; j < numerosDivididos.length; j++) {
if (j < divisores.length) {
if (numeros[i].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[j].length()) == '/') {
divisores[j] = String.valueOf(numeros[i].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[j].length()));
tamanhoNumeroDivididoAnterior += numerosDivididos[j].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
double resultadoDivisao = 0;
for (int j = 0; j < numerosDivididos.length - 1; j++) {
double arg1, arg2 = Double.parseDouble(numerosDivididos[j + 1]);
if (j == 0) {
arg1 = Double.parseDouble(numerosDivididos[j]);
} else {
arg1 = resultadoDivisao;
}
resultadoDivisao = arg1 / arg2;
}
numeros[i] = String.valueOf(resultadoDivisao);
}
}
double resultado = 0;
for (int i = 0; i < numeros.length - 1; i++) {
double arg1, arg2 = Double.parseDouble(numeros[i + 1]);
if (i == 0) {
arg1 = Double.parseDouble(numeros[i]);
} else {
arg1 = resultado;
}
if (operadoresBasicos[i].equals("+")) {
resultado = arg1 + arg2;
} else if (operadoresBasicos[i].equals(String.valueOf(MEIA_RISCA))) {
resultado = arg1 - arg2;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
return String.valueOf(resultado);
} else {
if (numeros[0].contains("*") && numeros[0].contains("/")) {
String[] numerosMultiplicados;
String[] multiplicadores;
numerosMultiplicados = numeros[0].split("[*]");
multiplicadores = new String[numerosMultiplicados.length - 1];
for (int j = 0, tamanhoNumeroMultiplicadoAnterior = 0; j < numerosMultiplicados.length; j++) {
if (j < multiplicadores.length) {
if (numeros[0].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()) == '*') {
multiplicadores[j] = String.valueOf(numeros[0].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()));
tamanhoNumeroMultiplicadoAnterior += numerosMultiplicados[j].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
if (numerosMultiplicados[j].contains("/")) {
String[] numerosDivididos;
String[] divisores;
numerosDivididos = numerosMultiplicados[j].split("[/]");
divisores = new String[numerosDivididos.length - 1];
for (int k = 0, tamanhoNumeroDivididoAnterior = 0; k < numerosDivididos.length; k++) {
if (k < operadoresBasicos.length) {
if (numerosMultiplicados[j].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[k].length()) == '/') {
divisores[k] = String.valueOf(numerosMultiplicados[j].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[k].length()));
tamanhoNumeroDivididoAnterior += numerosDivididos[k].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
double resultadoDivisao = 0;
for (int k = 0; k < numerosDivididos.length - 1; k++) {
double arg1, arg2 = Double.parseDouble(numerosDivididos[k + 1]);
if (k == 0) {
arg1 = Double.parseDouble(numerosDivididos[k]);
} else {
arg1 = resultadoDivisao;
}
resultadoDivisao = arg1 / arg2;
}
numerosMultiplicados[j] = String.valueOf(resultadoDivisao);
}
}
double resultadoMultiplicaco = 0;
for (int j = 0; j < numerosMultiplicados.length - 1; j++) {
double arg1, arg2 = Double.parseDouble(numerosMultiplicados[j + 1]);
if (j == 0) {
arg1 = Double.parseDouble(numerosMultiplicados[j]);
} else {
arg1 = resultadoMultiplicaco;
}
resultadoMultiplicaco = arg1 * arg2;
}
return String.valueOf(resultadoMultiplicaco);
} else if (numeros[0].contains("*")) {
String[] numerosMultiplicados;
String[] multiplicadores;
numerosMultiplicados = numeros[0].split("[*]");
multiplicadores = new String[numerosMultiplicados.length - 1];
for (int j = 0, tamanhoNumeroMultiplicadoAnterior = 0; j < numerosMultiplicados.length; j++) {
if (j < multiplicadores.length) {
if (numeros[0].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()) == '*') {
multiplicadores[j] = String.valueOf(numeros[0].charAt(tamanhoNumeroMultiplicadoAnterior + numerosMultiplicados[j].length()));
tamanhoNumeroMultiplicadoAnterior += numerosMultiplicados[j].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
double resultadoMultiplicaco = 0;
for (int j = 0; j < numerosMultiplicados.length - 1; j++) {
double arg1, arg2 = Double.parseDouble(numerosMultiplicados[j + 1]);
if (j == 0) {
arg1 = Double.parseDouble(numerosMultiplicados[j]);
} else {
arg1 = resultadoMultiplicaco;
}
resultadoMultiplicaco = arg1 * arg2;
}
return String.valueOf(resultadoMultiplicaco);
} else if (numeros[0].contains("/")) {
String[] numerosDivididos;
String[] divisores;
numerosDivididos = numeros[0].split("[/]");
divisores = new String[numerosDivididos.length - 1];
for (int j = 0, tamanhoNumeroDivididoAnterior = 0; j < numerosDivididos.length; j++) {
if (j < divisores.length) {
if (numeros[0].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[j].length()) == '/') {
divisores[j] = String.valueOf(numeros[0].charAt(tamanhoNumeroDivididoAnterior + numerosDivididos[j].length()));
tamanhoNumeroDivididoAnterior += numerosDivididos[j].length() + 1;
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
double resultadoDivisao = 0;
for (int j = 0; j < numerosDivididos.length - 1; j++) {
double arg1, arg2 = Double.parseDouble(numerosDivididos[j + 1]);
if (j == 0) {
arg1 = Double.parseDouble(numerosDivididos[j]);
} else {
arg1 = resultadoDivisao;
}
resultadoDivisao = arg1 / arg2;
}
return String.valueOf(resultadoDivisao);
} else {
throw new IllegalArgumentException("ERRO De Sintaxe!");
}
}
}
public static String calcResultado(char[] caracteres) throws IllegalArgumentException {
String formula = new String(caracteres);
return calcResultado(formula);
}
}
| 47.679878 | 164 | 0.46659 |
e20aa70c793f271fb438166eef6f037c8e3d2c61 | 9,574 | /*
* Copyright (C) ExBin Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.exbin.framework.editor.xbup.viewer;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.swing.JComponent;
import org.exbin.auxiliary.paged_data.ByteArrayEditableData;
import org.exbin.framework.api.XBApplication;
import org.exbin.framework.bined.gui.BinEdComponentPanel;
import org.exbin.framework.editor.xbup.gui.BlockComponentViewerPanel;
import org.exbin.framework.editor.xbup.gui.BlockDefinitionPanel;
import org.exbin.framework.editor.xbup.gui.BlockRowEditorPanel;
import org.exbin.framework.editor.xbup.gui.DocumentViewerPanel;
import org.exbin.framework.editor.xbup.gui.ModifyBlockPanel;
import org.exbin.framework.editor.xbup.gui.SimpleMessagePanel;
import org.exbin.framework.gui.utils.ClipboardActionsUpdateListener;
import org.exbin.xbup.core.block.XBBlockDataMode;
import org.exbin.xbup.core.block.XBTBlock;
import org.exbin.xbup.core.block.declaration.XBBlockDecl;
import org.exbin.xbup.core.block.declaration.catalog.XBCBlockDecl;
import org.exbin.xbup.core.catalog.XBACatalog;
import org.exbin.xbup.core.catalog.XBPlugUiType;
import org.exbin.xbup.core.catalog.base.XBCBlockRev;
import org.exbin.xbup.core.catalog.base.XBCXBlockUi;
import org.exbin.xbup.core.catalog.base.XBCXPlugUi;
import org.exbin.xbup.core.catalog.base.service.XBCXUiService;
import org.exbin.xbup.core.parser.XBProcessingException;
import org.exbin.xbup.core.parser.token.pull.convert.XBTProviderToPullProvider;
import org.exbin.xbup.core.serial.XBPSerialReader;
import org.exbin.xbup.core.serial.XBSerializable;
import org.exbin.xbup.core.util.StreamUtils;
import org.exbin.xbup.parser_tree.XBTTreeNode;
import org.exbin.xbup.parser_tree.XBTTreeWriter;
import org.exbin.xbup.plugin.XBCatalogPlugin;
import org.exbin.xbup.plugin.XBPanelViewer;
import org.exbin.xbup.plugin.XBPanelViewerCatalogPlugin;
import org.exbin.xbup.plugin.XBPluginRepository;
/**
* Custom viewer of document.
*
* @version 0.2.1 2020/09/25
* @author ExBin Project (http://exbin.org)
*/
@ParametersAreNonnullByDefault
public class ViewerDocumentTab implements DocumentTab {
private XBPluginRepository pluginRepository;
private DocumentViewerPanel viewerPanel = new DocumentViewerPanel();
private final BlockDefinitionPanel definitionPanel = new BlockDefinitionPanel();
private final BinEdComponentPanel dataPanel = new BinEdComponentPanel();
private final BlockRowEditorPanel rowEditorPanel = new BlockRowEditorPanel();
private final BlockComponentViewerPanel componentViewerPanel = new BlockComponentViewerPanel();
private XBTBlock selectedItem = null;
private XBACatalog catalog;
private ClipboardActionsUpdateListener updateListener;
public ViewerDocumentTab() {
SimpleMessagePanel messagePanel = new SimpleMessagePanel();
viewerPanel.setBorderComponent(messagePanel);
}
@Nonnull
@Override
public JComponent getComponent() {
return viewerPanel;
}
@Override
public void setCatalog(XBACatalog catalog) {
this.catalog = catalog;
definitionPanel.setCatalog(catalog);
}
@Override
public void setPluginRepository(XBPluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
definitionPanel.setPluginRepository(pluginRepository);
}
@Override
public void setApplication(XBApplication application) {
definitionPanel.setApplication(application);
}
@Override
public void setSelectedItem(@Nullable XBTBlock block) {
viewerPanel.removeAllViews();
if (block != null) {
XBCXUiService uiService = catalog.getCatalogService(XBCXUiService.class);
XBBlockDecl decl = block instanceof XBTTreeNode ? ((XBTTreeNode) block).getBlockDecl() : null;
if (decl instanceof XBCBlockDecl) {
XBCBlockRev blockSpecRev = ((XBCBlockDecl) decl).getBlockSpecRev();
XBCXBlockUi panelViewerUi = uiService.findUiByPR(blockSpecRev, XBPlugUiType.PANEL_VIEWER, 0);
if (panelViewerUi != null) {
XBCXPlugUi plugUi = panelViewerUi.getUi();
Long methodIndex = plugUi.getMethodIndex();
//pane.getPlugin().getPluginFile();
try {
XBCatalogPlugin pluginHandler = pluginRepository.getPluginHandler(plugUi.getPlugin());
if (pluginHandler != null) {
XBPanelViewer panelViewer = ((XBPanelViewerCatalogPlugin) pluginHandler).getPanelViewer(methodIndex);
reloadCustomEditor(panelViewer, block);
viewerPanel.addView("Viewer", panelViewer.getViewer());
}
} catch (Exception ex) {
Logger.getLogger(ViewerDocumentTab.class.getName()).log(Level.SEVERE, null, ex);
}
}
XBCXBlockUi componentViewerUi = uiService.findUiByPR(blockSpecRev, XBPlugUiType.COMPONENT_VIEWER, 0);
if (componentViewerUi != null) {
XBCXPlugUi plugUi = componentViewerUi.getUi();
try {
XBCatalogPlugin pluginHandler = pluginRepository.getPluginHandler(plugUi.getPlugin());
if (pluginHandler != null) {
componentViewerPanel.setBlock(block, plugUi, pluginHandler);
viewerPanel.addView("Component Viewer", componentViewerPanel);
}
} catch (Exception ex) {
Logger.getLogger(ViewerDocumentTab.class.getName()).log(Level.SEVERE, null, ex);
}
}
XBCXBlockUi rowEditorUi = uiService.findUiByPR(blockSpecRev, XBPlugUiType.ROW_EDITOR, 0);
if (rowEditorUi != null) {
XBCXPlugUi plugUi = rowEditorUi.getUi();
try {
XBCatalogPlugin pluginHandler = pluginRepository.getPluginHandler(plugUi.getPlugin());
if (pluginHandler != null) {
rowEditorPanel.setBlock(block, plugUi, pluginHandler);
viewerPanel.addView("Row Viewer", rowEditorPanel);
}
} catch (Exception ex) {
Logger.getLogger(ViewerDocumentTab.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if (block.getDataMode() == XBBlockDataMode.DATA_BLOCK) {
ByteArrayEditableData byteArrayData = new ByteArrayEditableData();
try (OutputStream dataOutputStream = byteArrayData.getDataOutputStream()) {
StreamUtils.copyInputStreamToOutputStream(block.getData(), dataOutputStream);
} catch (IOException ex) {
Logger.getLogger(ViewerDocumentTab.class.getName()).log(Level.SEVERE, null, ex);
}
dataPanel.setContentData(byteArrayData);
viewerPanel.addView("Data", dataPanel);
} else {
definitionPanel.setBlock(block);
viewerPanel.addView("Definition", definitionPanel);
}
}
viewerPanel.viewsAdded();
selectedItem = block;
viewerPanel.revalidate();
viewerPanel.repaint();
}
private void reloadCustomEditor(XBPanelViewer panelViewer, XBTBlock block) {
XBPSerialReader serialReader = new XBPSerialReader(new XBTProviderToPullProvider(new XBTTreeWriter(block)));
try {
serialReader.read((XBSerializable) panelViewer);
} catch (XBProcessingException | IOException ex) {
Logger.getLogger(ModifyBlockPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void performCut() {
}
@Override
public void performCopy() {
}
@Override
public void performPaste() {
}
@Override
public void performDelete() {
}
@Override
public void performSelectAll() {
}
@Override
public boolean isSelection() {
return false;
}
@Override
public boolean isEditable() {
return false;
}
@Override
public boolean canSelectAll() {
return false;
}
@Override
public boolean canPaste() {
return false;
}
@Override
public boolean canDelete() {
return false;
}
@Override
public void setUpdateListener(ClipboardActionsUpdateListener updateListener) {
this.updateListener = updateListener;
}
@Override
public void setActivationListener(ActivationListener listener) {
}
}
| 38.604839 | 129 | 0.667328 |
4a25c68f908681f3408c2f84c65a4463a2ad737b | 1,995 | package io.rapidpro.flows.runner;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.rapidpro.expressions.dates.DateStyle;
import io.rapidpro.flows.utils.JsonUtils;
import io.rapidpro.flows.utils.Jsonizable;
import org.threeten.bp.ZoneId;
/**
* An organization - used to provide additional information about how a flow should be run
*/
public class Org implements Jsonizable {
protected String m_country;
protected String m_primaryLanguage;
protected ZoneId m_timezone;
protected DateStyle m_dateStyle;
protected boolean m_anon;
public Org(String country, String primaryLanguage, ZoneId timezone, DateStyle dateStyle, boolean anon) {
m_country = country;
m_primaryLanguage = primaryLanguage;
m_timezone = timezone;
m_dateStyle = dateStyle;
m_anon = anon;
}
public static Org fromJson(JsonElement elm) {
JsonObject obj = elm.getAsJsonObject();
return new Org(
obj.get("country").getAsString(),
obj.get("primary_language").getAsString(),
ZoneId.of(obj.get("timezone").getAsString()),
DateStyle.valueOf(obj.get("date_style").getAsString().toUpperCase()),
obj.get("anon").getAsBoolean()
);
}
@Override
public JsonElement toJson() {
return JsonUtils.object(
"country", m_country,
"primary_language", m_primaryLanguage,
"timezone", m_timezone.getId(),
"date_style", m_dateStyle.name().toLowerCase(),
"anon", m_anon
);
}
public String getCountry() {
return m_country;
}
public String getPrimaryLanguage() {
return m_primaryLanguage;
}
public ZoneId getTimezone() {
return m_timezone;
}
public DateStyle getDateStyle() {
return m_dateStyle;
}
public boolean isAnon() {
return m_anon;
}
}
| 26.6 | 108 | 0.633584 |
8db936c6046b3fd3aadff5fcd834cf1f8b1e8258 | 472 | package musti;
import java.awt.Graphics;
import java.awt.Image;
public class Arkaplan {
private Image arkaplanimage;
int height;
public Arkaplan(Image arkaplanimage)
{
super();
this.arkaplanimage = arkaplanimage;
height = arkaplanimage.getHeight(null);
}
public void ciz (Graphics g,double coordinateX,int CY1, int CY2,int a,int b,int c, int d)
{
g.drawImage(arkaplanimage, a, b,c,d, 0+(int)coordinateX,CY1,500+(int)coordinateX ,CY2 , null);
}
}
| 19.666667 | 96 | 0.71822 |
8ff77d8668534fcf4310abf747015a5ffc74a6af | 222 | package pl.zankowski.tostringverifier.validator;
import pl.zankowski.tostringverifier.generator.GeneratorResult;
interface Validator {
void validate(final String toString, final GeneratorResult generatorResult);
}
| 22.2 | 80 | 0.828829 |
ab36abc5b10739c4efbe20f596fc9074335cb822 | 481 | package b.j.a.c.h0.t;
import b.j.a.b.f;
import b.j.a.c.y;
import b.j.a.c.z.a;
@a
public final class t0 extends r0<Object> {
public t0() {
super(String.class, false);
}
public boolean d(y yVar, Object obj) {
return ((String) obj).length() == 0;
}
public void f(Object obj, f fVar, y yVar) {
fVar.Q0((String) obj);
}
public final void g(Object obj, f fVar, y yVar, b.j.a.c.f0.f fVar2) {
fVar.Q0((String) obj);
}
}
| 19.24 | 73 | 0.557173 |
50fe39377f8aab55394fef381e5ab7aaac6ae791 | 360 | package com.fredhappyface.anothergemsmod.lib.blocks;
/**
* @author FredHappyface
* @version latest update 2019.08.06
*
* Provides a public constructor for net.minecraft.block.DoorBlock
*/
public class ModDoorBlock extends net.minecraft.block.DoorBlock {
public ModDoorBlock(final Properties blockProperties) {
super(blockProperties);
}
}
| 25.714286 | 66 | 0.752778 |
ac5e718e6b1309711078e8b695e8497ae64437d5 | 1,142 | package com.leax_xiv.logo;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Turtle {
private Graphics2D g;
// Not really sure what to use these for
private int w;
private int h;
private boolean writing;
private boolean showHead;
public Turtle(Graphics g, int w, int h) {
this.g = (Graphics2D) g;
this.w = w;
this.h = h;
g.translate(w / 2, h / 2);
this.g.rotate(Math.PI);
this.writing = true;
this.showHead = true;
}
public void drawHead() {
if(showHead)
g.drawPolygon(new int[] {0, -5, 0, 5}, new int[] {7, -5, 0, -5}, 4);
}
public void move(int y) {
if(writing)
g.drawLine(0, 0, 0, y);
g.translate(0, y);
}
public void rotate(int degrees) {
g.rotate(Math.toRadians(degrees));
}
public void returnHome() {
// XXX: figure it out
}
public void clean() {
// XXX: figure it out
}
public void setWriting(boolean w) {
this.writing = w;
}
public void setShowHead(boolean s) {
this.showHead = s;
}
public boolean isShowHead() {
return this.showHead;
}
public void setTrailColor(Color c) {
this.g.setColor(c);
}
}
| 16.550725 | 71 | 0.637478 |
b70055556eb9194f3cf337ad8210f5af802b7f12 | 1,019 | package com.lcg.basicweb.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
public abstract class BaseController {
/**
* 基础异常处理
* @param e Exception
* @param request request
* @return ResponseEntity
*/
@ExceptionHandler(value = Exception.class)
public ResponseEntity<Map<String, Object>> basicHandler(Exception e, HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value()).body(
new HashMap<String, Object>() {
{
put("message", e.getMessage());
put("success", false);
put("request", request.getRequestURI());
put("code", 0);
}
}
);
}
}
| 30.878788 | 102 | 0.606477 |
1b34853e388c225f4c3ea651b82f3e7e6bcbcf83 | 4,684 | /**
* Copyright (c) 2013 Martin Geisse
*
* This file is distributed under the terms of the MIT license.
*/
package name.martingeisse.guiserver.configuration.multiverse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import name.martingeisse.guiserver.configuration.ConfigurationException;
import name.martingeisse.guiserver.configuration.element.Element;
import name.martingeisse.guiserver.configuration.element.StorageElementParser;
import name.martingeisse.guiserver.configuration.element.StorageElementParserSwitch;
import name.martingeisse.guiserver.configuration.storage.StorageElement;
import name.martingeisse.guiserver.configuration.storage.StorageException;
import name.martingeisse.guiserver.configuration.storage.StorageFolder;
import name.martingeisse.guiserver.configuration.storage.StorageFolderEntry;
import name.martingeisse.guiserver.configuration.storage.UniverseStorage;
import name.martingeisse.guiserver.template.ComponentGroupConfiguration;
import name.martingeisse.guiserver.template.IConfigurationSnippet;
import name.martingeisse.guiserver.template.MarkupContent;
import name.martingeisse.guiserver.xml.content.ContentParser;
/**
* Helper class to generate the configuration from the configuration files.
*
* Instances of this class should not be used by two callers at the same time.
*/
final class DefaultUniverseConfigurationBuilder {
/**
* the fileParser
*/
private final StorageElementParser fileParser;
/**
* the elements
*/
private final Map<String, Element> elements = new HashMap<>();
/**
* the pathSegments
*/
private final Stack<String> pathSegments = new Stack<>();
/**
* the snippets
*/
private final List<IConfigurationSnippet> snippets = new ArrayList<>();
/**
* Constructor.
* @param templateParser the XML-content-to-object-binding
*/
public DefaultUniverseConfigurationBuilder(ContentParser<MarkupContent<ComponentGroupConfiguration>> templateParser) {
this.fileParser = new StorageElementParserSwitch(templateParser);
}
/**
* Builds the configuration using the files in the specified root folder and its subfolders.
* @param storage the configuration storage
* @param serialNumber the serial number for the configuration to build
* @return the configuration elements
* @throws StorageException on errors in the storage system
*/
public DefaultUniverseConfiguration build(UniverseStorage storage, int serialNumber) throws StorageException, ConfigurationException {
if (storage == null) {
throw new IllegalArgumentException("storage cannot be null");
}
elements.clear();
pathSegments.clear();
snippets.clear();
handleFolder(storage.getRootFolder());
return new DefaultUniverseConfiguration(serialNumber, elements, snippets);
}
/**
*
*/
private void handleFolder(StorageFolder folder) throws StorageException, ConfigurationException {
for (StorageFolderEntry entry : folder.list()) {
pathSegments.push(entry.getName());
if (entry instanceof StorageFolder) {
handleFolder((StorageFolder)entry);
} else if (entry instanceof StorageElement) {
handleElement((StorageElement)entry);
} else {
throw new RuntimeException("configuration folder contains non-element, non-folder entry: " + getCurrentPath());
}
pathSegments.pop();
}
}
/**
*
*/
private void handleElement(StorageElement element) throws StorageException, ConfigurationException {
String path = getCurrentPath();
elements.put(path, fileParser.parse(element, path, snippets));
}
/**
* TODO clean up the vagueness between this method, the folder's configuration path
* and the folder's HTTP path
*/
private String getCurrentPath() {
if (pathSegments.isEmpty()) {
throw new IllegalStateException();
}
int remainingPrefixSegments = pathSegments.size() - 1;
StringBuilder builder = new StringBuilder();
for (final String segment : pathSegments) {
if (remainingPrefixSegments > 0) {
builder.append('/').append(segment);
} else {
int dotIndex = segment.indexOf('.');
if (dotIndex == -1) {
throw new RuntimeException("invalid configuration element path (missing filename extension): " + segment);
}
String baseName = segment.substring(0, dotIndex);
if (baseName.isEmpty()) {
throw new RuntimeException("invalid configuration element path (empty base name): " + segment);
}
if (baseName.equals("_")) {
if (pathSegments.size() == 1) {
builder.append('/');
}
} else {
builder.append('/').append(baseName);
}
}
remainingPrefixSegments--;
}
return builder.toString();
}
}
| 32.755245 | 135 | 0.751067 |
9ddaf7318fccdb6a3758c4fc974f1be6f27926da | 965 | package me.chanjar.weixin.mp.bean.guide;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
* 获取快捷回复,关注顾问自动回复返回类
* @author <a href="https://www.sacoc.cn">广州跨界-宋心成</a>
* @date 2021/5/8/008
*/
@Data
public class WxMpGuideConfig implements Serializable {
private static final long serialVersionUID = -343579331927473027L;
/**
* 快捷回复列表
*/
@SerializedName("guide_fast_reply_list")
private List<WxMpGuideFastReply> guideFastReplyList;
/**
* 第一条关注顾问自动回复(欢迎语)
*/
@SerializedName("guide_auto_reply")
private WxMpGuideAutoReply guideAutoReply;
/**
* 第二条关注顾问自动回复(欢迎语)
*/
@SerializedName("guide_auto_reply_plus")
private WxMpGuideAutoReply guideAutoReplyPlus;
public static WxMpGuideConfig fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxMpGuideConfig.class);
}
}
| 23.536585 | 72 | 0.74715 |
7fa81dba5ecf254a739ca7fab6ad5674b4ca4145 | 4,940 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.formrecognizer;
import com.azure.ai.formrecognizer.models.FormRecognizerLocale;
import com.azure.ai.formrecognizer.models.FormRecognizerOperationResult;
import com.azure.ai.formrecognizer.models.RecognizeReceiptsOptions;
import com.azure.ai.formrecognizer.models.RecognizedForm;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.Context;
import com.azure.core.util.polling.SyncPoller;
import java.util.List;
/**
* Sample demonstrating converting recognized form fields to strongly typed US receipt field values.
* See
* <a href="https://aka.ms/formrecognizer/receiptfields"></a>
* for information on the strongly typed fields returned by service when recognizing receipts.
* More information on the Receipt used in the example below can be found
* <a href="https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/resources/java/com/azure/ai/formrecognizer/Receipt.java">here</a>
*/
public class StronglyTypedRecognizedForm {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
public static void main(final String[] args) {
// Instantiate a client that will be used to call the service.
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https://{endpoint}.cognitiveservices.azure.com/")
.buildClient();
String receiptUrl =
"https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/sdk/formrecognizer"
+ "/azure-ai-formrecognizer/src/samples/resources/sample-forms/receipts/contoso-allinone.jpg";
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeReceiptPoller =
client.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US),
Context.NONE);
List<RecognizedForm> receiptPageResults = recognizeReceiptPoller.getFinalResult();
for (int i = 0; i < receiptPageResults.size(); i++) {
final RecognizedForm recognizedForm = receiptPageResults.get(i);
System.out.printf("----------- Recognized receipt info for page %d -----------%n", i);
// Use Receipt model to transform the recognized form to a strongly typed US receipt
Receipt usReceipt = new Receipt(recognizedForm);
System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getValue(),
usReceipt.getMerchantName().getConfidence());
System.out.printf("Merchant Address: %s, confidence: %.2f%n",
usReceipt.getMerchantAddress().getValue(),
usReceipt.getMerchantAddress().getConfidence());
System.out.printf("Merchant Phone Number %s, confidence: %.2f%n",
usReceipt.getMerchantPhoneNumber().getValue(), usReceipt.getMerchantPhoneNumber().getConfidence());
System.out.printf("Total: %.2f confidence: %.2f%n", usReceipt.getTotal().getValue(),
usReceipt.getTotal().getConfidence());
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
usReceipt.getTransactionDate().getValue(), usReceipt.getTransactionDate().getConfidence());
System.out.printf("Transaction Time: %s, confidence: %.2f%n",
usReceipt.getTransactionTime().getValue(), usReceipt.getTransactionTime().getConfidence());
System.out.printf("Receipt Items: %n");
usReceipt.getReceiptItems().forEach(receiptItem -> {
if (receiptItem.getName() != null) {
System.out.printf("Name: %s, confidence: %.2f%n", receiptItem.getName().getValue(),
receiptItem.getName().getConfidence());
}
if (receiptItem.getQuantity() != null) {
System.out.printf("Quantity: %.2f, confidence: %.2f%n", receiptItem.getQuantity().getValue(),
receiptItem.getQuantity().getConfidence());
}
if (receiptItem.getPrice() != null) {
System.out.printf("Price: %.2f, confidence: %.2f%n", receiptItem.getPrice().getValue(),
receiptItem.getPrice().getConfidence());
}
if (receiptItem.getTotalPrice() != null) {
System.out.printf("Total Price: %.2f, confidence: %.2f%n",
receiptItem.getTotalPrice().getValue(), receiptItem.getTotalPrice().getConfidence());
}
});
System.out.println("-----------------------------------");
}
}
}
| 55.505618 | 188 | 0.640283 |
7a03d376cee04ea4e0ae388fde7abf6f7c247b74 | 7,351 | package com.mysaasa.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.mysaasa.MySaasaApplication;
import com.mysaasa.R;
import com.mysaasa.api.model.BlogComment;
import com.mysaasa.api.model.BlogPost;
import com.mysaasa.api.responses.PostCommentResponse;
import com.mysaasa.api.responses.PostReplyResponse;
import java.io.Serializable;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
/**
* Created by administrator on 2014-06-30.
*/
public class ActivityPostComment extends Activity {
TextView title, reply;
EditText commentBox;
Button postButton;
private boolean editMode = false;
private State state = new State();
static class State implements Serializable {
BlogPost post = null;
BlogComment comment = null;
}
public static void editComment(Activity ctx, BlogComment comment) {
Intent i = new Intent(ctx, ActivityPostComment.class);
i.putExtra("comment",comment);
i.putExtra("edit_mode",true);
ctx.startActivityForResult(i, 200202);
}
public static void postComment(Activity ctx, BlogPost post, BlogComment comment) {
Intent i = new Intent(ctx, ActivityPostComment.class);
i.putExtra("edit_mode",false);
i.putExtra("post",post);
i.putExtra("comment",comment);
ctx.startActivityForResult(i, 12345);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editMode = getIntent().getBooleanExtra("edit_mode",false);
if (editMode) setTitle("Edit Comment");
setContentView(R.layout.activity_post_comment);
if (savedInstanceState != null && savedInstanceState.containsKey("state")) {
state = (State)savedInstanceState.getSerializable("state");
} else {
state.post = (BlogPost) getIntent().getSerializableExtra("post");
state.comment = (BlogComment) getIntent().getSerializableExtra("comment");
}
title = (TextView) findViewById(R.id.title);
reply = (TextView) findViewById(R.id.reply);
commentBox = (EditText) findViewById(R.id.comment);
postButton = (Button) findViewById(R.id.post);
if (state.comment != null) {
reply.setText(state.comment.getAuthor().identifier + " said \""+ state.comment.getContent() +"\"");
} else {
reply.setVisibility(View.GONE);
}
postButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (editMode) {
System.out.println(state);
} else {
if (state.post != null) {
MySaasaApplication
.getService()
.getCommentManager()
.postBlogComment(state.post, commentBox.getText().toString())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Crouton.makeText(ActivityPostComment.this, throwable.getMessage(), Style.ALERT).show();
}
})
.subscribe(new Action1<PostCommentResponse>() {
@Override
public void call(PostCommentResponse postCommentResponse) {
if (postCommentResponse.isSuccess()) {
setResult(Activity.RESULT_OK);
finish();
} else {
Crouton.makeText(ActivityPostComment.this, postCommentResponse.getMessage(), Style.ALERT).show();
}
}
});
} else if (state.comment != null) {
MySaasaApplication
.getService()
.getCommentManager()
.postCommentResponse(state.comment, commentBox.getText().toString())
.onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Crouton.makeText(ActivityPostComment.this, throwable.getMessage(), Style.ALERT).show();
}
})
.subscribe(new Action1<PostReplyResponse>() {
@Override
public void call(PostReplyResponse postReplyResponse) {
if (postReplyResponse.isSuccess()) {
setResult(Activity.RESULT_OK);
finish();
} else {
Crouton.makeText(ActivityPostComment.this, postReplyResponse.getMessage(), Style.ALERT).show();
}
}
});
}
}
}
});
if (MySaasaApplication.getService().getAuthenticationManager().getAuthenticatedUser() == null) {
Intent i = new Intent(this, ActivitySignin.class);
startActivityForResult(i, 10010);
}
if (editMode) {
reply.setVisibility(View.GONE);
postButton.setText("Save Post");
title.setVisibility(View.GONE);
commentBox.setText(state.comment.getContent());
} else {
if (state.post != null && state.post.title != null) {
title.setText(state.post.title);
} else {
title.setVisibility(View.GONE);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("state",state);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10010 && resultCode != Activity.RESULT_OK) {
setResult(Activity.RESULT_CANCELED);
finish();
}
}
}
| 40.838889 | 141 | 0.522242 |
af8b3fb4568a2762340f6fc44bfcd35ae668ea00 | 5,501 | /*-
* Copyright (C) 2013-2014 The JBromo Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jbromo.common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import lombok.experimental.UtilityClass;
/**
* Define List Utility.
* @author qjafcunuas
*/
@UtilityClass
public final class ListUtil {
/**
* Return true if list contains same elements.
* @param <M> the model element of the list.
* @param one the first list.
* @param two the second list.
* @param sameSize if true, collections must have same size; else collections can not have the same size.
* @return true/false.
*/
public static <M> boolean containsAll(final List<M> one, final List<M> two, final boolean sameSize) {
return CollectionUtil.containsAll(one, two, sameSize);
}
/**
* Return true if list is null or empty.
* @param list the list to check.
* @return true/false.
*/
public static boolean isEmpty(final List<?> list) {
return CollectionUtil.isEmpty(list);
}
/**
* Return true if list is not null and not empty.
* @param list the list to check.
* @return true/false.
*/
public static boolean isNotEmpty(final List<?> list) {
return CollectionUtil.isNotEmpty(list);
}
/**
* Return true if list is not null and has only one elements.
* @param list the list to check.
* @return true/false.
*/
public static boolean hasOneElement(final List<?> list) {
return CollectionUtil.hasOneElement(list);
}
/**
* Return true if list contains more than one elements.
* @param list the list to check.
* @return true/false.
*/
public static boolean hasElements(final List<?> list) {
return CollectionUtil.hasElements(list);
}
/**
* Build an array list from an array.
* @param <T> the element type.
* @param values the values.
* @return true/false.
*/
@SafeVarargs
public static <T> List<T> toList(final T... values) {
if (ArrayUtil.isEmpty(values)) {
return new ArrayList<>();
}
final List<T> list = new ArrayList<>(values.length + IntegerUtil.INT_10);
for (final T value : values) {
list.add(value);
}
return list;
}
/**
* Build an unmodifiable list from an array.
* @param <T> the element type.
* @param values the values.
* @return true/false.
*/
@SafeVarargs
public static <T> List<T> toUnmodifiableList(final T... values) {
if (ArrayUtil.isEmpty(values)) {
return Collections.unmodifiableList(new ArrayList<T>());
}
return Collections.unmodifiableList(toList(values));
}
/**
* Build an array list from a collection.
* @param <T> the element type.
* @param values the values.
* @return true/false.
*/
public static <T> List<T> toList(final Collection<T> values) {
if (CollectionUtil.isEmpty(values)) {
return new ArrayList<>();
}
return new ArrayList<>(values);
}
/**
* Build an unmodifiable list from a collection.
* @param <T> the element type.
* @param values the values.
* @return true/false.
*/
public static <T> List<T> toUnmodifiableList(final Collection<T> values) {
if (CollectionUtil.isEmpty(values)) {
return Collections.unmodifiableList(new ArrayList<T>());
}
return Collections.unmodifiableList(toList(values));
}
/**
* Is assignable to a List.
* @param type the type to check
* @return true if type is List.
*/
public static boolean isList(final Class<?> type) {
return ClassUtil.isAssignableFrom(type, List.class);
}
/**
* Is assignable to a List.
* @param obj the obj to check
* @return true if type is List.
*/
public static boolean isList(final Object obj) {
return ClassUtil.isInstance(obj, List.class);
}
/**
* Return the las element of a list (null if empty).
* @param <M> the type element.
* @param list the list.
* @return the last element.
*/
public static <M> M getLast(final List<M> list) {
if (isEmpty(list)) {
return null;
} else {
return list.get(list.size() - 1);
}
}
}
| 31.079096 | 109 | 0.632976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.