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 |
|---|---|---|---|---|---|
877085968dc07ff6df8baf029a3548340f6443c0 | 6,723 | package org.fundacionparaguaya.adviserplatform.data.model;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import timber.log.Timber;
import static java.lang.String.format;
/**
* An Indicator is asked during a survey. Each indicator has a red, yellow, and green level. When the family takes the
* survey, they will choose one of those levels.
*/
public class Indicator {
private String name;
private String dimension;
private List<IndicatorOption> options;
public Indicator(String name, String dimension) {
this(name, dimension, null);
}
public Indicator(String name, String dimension, List<IndicatorOption> options) {
this.name = name;
this.dimension = dimension;
setOptions(options);
}
public String getName() {
return name;
}
public String getTitle() {
return IndicatorNameResolver.resolve(name);
}
public String getDimension() {
return dimension;
}
public List<IndicatorOption> getOptions() {
return options;
}
public void setOptions(List<IndicatorOption> options) {
this.options = options;
if (options == null) {
return;
}
for (IndicatorOption option : options) { // add references to this indicator
option.setIndicator(this);
}
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Indicator that = (Indicator) o;
return new EqualsBuilder()
.append(name, that.name)
.append(dimension, that.dimension)
.append(options, that.options)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(67, 19)
.append(name)
.append(dimension)
.append(options)
.toHashCode();
}
/**
* A temporary utility for resolving indicator names.
*/
private static class IndicatorNameResolver {
private static final String TAG = "IndicatorNameResolver";
private static Map<String, String> mNames = new HashMap<>();
static {
if (Locale.getDefault().getLanguage().equals("es")) {
map("income", "Nivel de Ingreso");
map("properKitchen", "Cocina Adecuada");
map("awarenessOfNeeds", "Conocimiento de las Necesidades");
map("documentation", "Documentación");
map("separateBed", "Cama Separada");
map("alimentation", "Alimentación");
map("separateBedrooms", "Habitaciones Separadas");
map("selfEsteem", "Autoestima");
map("security", "Seguridad");
map("autonomyDecisions", "Autonomía de Decisión");
map("phone", "Teléfono");
map("influenceInPublicSector", "Influencia Pública");
map("socialCapital", "Capital Social");
map("safeBathroom", "Baño Seguro");
map("informationAccess", "Acceso a la Información");
map("middleEducation", "Educación Media");
map("drinkingWaterAccess", "Acceso al Agua Potable");
map("safeHouse", "Casa Segura");
map("readAndWrite", "Lee y Escribe");
map("refrigerator", "Refrigerador");
map("nearbyHealthPost", "Centro Médico Cercano");
map("electricityAccess", "Acceso a la Electricidad");
map("garbageDisposal", "Basurero");
} else {
map("income", "Income");
map("properKitchen", "Proper Kitchen");
map("awarenessOfNeeds", "Awareness Of Needs");
map("documentation", "Documentation");
map("separateBed", "Separate Bed");
map("alimentation", "Alimentation");
map("separateBedrooms", "Separate Bedrooms");
map("selfEsteem", "Self-Esteem");
map("security", "Security");
map("autonomyDecisions", "Decision Autonomy");
map("phone", "Phone");
map("influenceInPublicSector", "Influence in Public Sector");
map("socialCapital", "Social Capital");
map("safeBathroom", "Safe Bathroom");
map("informationAccess", "Information Access");
map("middleEducation", "Middle Education");
map("drinkingWaterAccess", "Drinking Water Access");
map("safeHouse", "Safe House");
map("readAndWrite", "Read and Write");
map("refrigerator", "Refrigerator");
map("nearbyHealthPost", "Nearby Health Post");
map("electricityAccess", "Electricity Access");
map("garbageDisposal", "Garbage Disposal");
}
}
private static void map(String indicator, String name) {
mNames.put(indicator, name);
}
private static String resolve(String indicator) {
if (mNames.containsKey(indicator)) {
return mNames.get(indicator);
}
Timber.w(format("resolve: Don't have a mapping for %s!", indicator));
String generated = titleCase(indicator);
map(indicator, generated);
return generated;
}
/**
* Maps a indicator to a "pretty" name.
*/
private static String titleCase(String indicator) {
StringBuilder result = new StringBuilder();
CharacterIterator iterator = new StringCharacterIterator(indicator);
for (char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next()) {
if (result.length() > 0) {
result.append(" ");
}
result.append(Character.toUpperCase(c));
c = iterator.next();
while (Character.isLowerCase(c)) {
result.append(c);
c = iterator.next();
}
iterator.previous();
}
return result.toString();
}
}
}
| 35.760638 | 118 | 0.562695 |
a4c868ba7ac6f492a98c75d6fbbc6a19f00ade45 | 2,107 | package io.eventuate.messaging.kafka.basic.consumer;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import java.time.Duration;
import java.util.*;
public class DefaultKafkaMessageConsumer implements KafkaMessageConsumer {
private final KafkaConsumer<String, byte[]> delegate;
public static KafkaMessageConsumer create(Properties properties) {
return new DefaultKafkaMessageConsumer(new KafkaConsumer<>(properties));
}
private DefaultKafkaMessageConsumer(KafkaConsumer<String, byte[]> delegate) {
this.delegate = delegate;
}
@Override
public void assign(Collection<TopicPartition> topicPartitions) {
delegate.assign(topicPartitions);
}
@Override
public void seekToEnd(Collection<TopicPartition> topicPartitions) {
delegate.seekToEnd(topicPartitions);
}
@Override
public long position(TopicPartition topicPartition) {
return delegate.position(topicPartition);
}
@Override
public void seek(TopicPartition topicPartition, long position) {
delegate.seek(topicPartition, position);
}
@Override
public void subscribe(List<String> topics) {
delegate.subscribe(new ArrayList<>(topics));
}
@Override
public void commitOffsets(Map<TopicPartition, OffsetAndMetadata> offsets) {
delegate.commitSync(offsets);
}
@Override
public List<PartitionInfo> partitionsFor(String topic) {
return delegate.partitionsFor(topic);
}
@Override
public ConsumerRecords<String, byte[]> poll(Duration duration) {
return delegate.poll(duration);
}
@Override
public void pause(Set<TopicPartition> partitions) {
delegate.pause(partitions);
}
@Override
public void resume(Set<TopicPartition> partitions) {
delegate.resume(partitions);
}
@Override
public void close() {
delegate.close();
}
@Override
public void close(Duration duration) {
delegate.close(duration);
}
}
| 25.083333 | 79 | 0.756051 |
6c3df3bd4e1c163936a303376c64dc57b7ffee47 | 610 | package com.wcf.funny.admin.constant;
/**
* 用户常量信息
*/
public class UserConstant {
/**
* 空的个人简介
*/
public final static String NULL_INRODUCE="";
/**
* 默认注册用户角色
*/
public final static String DEFAULT_REGISTER_ROLE_TYPE="VIP-1";
/**
* 默认头像
*/
public final static String DEFAULT_FACE="/upload/image/face/default.jpg";
/**
* 默认的密码,重置的初始密码
*/
public final static String DEFAULT_PASSWORD="123456+";
/**
* 请求用户登录区域的地址
*/
public final static String REQUEST_FOR_AREA_ADDRESS="http://ip.taobao.com/service/getIpInfo.php";
}
| 17.941176 | 101 | 0.616393 |
ad2a1a5e3f7cdb8d525201b6a59bcb68f2b43267 | 229 | package com.sokil.repository;
import com.sokil.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> {
Role findByRole(String role);
}
| 22.9 | 67 | 0.803493 |
8b88d3ca8a2fdbd53f52e4ea2a5c76e7921a9ccc | 3,776 | package org.apache.hawq.pxf.service.rest;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.apache.commons.codec.CharEncoding;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
@PrepareForTest({RestResource.class})
public class RestResourceTest {
RestResource restResource;
MultivaluedMap<String, String> multivaluedMap;
@Test
public void testConvertToCaseInsensitiveMap() throws Exception {
List<String> multiCaseKeys = Arrays.asList("X-GP-SHLOMO", "x-gp-shlomo", "X-Gp-ShLoMo");
String value = "\\\"The king";
String replacedValue = "\"The king";
for (String key : multiCaseKeys) {
multivaluedMap.put(key, Collections.singletonList(value));
}
assertEquals("All keys should have existed", multivaluedMap.keySet().size(), multiCaseKeys.size());
Map<String, String> caseInsensitiveMap = restResource.convertToCaseInsensitiveMap(multivaluedMap);
assertEquals("Only one key should have exist", caseInsensitiveMap.keySet().size(), 1);
for (String key : multiCaseKeys) {
assertEquals("All keys should have returned the same value", caseInsensitiveMap.get(key), replacedValue);
}
}
@Test
public void testConvertToCaseInsensitiveMapUtf8() throws Exception {
byte[] bytes = {
(byte) 0x61, (byte) 0x32, (byte) 0x63, (byte) 0x5c, (byte) 0x22,
(byte) 0x55, (byte) 0x54, (byte) 0x46, (byte) 0x38, (byte) 0x5f,
(byte) 0xe8, (byte) 0xa8, (byte) 0x88, (byte) 0xe7, (byte) 0xae,
(byte) 0x97, (byte) 0xe6, (byte) 0xa9, (byte) 0x9f, (byte) 0xe7,
(byte) 0x94, (byte) 0xa8, (byte) 0xe8, (byte) 0xaa, (byte) 0x9e,
(byte) 0x5f, (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30,
(byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x5c,
(byte) 0x22, (byte) 0x6f, (byte) 0x35
};
String value = new String(bytes, CharEncoding.ISO_8859_1);
multivaluedMap.put("one", Collections.singletonList(value));
Map<String, String> caseInsensitiveMap = restResource.convertToCaseInsensitiveMap(multivaluedMap);
assertEquals("Only one key should have exist", caseInsensitiveMap.keySet().size(), 1);
assertEquals("Value should be converted to UTF-8",
caseInsensitiveMap.get("one"), "a2c\"UTF8_計算機用語_00000000\"o5");
}
@Before
public void before() throws Exception {
restResource = mock(RestResource.class, Mockito.CALLS_REAL_METHODS);
multivaluedMap = new MultivaluedMapImpl();
}
}
| 38.530612 | 117 | 0.681144 |
3fa1807ee21ecac0a7e27d52d9617c6f4c76a4b5 | 424 | package co.lq.modules.system.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import co.lq.modules.system.domain.SellerUserAvatar;
/**
* @author billy
* @date 2018-11-22
*/
public interface SellerUserAvatarRepository
extends JpaRepository<SellerUserAvatar, Long>, JpaSpecificationExecutor<SellerUserAvatar> {
}
| 26.5 | 99 | 0.806604 |
1d5f30a70868992712c9841cb9e9e9db97279982 | 699 | package slr.expression;
/**
* Árvore binária.
* @param <T>
*/
public class BinaryTree<T> {
private BinaryTreeNode<T> root;
/**
* Construtor.
*/
public BinaryTree() {
this.root = null;
}
/**
* Construtor.
* @param root raiz da árvore.
*/
public BinaryTree(BinaryTreeNode<T> root) {
this.root = root;
}
/**
* Obter a raiz da árvore.
* @return nodo raiz da árvore.
*/
public BinaryTreeNode<T> getRoot() {
return root;
}
/**
* Definir a raiz da árvore.
* @param root nodo raiz da árvore.
*/
public void setRoot(BinaryTreeNode<T> root) {
this.root = root;
}
/**
* Imprimir a árvore.
*/
public void print() {
this.getRoot().print();
}
}
| 13.705882 | 46 | 0.600858 |
68eb1862c4f257b7952809a194de2fddeedc3f40 | 834 | public class Solution {
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number and the index of the last number
*/
public List<Integer> subarraySum(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
int n = nums.length;
int prefixSum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 0);
for (int i = 0; i < n; i++) {
prefixSum += nums[i];
if (map.containsKey(prefixSum)) {
res.add(map.get(prefixSum));
res.add(i);
return res;
}
map.put(prefixSum, i + 1);
}
return res;
}
} | 28.758621 | 106 | 0.468825 |
93f48598d9c9c99ed37378e615a67bc9dc4801f9 | 1,203 | package mx.ipn.escom.prueba.coffeeapp.asynctasks;
import android.os.AsyncTask;
import android.util.Log;
import mx.ipn.escom.prueba.coffeeapp.entities.Local;
import mx.ipn.escom.prueba.coffeeapp.services.LocalesService;
import retrofit2.Response;
public class GetLocalDetailByIdAsyncTask extends AsyncTask<Integer,Void,Void> {
private LocalesService localesService;
private Response<Local> localResponse;
public GetLocalDetailByIdAsyncTask(LocalesService localesService){
this.localesService = localesService;
}
@Override
protected Void doInBackground(Integer... integers) {
try{
localResponse = localesService.getLocalById(integers[0]).execute();
if (localResponse.isSuccessful()){
if(localResponse.body() == null){
Log.d("--->","NO SE ENCONTRÓ EL LOCAL");
}
}else{
Log.d("--->","NO SE ENCONTRÓ EL LOCAL");
}
}catch (Exception e){
e.printStackTrace();
Log.d("--->","ERROR EN LA CONSULTA");
}
return null;
}
public Local getResponseBody() {
return localResponse.body();
}
}
| 30.075 | 79 | 0.627598 |
55666f7514018ce852ea731eedb29f6973173075 | 771 | /*
* Copyright (c) 2015-2018 Vladimir Schneider <vladimir.schneider@gmail.com>, all rights reserved.
*
* This code is private property of the copyright holder and cannot be used without
* having obtained a license or prior written permission of the of the copyright holder.
*
* 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.vladsch.javafx.webview.debugger;
public interface JfxDebuggerConnector extends JfxDebuggerProxy {
void sendMessageToBrowser(String data);
}
| 36.714286 | 98 | 0.774319 |
671bcbb3c7c673cbfb5561aa43976614ceff1b34 | 402 | package com.icuxika.api.exception;
/**
* 请求返回体为空
*/
public class ResponseNotOKException extends RuntimeException {
private Integer code;
public ResponseNotOKException(String message, Integer code) {
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
| 17.478261 | 65 | 0.636816 |
3efd690f8062f15ec787de26f83a520b7af3e65b | 14,537 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2019 John Stewart.
*
* 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.proticity.irc.client.parser;
import java.io.Serializable;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.proticity.irc.client.command.Capability;
import org.proticity.irc.client.command.Channel;
import org.proticity.irc.client.command.CommandBuilder;
import org.proticity.irc.client.command.ErrorCommand;
import org.proticity.irc.client.command.InvalidCommand;
import org.proticity.irc.client.command.InviteCommand;
import org.proticity.irc.client.command.IrcCommand;
import org.proticity.irc.client.command.JoinCommand;
import org.proticity.irc.client.command.MessageCommand;
import org.proticity.irc.client.command.ModeCommand;
import org.proticity.irc.client.command.NickCommand;
import org.proticity.irc.client.command.NicknamePrefix;
import org.proticity.irc.client.command.NoticeCommand;
import org.proticity.irc.client.command.NumericReplyCommand;
import org.proticity.irc.client.command.PartCommand;
import org.proticity.irc.client.command.PingCommand;
import org.proticity.irc.client.command.PongCommand;
import org.proticity.irc.client.command.PrivmsgCommand;
import org.proticity.irc.client.command.SQueryCommand;
import org.proticity.irc.client.command.ServerPrefix;
import org.proticity.irc.client.command.TagKey;
import org.proticity.irc.client.command.TopicCommand;
import org.proticity.irc.client.command.User;
import org.proticity.irc.client.command.twitch.WhisperCommand;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.util.annotation.NonNull;
import reactor.util.annotation.Nullable;
public class IrcInput implements Serializable {
private static final long serialVersionUID = 0L;
// Hostname pattern extends the standard by allowing underscrores, required for Twitch which forms a nickname-based
// hostname for hostname prefixes. Since nicknames can have underscores this means Twitch will form illegal
// hostnames.
private static final String HOSTNAME_PATTERN =
"(?<host>[a-zA-Z0-9][a-zA-Z0-9\\-_]*(\\.[a-zA-Z0-9][a-zA-Z0-9\\-_]*)*)";
private static final String IPV4_PATTERN =
"(?<ipv4>[0-9]?[0-9]?[0-9]\\.[0-9]?[0-9]?[0-9]\\.[0-9]?[0-9]?[0-9]\\.[0-9]?[0-9]?[0-9])";
private static final String IPV6_PATTERN = "(?<ipv6>123abc)"; // TODO: Proper IPv6 support.
// The nickname pattern extends the standard by allowing the first character to be numeric, required by Twitch.
private static final String NICKNAME_PATTERN = "(?<nick>[a-zA-Z\\[-`{-}0-9][a-zA-Z\\[-`{-}0-9\\-]*)";
private static final String USER_PATTERN = "(?<user>[^ \0\r\n@]+)";
private static final Pattern NICKNAME = Pattern.compile("^" + NICKNAME_PATTERN);
private static final Pattern CHANNEL =
Pattern.compile("^(?<prefix>[#+&]|(![A-Z0-9]{5}))(?<name>[^ \0\r\n:,\u0007]+)");
private static final Pattern NUMERIC_REPLY = Pattern.compile("^[0-9]{3}");
private static final Pattern NONCRLF = Pattern.compile("^[^\r\n]*");
private static final Pattern PARAM = Pattern.compile("^[^ \r\n:]+");
private static final Pattern TAG_KEY = Pattern.compile("^[a-zA-Z0-9\\-]+");
private static final Pattern TAG_VENDOR = Pattern.compile("^" + HOSTNAME_PATTERN + "/");
private static final Pattern TAG_VALUE = Pattern.compile("^(\\\\[ ;\r\n\0]|[^ ;\r\n\0])*");
private static final Pattern SERVER_PREFIX = Pattern.compile("^" + HOSTNAME_PATTERN + "|" + IPV4_PATTERN + "|" +
IPV6_PATTERN);
private static final Pattern NICK_PREFIX = Pattern.compile("^" + NICKNAME_PATTERN + "((!" + USER_PATTERN + ")?@(" +
HOSTNAME_PATTERN + "|" + IPV4_PATTERN + "|" + IPV6_PATTERN + "))?");
private static final Pattern COMMAND = Pattern.compile("^[a-zA-Z0-9]+");
private String input;
private int position;
public IrcInput(String input) {
this.input = input;
}
public Flux<IrcCommand> messages() {
tryCrlf();
return Flux.create((FluxSink<IrcCommand> sink) -> {
while (!tryEof()) {
try {
sink.next(message());
} catch (IrcParseException e) {
sink.next(new InvalidCommand(e.getInput(), e));
}
if (!tryCrlf()) {
break;
}
}
sink.complete();
});
}
protected IrcCommand message() {
var builder = new CommandBuilder();
if (tryConsume('@')) {
tags(builder);
space();
}
if (tryConsume(':')) {
prefix(builder);
space();
}
return command(builder);
}
protected IrcCommand command(@NonNull CommandBuilder builder) {
builder.command(consume(COMMAND).group());
while (trySpace()) {
if (tryConsume(':')) {
builder.trailingParameter(consume(NONCRLF).group());
break;
}
builder.parameter(consume(PARAM).group());
}
switch (builder.getCommand()) {
case "PRIVMSG":
return privmsg(builder, PrivmsgCommand.class);
case "ERROR":
return new ErrorCommand(builder);
case "NOTICE":
return privmsg(builder, NoticeCommand.class);
case "WHISPER":
return privmsg(builder, WhisperCommand.class);
case "PING":
return new PingCommand(builder);
case "PONG":
return new PongCommand(builder);
case "JOIN":
return new JoinCommand(builder);
case "PART":
return new PartCommand(builder);
case "NICK":
return new NickCommand(builder);
case "TOPIC":
return new TopicCommand(builder);
case "MODE":
return new ModeCommand(builder);
case "KICK":
// TODO
case "INVITE":
return new InviteCommand(builder);
case "SQUERY":
return privmsg(builder, SQueryCommand.class);
default:
var matcher = NUMERIC_REPLY.matcher(builder.getCommand());
if (matcher.lookingAt()) {
return new NumericReplyCommand(builder);
}
return new IrcCommand(builder);
}
}
@Nullable
protected MessageCommand<?> privmsg(@NonNull CommandBuilder builder, @NonNull Class<?> commandClass) {
var params = builder.getParameters();
if (params == null || params.isEmpty()) {
// TODO: proper error
parseError();
return null;
}
var chanName = params.get(0);
if (chanName == null) {
parseError();
return null;
}
if (commandClass.equals(SQueryCommand.class)) {
return new SQueryCommand(builder);
} else if (commandClass.equals(WhisperCommand.class)) {
return new WhisperCommand(builder);
} else {
var chan = CHANNEL.matcher(chanName);
if (chan.lookingAt()) {
if (commandClass.equals(NoticeCommand.class)) {
return new NoticeCommand<>(builder,
new Channel(chan.group("prefix"), chan.group("name")));
} else {
return new PrivmsgCommand<>(builder,
new Channel(chan.group("prefix"), chan.group("name")));
}
} else if (commandClass.equals(NoticeCommand.class)) {
return new NoticeCommand<>(builder, new User(chanName));
} else {
return new PrivmsgCommand<>(builder, new User(chanName));
}
}
}
/**
* Consume a capability.
* <p>
* Although not strictly defined as such, these use identical rules to tag keys, including the
* vendor, and so these rules are reused.
*
* @return A {@link Capability} representing the capability text.
*/
protected Capability capability() {
return new Capability(tryTagVendor().orElse(null), consume(TAG_KEY).group());
}
protected void tags(@NonNull CommandBuilder builder) {
tag(builder);
while (tryConsume(';')) {
tag(builder);
}
}
protected void tag(@NonNull CommandBuilder builder) {
var key = tagKey();
String value = null;
if (tryConsume('=')) {
value = tagValue();
}
builder.tag(key, value);
}
protected TagKey tagKey() {
var clientOnly = tryConsume('+');
var vendor = tryTagVendor();
return new TagKey(clientOnly, vendor.orElse(null), consume(TAG_KEY).group());
}
/**
* Attempt to parse a tag's vendor.
* <p>
* A vendor portion of a name is permitted in a tag key, but is optional.
*
* @return The vendor in the tag name if one is present.
*/
protected Optional<String> tryTagVendor() {
return tryConsume(TAG_VENDOR).map(matcher -> matcher.group("host"));
}
protected String tagValue() {
return consume(TAG_VALUE).group();
}
/**
* Consume zero or more space characters, returning if any were found.
*
* @return Whether or not at least one space was consumed.
*/
protected boolean trySpace() {
var found = false;
while (tryConsume(' ')) {
found = true;
}
return found;
}
/**
* Consume the required spaces in the input.
* <p>
* This is permissive in that multiple spaces may be consumed as a single delimiter, however at
* least one is required.
*/
protected void space() {
consumeAtLeastOne(' ');
}
/**
* Consume zero or more CRLF sequences.
* <p>
* This can be used where a CRLF may appear, such as at the very start of an input or at the
* end.
*
* @return Whether at least one CRLF was present.
*/
protected boolean tryCrlf() {
boolean found = false;
while (tryConsume("\r\n")) {
found = true;
}
return found;
}
/**
* Consume zero or one (or more, it's all the same) EOFs.
* <p>
* This is used to peek for the end of the sequence.
*
* @return Whether or not the parser is at the end of the input.
*/
protected boolean tryEof() {
return position == input.length();
}
/**
* Consume zero (or one, or more, it's all the same) EOFs.
* <p>
* This will require the end of input and fail if the parser is elsewhere.
*/
protected void eof() {
if (position != input.length()) {
parseError();
}
}
/**
* Parse the message prefix.
* <p>
* This can be awkward because it requires backtracking. There is ambiguous grammar here and we
* want to prioritize a servername prefix over a nickname prefix when both are valid.
*
* @param builder A {@link CommandBuilder}.
*/
protected void prefix(@NonNull CommandBuilder builder) {
int pos = position;
var serverPrefix = tryConsume(SERVER_PREFIX);
var hasServerPrefix = peek(' ');
position = pos;
var nickPrefix = tryConsume(NICK_PREFIX);
var hasNickPrefix = peek(' ');
if (!hasServerPrefix) {
if (!hasNickPrefix) {
parseError();
}
builder.prefix(new NicknamePrefix(nickPrefix.get().group("nick"),
nickPrefix.get().group("user"),
nickPrefix.get().group("host")));
} else {
position = pos + serverPrefix.get().group().length();
builder.prefix(new ServerPrefix(serverPrefix.get().group()));
}
}
protected boolean tryConsume(char c) {
if (position == input.length()) {
return false;
}
if (input.charAt(position) == c) {
position++;
return true;
}
return false;
}
/**
* Peek at the next character without advancing the parser position.
*
* @param c The character to look for.
* @return Whether the next character of the input is <code>c</code>.
*/
protected boolean peek(char c) {
if (position == input.length()) {
return false;
}
return input.charAt(position) == c;
}
protected boolean tryConsume(String s) {
if (position + s.length() > input.length()) {
return false;
}
if (input.substring(position, position + s.length()).equals(s)) {
position += s.length();
return true;
}
return false;
}
protected Optional<Matcher> tryConsume(Pattern pattern) {
var matcher = pattern.matcher(input.substring(position));
if (matcher.lookingAt()) {
position += matcher.group().length();
return Optional.of(matcher);
}
return Optional.empty();
}
protected Matcher consume(Pattern pattern) {
return tryConsume(pattern).orElseThrow(this::createParseError);
}
protected void consumeAtLeastOne(char c) {
boolean oneOrMore = false;
while (tryConsume(c)) {
oneOrMore = true;
}
if (!oneOrMore) {
parseError();
}
}
/**
* Returns a parser exception.
*
* @return A new parser exception.
*/
protected IrcParseException createParseError() {
return new IrcParseException(input, position);
}
/**
* Throws a parser exception.
*/
protected void parseError() {
throw createParseError();
}
}
| 34.944712 | 119 | 0.59125 |
026d4f041ac5884c37b6c702c29f5010e5f40164 | 298 | package com.qinwei.deathnote.support.resolve;
import java.util.Map;
import java.util.Set;
/**
* @author qinwei
* @date 2019-06-03
*/
public interface PropertyResolver {
String resolvePlaceholders(String text, Map<String, Object> config);
Set<String> findPlaceholders(String text);
}
| 18.625 | 72 | 0.734899 |
e81a35480947e2e344e93531a6de51784ec2452c | 6,585 | /**
* Copyright 2014 Flipkart Internet Pvt. 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.flipkart.foxtrot.server.resources;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.foxtrot.common.FieldType;
import com.flipkart.foxtrot.common.FieldTypeMapping;
import com.flipkart.foxtrot.common.TableFieldMapping;
import com.flipkart.foxtrot.core.MockElasticsearchServer;
import com.flipkart.foxtrot.core.TestUtils;
import com.flipkart.foxtrot.core.common.CacheUtils;
import com.flipkart.foxtrot.core.datastore.DataStore;
import com.flipkart.foxtrot.core.querystore.QueryExecutor;
import com.flipkart.foxtrot.core.querystore.QueryStore;
import com.flipkart.foxtrot.core.querystore.TableMetadataManager;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsLoader;
import com.flipkart.foxtrot.core.querystore.impl.*;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.yammer.dropwizard.testing.ResourceTest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.junit.After;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
/**
* Created by rishabh.goyal on 06/05/14.
*/
public class TableFieldMappingResourceTest extends ResourceTest {
private ObjectMapper mapper = new ObjectMapper();
private HazelcastInstance hazelcastInstance;
private MockElasticsearchServer elasticsearchServer;
private QueryStore queryStore;
public TableFieldMappingResourceTest() throws Exception {
ElasticsearchUtils.setMapper(mapper);
DataStore dataStore = TestUtils.getDataStore();
//Initializing Cache Factory
hazelcastInstance = new TestHazelcastInstanceFactory(1).newHazelcastInstance();
HazelcastConnection hazelcastConnection = Mockito.mock(HazelcastConnection.class);
when(hazelcastConnection.getHazelcast()).thenReturn(hazelcastInstance);
CacheUtils.setCacheFactory(new DistributedCacheFactory(hazelcastConnection, mapper));
elasticsearchServer = new MockElasticsearchServer(UUID.randomUUID().toString());
ElasticsearchConnection elasticsearchConnection = Mockito.mock(ElasticsearchConnection.class);
when(elasticsearchConnection.getClient()).thenReturn(elasticsearchServer.getClient());
ElasticsearchUtils.initializeMappings(elasticsearchServer.getClient());
Settings indexSettings = ImmutableSettings.settingsBuilder().put("number_of_replicas", 0).build();
CreateIndexRequest createRequest = new CreateIndexRequest(TableMapStore.TABLE_META_INDEX).settings(indexSettings);
elasticsearchServer.getClient().admin().indices().create(createRequest).actionGet();
elasticsearchServer.getClient().admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet();
TableMetadataManager tableMetadataManager = Mockito.mock(TableMetadataManager.class);
tableMetadataManager.start();
when(tableMetadataManager.exists(TestUtils.TEST_TABLE)).thenReturn(true);
AnalyticsLoader analyticsLoader = new AnalyticsLoader(dataStore, elasticsearchConnection);
TestUtils.registerActions(analyticsLoader, mapper);
ExecutorService executorService = Executors.newFixedThreadPool(1);
QueryExecutor queryExecutor = new QueryExecutor(analyticsLoader, executorService);
queryStore = new ElasticsearchQueryStore(tableMetadataManager, elasticsearchConnection, dataStore, queryExecutor);
}
@Override
protected void setUpResources() throws Exception {
addResource(new TableFieldMappingResource(queryStore));
}
@After
public void tearDown() throws IOException {
elasticsearchServer.shutdown();
hazelcastInstance.shutdown();
}
@Test
public void testGet() throws Exception {
queryStore.save(TestUtils.TEST_TABLE, TestUtils.getMappingDocuments(mapper));
Thread.sleep(500);
Set<FieldTypeMapping> mappings = new HashSet<FieldTypeMapping>();
mappings.add(new FieldTypeMapping("word", FieldType.STRING));
mappings.add(new FieldTypeMapping("data.data", FieldType.STRING));
mappings.add(new FieldTypeMapping("header.hello", FieldType.STRING));
mappings.add(new FieldTypeMapping("head.hello", FieldType.LONG));
TableFieldMapping tableFieldMapping = new TableFieldMapping(TestUtils.TEST_TABLE, mappings);
String response = client().resource(String.format("/v1/tables/%s/fields", TestUtils.TEST_TABLE))
.get(String.class);
TableFieldMapping mapping = mapper.readValue(response, TableFieldMapping.class);
assertEquals(tableFieldMapping.getTable(), mapping.getTable());
assertTrue(tableFieldMapping.getMappings().equals(mapping.getMappings()));
}
@Test(expected = UniformInterfaceException.class)
public void testGetInvalidTable() throws Exception {
client().resource(String.format("/v1/tables/%s/fields", TestUtils.TEST_TABLE + "-missing"))
.get(String.class);
}
@Test
public void testGetTableWithNoDocument() throws Exception {
TableFieldMapping request = new TableFieldMapping(TestUtils.TEST_TABLE, new HashSet<FieldTypeMapping>());
TableFieldMapping response = client().resource(String.format("/v1/tables/%s/fields", TestUtils.TEST_TABLE))
.get(TableFieldMapping.class);
assertEquals(request.getTable(), response.getTable());
assertTrue(request.getMappings().equals(response.getMappings()));
}
}
| 46.373239 | 122 | 0.764313 |
d149bb59bcd8a23bdda92a99f686bafdf63c7be5 | 652 | package tools;
/**
*
* @author broihier
* <pre>
* Class for creating ExpectedResults objects
* </pre>
*/
public class ExpectedResults extends DatabaseComponent {
/**
* Constructor for creating ExpectedResults objects
*
* @param category name that maps to 'category'.testDbExpectedResults files
*
*/
public ExpectedResults(String category) {
super(category+".testDbExpectedResults");
}
/**
* Method to get the expected results text for a particular testID
* @param testID test case ID
* @return getComponentText(testID)
*/
public String getExpectedResultsText(String testID) {
return getComponentText(testID);
}
}
| 22.482759 | 76 | 0.720859 |
1e5ccfaa49b1b981545a1cd0c39d844fe76b0655 | 6,911 | /*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package pi.orbinit;
import corba.framework.InternalProcess;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Properties;
import org.glassfish.pfl.test.JUnitReportHelper;
import org.omg.CORBA.ORB;
import org.omg.IOP.CodecFactory;
public abstract class ClientCommon
implements InternalProcess
{
JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ;
// Set from run()
private ORB orb;
// Set from run()
private PrintStream out;
// Set from run()
private PrintStream err;
private CodecFactory codecFactory;
public void run( Properties environment, String args[], PrintStream out,
PrintStream err, Hashtable extra)
throws Exception
{
out.println( "Client" );
out.println( "======" );
this.out = out;
this.err = err;
ClientTestInitializer.out = this.out;
this.orb = createORB( args );
ClientTestInitializer.orb = this.orb;
try {
// Test ORBInitializer
testORBInitializer();
// Test ORBInitInfo
testORBInitInfo();
// Test destroy
testDestroy();
} finally {
helper.done() ;
}
}
/**
* Perform ORBInitializer-related tests
*/
private void testORBInitializer() {
helper.start( "testORBInitializer" ) ;
try {
out.println();
out.println( "Testing ORBInitializer" );
out.println( "======================" );
// Ensure the test initializer was initialized appropriately.
out.println( "Verifying testInitializer: " );
if( !ClientTestInitializer.initializedAppropriately() ) {
throw new RuntimeException(
"ClientTestInitializer not initialized appropriately." );
}
out.println( " - initialized appropriately. (ok)" );
if( !ClientTestInitializer.post_post_init() ) {
throw new RuntimeException(
"ORBInitInfo allowed access after post_init." );
}
helper.pass() ;
} catch (RuntimeException exc) {
helper.fail( exc ) ;
throw exc ;
}
}
/**
* Perform ORBInitInfo-related tests
*/
private void testORBInitInfo() {
helper.start( "testORBInitInfo" ) ;
try {
// Any tests on ORBInitInfo are actually done inside the
// ORBInitializer. At this point, we just analyze the results of
// tests that have already run.
out.println();
out.println( "Testing ORBInitInfo" );
out.println( "===================" );
// Analyze resolve_initial_references results
out.println( ClientTestInitializer.resolveInitialReferencesResults );
if( !ClientTestInitializer.passResolveInitialReferences ) {
throw new RuntimeException(
"resolve_initial_references not functioning properly." );
}
else if( !ClientTestInitializer.passResolveInitialReferencesInvalid ) {
throw new RuntimeException(
"resolve_initial_references not raising InvalidName." );
}
// Analyze add_*_interceptor
out.println( "Testing pre_init add interceptor..." );
out.println( ClientTestInitializer.preAddInterceptorResult );
if( !ClientTestInitializer.preAddInterceptorPass ) {
throw new RuntimeException(
"pre_init add interceptor test failed." );
}
out.println( "Testing post_init add interceptor..." );
out.println( ClientTestInitializer.postAddInterceptorResult );
if( !ClientTestInitializer.postAddInterceptorPass ) {
throw new RuntimeException(
"post_init add interceptor test failed." );
}
// Analyze get/set_slot test results
out.println( "Testing get/set slot from within ORBInitializer..." );
out.println( ClientTestInitializer.getSetSlotResult );
if( !ClientTestInitializer.getSetSlotPass ) {
throw new RuntimeException( "get/set slot test failed." );
}
helper.pass() ;
} catch (RuntimeException exc) {
helper.fail( exc ) ;
throw exc ;
}
}
/**
* Test that destroy is called on all interceptors.
*/
private void testDestroy()
throws Exception
{
helper.start( "testDestroy" ) ;
try {
out.println();
out.println( "Testing destroy functionality" );
out.println( "=============================" );
out.println( "Checking destroy counts before calling destroy..." );
int clientCount = SampleClientRequestInterceptor.destroyCount;
int serverCount = SampleServerRequestInterceptor.destroyCount;
int iorCount = SampleIORInterceptor.destroyCount;
checkDestroyCount( "Client", 0, clientCount );
checkDestroyCount( "Server", 0, serverCount );
checkDestroyCount( "IOR", 0, iorCount );
out.println( "Calling ORB.destroy..." );
orb.destroy();
out.println(
"Checking that interceptors' destroy methods were called." );
clientCount = SampleClientRequestInterceptor.destroyCount;
serverCount = SampleServerRequestInterceptor.destroyCount;
iorCount = SampleIORInterceptor.destroyCount;
checkDestroyCount( "Client", 6, clientCount );
checkDestroyCount( "Server", 2, serverCount );
checkDestroyCount( "IOR", 2, iorCount );
helper.pass() ;
} catch (Exception exc) {
helper.fail( exc ) ;
throw exc ;
}
}
/**
* Checks that a single interceptor passed the destroy test
*/
private void checkDestroyCount( String name, int expected, int actual )
throws Exception
{
out.println( "* " + name + " interceptor: Expected " + expected +
" destroys. Received " + actual + "." );
if( expected != actual ) {
throw new RuntimeException(
"Incorrect number of destroys called." );
}
}
abstract protected ORB createORB( String[] args );
}
| 33.548544 | 83 | 0.578498 |
f0f503828a40179020966210173a45baf7f8a3de | 5,667 | package edu.gemini.itc.operation;
import edu.gemini.itc.base.ITCConstants;
import edu.gemini.itc.base.Instrument;
import edu.gemini.itc.base.SampledSpectrumVisitor;
import edu.gemini.itc.base.TransmissionElement;
import edu.gemini.spModel.core.Site;
import edu.gemini.spModel.gemini.obscomp.SPSiteQuality;
/**
* The WaterTransmissionVisitor is designed to adjust the SED for
* water in the atmosphere.
*/
public final class WaterTransmissionVisitor {
private WaterTransmissionVisitor() {
}
public static SampledSpectrumVisitor create(final Instrument instrument, final SPSiteQuality.WaterVapor wv, final double airMass, final String file_name) {
final String name;
switch (instrument.getBands()) {
case VISIBLE:
switch (wv) {
case PERCENT_20:
if (airMass <= 1.25) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "20_" + "10" +
ITCConstants.DATA_SUFFIX;
} else if (airMass > 1.25 && airMass <= 1.75) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "20_" + "15" +
ITCConstants.DATA_SUFFIX;
} else {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "20_" + "20" +
ITCConstants.DATA_SUFFIX;
}
break;
case PERCENT_50:
if (airMass <= 1.25) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "50_" + "10" +
ITCConstants.DATA_SUFFIX;
} else if (airMass > 1.25 && airMass <= 1.75) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "50_" + "15" +
ITCConstants.DATA_SUFFIX;
} else {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "50_" + "20" +
ITCConstants.DATA_SUFFIX;
}
break;
case PERCENT_80:
if (airMass <= 1.25) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "80_" + "10" +
ITCConstants.DATA_SUFFIX;
} else if (airMass > 1.25 && airMass <= 1.75) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "80_" + "15" +
ITCConstants.DATA_SUFFIX;
} else {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "80_" + "20" +
ITCConstants.DATA_SUFFIX;
}
break;
case ANY:
if (airMass <= 1.25) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "100_" + "10" +
ITCConstants.DATA_SUFFIX;
} else if (airMass > 1.25 && airMass <= 1.75) {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "100_" + "15" +
ITCConstants.DATA_SUFFIX;
} else {
name = ITCConstants.TRANSMISSION_LIB + "/" +
file_name + "100_" + "20" +
ITCConstants.DATA_SUFFIX;
}
break;
default:
throw new IllegalArgumentException("unknown WV value");
}
break;
default:
final String _airmassCategory;
final String _transmissionCategory;
if (airMass <= 1.25)
_airmassCategory = "10";
else if (airMass > 1.25 && airMass <= 1.75)
_airmassCategory = "15";
else
_airmassCategory = "20";
switch (wv) {
case PERCENT_20: _transmissionCategory = "20_"; break;
case PERCENT_50: _transmissionCategory = "50_"; break;
case PERCENT_80: _transmissionCategory = "80_"; break;
case ANY: _transmissionCategory = "100_"; break;
default:
throw new IllegalArgumentException("unknown WV value");
}
name = "/HI-Res/" + abbrForSite(instrument.getSite()) + instrument.getBands().getDirectory() + ITCConstants.TRANSMISSION_LIB + "/"
+ file_name + _transmissionCategory + _airmassCategory + ITCConstants.DATA_SUFFIX;
}
return new TransmissionElement(name);
}
private static String abbrForSite(Site site) {
switch (site) {
case GN: return "mk";
case GS: return "cp";
default: throw new IllegalArgumentException();
}
}
}
| 43.592308 | 159 | 0.426857 |
1c199b8fb5d7eb392e95a913255fc7404c396018 | 5,200 |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.porcelli.nio.jgit.impl;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchService;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import me.porcelli.nio.jgit.cluster.ClusterMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JGitFileSystemsEventsManager {
private static final Logger LOGGER = LoggerFactory.getLogger(JGitFileSystemsEventsManager.class);
private final Map<String, JGitFileSystemWatchServices> fsWatchServices = new ConcurrentHashMap<>();
private final ClusterMessageService clusterMessageService;
JGitEventsBroadcast jGitEventsBroadcast;
public JGitFileSystemsEventsManager() {
clusterMessageService = getClusterMessageService();
if (clusterMessageService.isSystemClustered()) {
setupJGitEventsBroadcast();
}
}
ClusterMessageService getClusterMessageService() {
return new ClusterMessageService() {
@Override
public void connect() {
}
@Override
public <T> void createConsumer(DestinationType type, String channel, Class<T> clazz, Consumer<T> listener) {
}
@Override
public void broadcast(DestinationType type, String channel, Serializable object) {
}
@Override
public boolean isSystemClustered() {
return false;
}
@Override
public void close() {
}
};
}
void setupJGitEventsBroadcast() {
jGitEventsBroadcast = new JGitEventsBroadcast(clusterMessageService,
w -> publishEvents(w.getFsName(),
w.getWatchable(),
w.getEvents(),
false));
}
public WatchService newWatchService(String fsName)
throws UnsupportedOperationException, IOException {
fsWatchServices.putIfAbsent(fsName,
createFSWatchServicesManager());
if (jGitEventsBroadcast != null) {
jGitEventsBroadcast.createWatchService(fsName);
}
return fsWatchServices.get(fsName).newWatchService(fsName);
}
JGitFileSystemWatchServices createFSWatchServicesManager() {
return new JGitFileSystemWatchServices();
}
public void publishEvents(String fsName,
Path watchable,
List<WatchEvent<?>> elist) {
publishEvents(fsName,
watchable,
elist,
true);
}
public void publishEvents(String fsName,
Path watchable,
List<WatchEvent<?>> elist,
boolean broadcastEvents) {
JGitFileSystemWatchServices watchService = fsWatchServices.get(fsName);
if (watchService == null) {
return;
}
watchService.publishEvents(watchable,
elist);
if (shouldIBroadcast(broadcastEvents)) {
jGitEventsBroadcast.broadcast(fsName,
watchable,
elist);
}
}
private boolean shouldIBroadcast(boolean broadcastEvents) {
return broadcastEvents && jGitEventsBroadcast != null;
}
public void close(String name) {
JGitFileSystemWatchServices watchService = fsWatchServices.get(name);
if (watchService != null) {
try {
watchService.close();
} catch (final Exception ex) {
LOGGER.error("Can't close watch service [" + toString() + "]",
ex);
}
}
}
public void shutdown() {
fsWatchServices.keySet().forEach(key -> this.close(key));
if (jGitEventsBroadcast != null) {
jGitEventsBroadcast.close();
}
}
JGitEventsBroadcast getjGitEventsBroadcast() {
return jGitEventsBroadcast;
}
Map<String, JGitFileSystemWatchServices> getFsWatchServices() {
return fsWatchServices;
}
}
| 30.409357 | 120 | 0.583269 |
13a4ef19d823ce841007abf34390123608e05fb6 | 412 | package com.example.ticketunion.model.domain;
import java.util.List;
/**
* @ProjectName: TicketUnion
* @Author: Tz
* @CreateDate: 2020/6/2 21:05
* God bless my code!
*/
public class Histories {
private List<String> histories;
public List<String> getHistories() {
return histories;
}
public void setHistories(List<String> histories) {
this.histories = histories;
}
}
| 17.913043 | 54 | 0.662621 |
25d8dddab1628ac26e5391bec579e68f90650a8c | 188 | package fudge.tasks;
import net.minecraft.entity.player.PlayerEntity;
@FunctionalInterface
public interface Reward {
void provide(PlayerEntity rewardedPlayer, Task rewardingTask);
}
| 20.888889 | 66 | 0.81383 |
da2a47cb7e054f67b0a9f317a73dc74f4234e400 | 505 | package com.didispace;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
@Slf4j
public class ApplicationEnvironmentPreparedEventListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
log.info("......ApplicationEnvironmentPreparedEvent......");
}
}
| 31.5625 | 126 | 0.817822 |
99711044be0a5cad7ffb9457d9bfc351128828b9 | 3,906 | package naef.ui;
import tef.MVO;
import tef.TransactionContext;
import tef.TransactionId;
import tef.skelton.AuthenticationException;
import tef.skelton.Model;
import tef.skelton.SkeltonTefService;
import tef.skelton.dto.DtoChanges;
import tef.skelton.dto.DtoOriginator;
import tef.skelton.dto.EntityDto;
import tef.ui.shell.InternalShellInvocation;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public interface NaefShellFacade extends Remote {
public static class ShellException extends Exception {
private final String command_;
private final Integer batchLineCount_;
public ShellException(String command, Integer batchLineCount, String message) {
super(message);
command_ = command;
batchLineCount_ = batchLineCount;
}
public String getCommand() {
return command_;
}
public Integer getBatchLineCount() {
return batchLineCount_;
}
}
public DtoChanges executeBatch(List<String> commands)
throws AuthenticationException, ShellException, RemoteException;
public class Impl extends NaefRmiFacade.Impl implements NaefShellFacade {
private final DtoOriginator originator_;
public Impl(DtoOriginator originator) throws RemoteException {
originator_ = originator;
}
@Override public DtoChanges executeBatch(List<String> commands)
throws AuthenticationException, ShellException
{
DtoChanges result;
InternalShellInvocation shellInvocation = new InternalShellInvocation();
try {
beginWriteTransaction();
try {
shellInvocation.processBatch(commands.toArray(new String[0]));
Set<MVO> newMvos = new HashSet<MVO>(TransactionContext.getNewObjects());
Set<MVO> changedMvos = new HashSet<MVO>(TransactionContext.getChangedObjects());
changedMvos.removeAll(newMvos);
Set<EntityDto> newDtos = buildDtos(newMvos);
Set<EntityDto> changedDtos = buildDtos(changedMvos);
TransactionId.W version = (TransactionId.W) TransactionContext.getTransactionId();
result = new DtoChanges(
originator_,
version,
version,
TransactionContext.getTargetTime(),
newDtos,
changedDtos);
commitTransaction();
} finally {
closeTransaction();
}
} catch (InternalShellInvocation.InvocationException ie) {
throw new ShellException(ie.getCommand(), ie.getBatchLineCount(), ie.getMessage());
} finally {
try {
shellInvocation.close();
} catch (IOException ioe) {
tef.TefService.instance().logError("internal shell invocation", ioe);
throw new RuntimeException(ioe);
}
}
return result;
}
private Set<EntityDto> buildDtos(Collection<MVO> mvos) {
SkeltonTefService tefService = SkeltonTefService.instance();
Set<EntityDto> result = new HashSet<EntityDto>();
for (MVO mvo : mvos) {
if ((mvo instanceof Model)
&& tefService.getMvoDtoMapping().hasDtoMapping((Class<? extends Model>) mvo.getClass()))
{
result.add(tefService.getMvoDtoFactory().build(originator_, mvo));
}
}
return result;
}
}
}
| 33.965217 | 108 | 0.595494 |
d4f03e11b34ade456b8ab9bc9d8eafd33eb5dba1 | 998 | package com.wuda.web.model.constant;
/**
* 路径常量.
*
* @author wuda
*/
public class PathConstant {
/**
* 禁止实例化.
*/
private PathConstant() {
}
/**
* rest接口的path context.
*/
public final static String PATH_CONTEXT_REST = "/rest";
/**
* mvc接口的path context.
*/
public final static String PATH_CONTEXT_MVC = "/controller";
public final static String MVC_SYSTEM_CONTROLLER = "/system";
public final static String MVC_SYSTEM_CONTROLLER_PING = PATH_CONTEXT_MVC + MVC_SYSTEM_CONTROLLER + "/ping";
public final static String MVC_SYSTEM_CONTROLLER_PING_MYSQL = PATH_CONTEXT_MVC + MVC_SYSTEM_CONTROLLER + "/ping/mysql";
public final static String REST_SYSTEM_CONTROLLER = "/system";
public final static String REST_SYSTEM_CONTROLLER_PING = PATH_CONTEXT_REST + REST_SYSTEM_CONTROLLER + "/ping";
public final static String REST_SYSTEM_CONTROLLER_PING_MYSQL = PATH_CONTEXT_REST + REST_SYSTEM_CONTROLLER + "/ping/mysql";
}
| 28.514286 | 126 | 0.709419 |
34a29e35b9f58ff20d96d65e8ac2dbd5dc78cba2 | 333 | package com.aaxis.rnsecurestorage.exceptions;
/**
* Created by zacharyhou on 2019/11/22.
*/
public class CryptoFailedException extends Exception {
public CryptoFailedException(String message) {
super(message);
}
public CryptoFailedException(String message, Throwable t) {
super(message, t);
}
}
| 19.588235 | 63 | 0.696697 |
79def2626ba7984df83af4a903475f03b6ba2b89 | 1,313 | package com.xiaomi.push.log;
import java.io.File;
import java.util.Date;
class c extends b {
File a;
final /* synthetic */ int b;
final /* synthetic */ Date c;
final /* synthetic */ Date d;
final /* synthetic */ String e;
final /* synthetic */ String f;
final /* synthetic */ boolean g;
final /* synthetic */ b h;
c(b bVar, int i, Date date, Date date2, String str, String str2, boolean z) {
this.h = bVar;
this.b = i;
this.c = date;
this.d = date2;
this.e = str;
this.f = str2;
this.g = z;
super(bVar);
}
public void b() {
if (com.xiaomi.channel.commonutils.file.c.d()) {
try {
File file = new File(this.h.b.getExternalFilesDir(null) + "/.logcache");
file.mkdirs();
if (file.isDirectory()) {
a aVar = new a();
aVar.a(this.b);
this.a = aVar.a(this.h.b, this.c, this.d, file);
}
} catch (NullPointerException e) {
}
}
}
public void c() {
if (this.a != null && this.a.exists()) {
this.h.a.add(new c(this.h, this.e, this.f, this.a, this.g));
}
this.h.a(0);
}
}
| 26.795918 | 88 | 0.46687 |
3bc3df3104e484601e3a5e270b791b844ae23f61 | 337 | package com.atharva.encryptchat.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Friend implements Serializable {
private String name;
private String phoneNo;
private String publicKey;
}
| 16.85 | 45 | 0.79822 |
b3467c9ea2830361d04afbccd8043b24867838ff | 220 | package com.oukingtim.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.oukingtim.domain.File;
/**
* Created by xufan on 2018/03/19.
*/
public interface MgrFileMapper extends BaseMapper<File> {
}
| 20 | 57 | 0.772727 |
d355e65128ab72cc07b5d7a9288f375f874a11f1 | 1,514 | /**
* Copyright (C) 2007 Google 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 safesax;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.IOException;
import java.io.Reader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
/**
* Parsing utility methods.
*/
public class Parsers {
/**
* Parses XML from the given reader with namespace support enabled.
*/
public static void parse(Reader in, ContentHandler contentHandler)
throws SAXException, IOException {
try {
XMLReader reader
= SAXParserFactory.newInstance().newSAXParser().getXMLReader();
reader.setFeature("http://xml.org/sax/features/namespaces", true);
reader.setContentHandler(contentHandler);
reader.parse(new InputSource(in));
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
}
| 29.686275 | 75 | 0.731836 |
f91955e8da6038b69ef7ef8235c943677483d46d | 3,315 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceAnalysis;
import org.bian.dto.BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceReport;
import javax.validation.Valid;
/**
* BQMaintenanceAndUpgradeRetrieveInputModel
*/
public class BQMaintenanceAndUpgradeRetrieveInputModel {
private Object maintenanceAndUpgradeRetrieveActionTaskRecord = null;
private String maintenanceAndUpgradeRetrieveActionRequest = null;
private BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceReport maintenanceAndUpgradeInstanceReport = null;
private BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceAnalysis maintenanceAndUpgradeInstanceAnalysis = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record
* @return maintenanceAndUpgradeRetrieveActionTaskRecord
**/
public Object getMaintenanceAndUpgradeRetrieveActionTaskRecord() {
return maintenanceAndUpgradeRetrieveActionTaskRecord;
}
public void setMaintenanceAndUpgradeRetrieveActionTaskRecord(Object maintenanceAndUpgradeRetrieveActionTaskRecord) {
this.maintenanceAndUpgradeRetrieveActionTaskRecord = maintenanceAndUpgradeRetrieveActionTaskRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service request (lists requested reports)
* @return maintenanceAndUpgradeRetrieveActionRequest
**/
public String getMaintenanceAndUpgradeRetrieveActionRequest() {
return maintenanceAndUpgradeRetrieveActionRequest;
}
public void setMaintenanceAndUpgradeRetrieveActionRequest(String maintenanceAndUpgradeRetrieveActionRequest) {
this.maintenanceAndUpgradeRetrieveActionRequest = maintenanceAndUpgradeRetrieveActionRequest;
}
/**
* Get maintenanceAndUpgradeInstanceReport
* @return maintenanceAndUpgradeInstanceReport
**/
public BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceReport getMaintenanceAndUpgradeInstanceReport() {
return maintenanceAndUpgradeInstanceReport;
}
public void setMaintenanceAndUpgradeInstanceReport(BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceReport maintenanceAndUpgradeInstanceReport) {
this.maintenanceAndUpgradeInstanceReport = maintenanceAndUpgradeInstanceReport;
}
/**
* Get maintenanceAndUpgradeInstanceAnalysis
* @return maintenanceAndUpgradeInstanceAnalysis
**/
public BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceAnalysis getMaintenanceAndUpgradeInstanceAnalysis() {
return maintenanceAndUpgradeInstanceAnalysis;
}
public void setMaintenanceAndUpgradeInstanceAnalysis(BQMaintenanceAndUpgradeRetrieveInputModelMaintenanceAndUpgradeInstanceAnalysis maintenanceAndUpgradeInstanceAnalysis) {
this.maintenanceAndUpgradeInstanceAnalysis = maintenanceAndUpgradeInstanceAnalysis;
}
}
| 39.939759 | 195 | 0.854299 |
c43018cc4e16c68b648a4799e31548fcc60fc5d1 | 997 | package ca.corefacility.bioinformatics.irida.service.remote;
import ca.corefacility.bioinformatics.irida.model.assembly.GenomeAssembly;
import ca.corefacility.bioinformatics.irida.model.assembly.UploadedAssembly;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import java.util.List;
/**
* A service for reading {@link UploadedAssembly}s from a remote location
*/
public interface GenomeAssemblyRemoteService extends RemoteService<UploadedAssembly> {
/**
* List the {@link GenomeAssembly} for a given {@link Sample}
*
* @param sample the Sample to get assemblies for
* @return a list of {@link UploadedAssembly}
*/
public List<UploadedAssembly> getGenomeAssembliesForSample(Sample sample);
/**
* Download the given {@link UploadedAssembly} to the local server
*
* @param seqObject the {@link UploadedAssembly} to download
* @return a local copy of the {@link UploadedAssembly}
*/
public UploadedAssembly mirrorAssembly(UploadedAssembly seqObject);
}
| 34.37931 | 86 | 0.781344 |
aeec3d7606d78fd56c116132a65e6bd983ba4abb | 3,989 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/eventarc/v1/eventarc.proto
package com.google.cloud.eventarc.v1;
public interface ListTriggersResponseOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.eventarc.v1.ListTriggersResponse)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The requested triggers, up to the number specified in `page_size`.
* </pre>
*
* <code>repeated .google.cloud.eventarc.v1.Trigger triggers = 1;</code>
*/
java.util.List<com.google.cloud.eventarc.v1.Trigger> getTriggersList();
/**
*
*
* <pre>
* The requested triggers, up to the number specified in `page_size`.
* </pre>
*
* <code>repeated .google.cloud.eventarc.v1.Trigger triggers = 1;</code>
*/
com.google.cloud.eventarc.v1.Trigger getTriggers(int index);
/**
*
*
* <pre>
* The requested triggers, up to the number specified in `page_size`.
* </pre>
*
* <code>repeated .google.cloud.eventarc.v1.Trigger triggers = 1;</code>
*/
int getTriggersCount();
/**
*
*
* <pre>
* The requested triggers, up to the number specified in `page_size`.
* </pre>
*
* <code>repeated .google.cloud.eventarc.v1.Trigger triggers = 1;</code>
*/
java.util.List<? extends com.google.cloud.eventarc.v1.TriggerOrBuilder>
getTriggersOrBuilderList();
/**
*
*
* <pre>
* The requested triggers, up to the number specified in `page_size`.
* </pre>
*
* <code>repeated .google.cloud.eventarc.v1.Trigger triggers = 1;</code>
*/
com.google.cloud.eventarc.v1.TriggerOrBuilder getTriggersOrBuilder(int index);
/**
*
*
* <pre>
* A page token that can be sent to ListTriggers to request the next page.
* If this is empty, then there are no more pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
java.lang.String getNextPageToken();
/**
*
*
* <pre>
* A page token that can be sent to ListTriggers to request the next page.
* If this is empty, then there are no more pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
com.google.protobuf.ByteString getNextPageTokenBytes();
/**
*
*
* <pre>
* Unreachable resources, if any.
* </pre>
*
* <code>repeated string unreachable = 3;</code>
*
* @return A list containing the unreachable.
*/
java.util.List<java.lang.String> getUnreachableList();
/**
*
*
* <pre>
* Unreachable resources, if any.
* </pre>
*
* <code>repeated string unreachable = 3;</code>
*
* @return The count of unreachable.
*/
int getUnreachableCount();
/**
*
*
* <pre>
* Unreachable resources, if any.
* </pre>
*
* <code>repeated string unreachable = 3;</code>
*
* @param index The index of the element to return.
* @return The unreachable at the given index.
*/
java.lang.String getUnreachable(int index);
/**
*
*
* <pre>
* Unreachable resources, if any.
* </pre>
*
* <code>repeated string unreachable = 3;</code>
*
* @param index The index of the value to return.
* @return The bytes of the unreachable at the given index.
*/
com.google.protobuf.ByteString getUnreachableBytes(int index);
}
| 25.570513 | 96 | 0.646027 |
4b45bb14c300de2f68e253c0ba0d13ef7947a8de | 4,217 | package org.radarcns.service;
import static org.radarcns.util.ThrowingFunction.tryOrRethrow;
import java.io.IOException;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.ws.rs.NotFoundException;
import org.radarcns.domain.managementportal.SubjectDTO;
import org.radarcns.domain.restapi.Source;
import org.radarcns.domain.restapi.Subject;
import org.radarcns.domain.restapi.header.TimeFrame;
import org.radarcns.listener.managementportal.ManagementPortalClient;
import org.radarcns.webapp.exception.BadGatewayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SubjectService {
private static final Logger LOGGER = LoggerFactory.getLogger(SubjectService.class);
private final ManagementPortalClient managementPortalClient;
private final SourceService sourceService;
/**
* Default constructor. Injects all dependencies.
*
* @param managementPortalClient instance
* @param sourceService instance
*/
@Inject
public SubjectService(ManagementPortalClient managementPortalClient,
SourceService sourceService) {
this.managementPortalClient = managementPortalClient;
this.sourceService = sourceService;
}
/**
* Checks whether given source-id is available in the sources available for the subject.
*
* @param subjectId of subject
* @param sourceId of source
* @throws IOException when unable to process the request.
*/
public void checkSourceAssignedToSubject(String subjectId, String sourceId)
throws IOException {
SubjectDTO subject = managementPortalClient.getSubject(subjectId);
if (subject.getSources().stream()
.map(s -> s.getSourceId().toString())
.noneMatch(sourceId::equals)) {
LOGGER.error("Cannot find source-id " + sourceId + "for subject" + subject.getId());
throw new NotFoundException(
"Source-id " + sourceId + " is not found for subject "
+ subject.getId());
}
}
private Subject buildSubject(SubjectDTO subject)
throws IOException {
List<Source> sources = this.sourceService.getAllSourcesOfSubject(subject.getProject()
.getProjectName(), subject.getId());
return new Subject()
.subjectId(subject.getId())
.projectName(subject.getProject().getProjectName())
.status(subject.getStatus())
.humanReadableId(subject.getHumanReadableIdentifier())
.sources(sources)
.lastSeen(getLastSeenForSubject(sources));
}
private Instant getLastSeenForSubject(List<Source> sources) {
return sources.stream()
.map(Source::getEffectiveTimeFrame)
.filter(Objects::nonNull)
.map(TimeFrame::getEndDateTime)
.filter(Objects::nonNull)
.max(Comparator.naturalOrder())
.orElse(null);
}
/**
* Returns list of {@link Subject} available under given project.
*
* @param projectName of project
* @return list of subjects.
* @throws IOException when unable to process
* @throws NotFoundException when given parameters are not available in the database.
*/
public List<Subject> getAllSubjectsFromProject(String projectName)
throws IOException, NotFoundException {
// returns NotFound if a project is not available
this.managementPortalClient.getProject(projectName);
return this.managementPortalClient.getAllSubjectsFromProject(projectName).stream()
.map(tryOrRethrow(this::buildSubject, BadGatewayException::new))
.collect(Collectors.toList());
}
public Subject getSubjectBySubjectId(String projectName, String subjectId)
throws IOException, NotFoundException {
this.managementPortalClient.getProject(projectName);
return this.buildSubject(this.managementPortalClient.getSubject(subjectId));
}
}
| 38.688073 | 96 | 0.682001 |
66f6fb05d5c36b3c3e57eb76953f3fd2d0bba81b | 2,268 | /*
* 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 io.hops.util.featurestore.ops.read_ops;
import io.hops.util.FeaturestoreRestClient;
import io.hops.util.exceptions.FeaturegroupDoesNotExistError;
import io.hops.util.exceptions.FeaturegroupMetadataError;
import io.hops.util.exceptions.FeaturestoreNotFound;
import io.hops.util.featurestore.ops.FeaturestoreOp;
import javax.xml.bind.JAXBException;
import java.util.HashMap;
import java.util.Map;
public class FeaturestoreGetMetadataForFeaturegroup extends FeaturestoreOp {
private String[] keys;
public FeaturestoreGetMetadataForFeaturegroup(String name) {
super(name);
}
@Override
public Object read() throws FeaturestoreNotFound, JAXBException,
FeaturegroupDoesNotExistError, FeaturegroupMetadataError {
if (keys == null || keys.length == 0) {
return FeaturestoreRestClient.getMetadata(getName(), getFeaturestore(),
getVersion(), null);
} else {
Map<String, String> results = new HashMap<>();
for (String key : keys) {
results.putAll(FeaturestoreRestClient.getMetadata(getName(),
getFeaturestore(), getVersion(), key));
}
return results;
}
}
@Override
public void write() {
throw new UnsupportedOperationException(
"write() is not supported on a read operation");
}
public FeaturestoreGetMetadataForFeaturegroup setFeaturestore(
String featurestore) {
this.featurestore = featurestore;
return this;
}
public FeaturestoreGetMetadataForFeaturegroup setVersion(int version) {
this.version = version;
return this;
}
public FeaturestoreGetMetadataForFeaturegroup setKeys(String... keys) {
this.keys = keys;
return this;
}
}
| 31.5 | 77 | 0.729277 |
fff9843cae6add0e79be5810a545efccd469aed6 | 11,538 | package com.github.sukhvir41.core.classgenerator;
import com.github.sukhvir41.core.template.Template;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static com.github.sukhvir41.utils.StringUtils.getIndentations;
public class RuntimeClassGenerator extends TemplateClassGenerator {
public RuntimeClassGenerator(String packageName, String className) {
super(packageName, className);
}
@Override
public String render() {
StringBuilder classString = new StringBuilder();
appendPackageName(classString);
appendImports(classString);
appendOpeningClass(classString);
// appending static variables and methods
appendPlainHtmlVariables(classString);
appendGetInstanceMethod(classString);
// appending writer initial size;
appendWriterInitialSize(classString);
//instance variables and methods
appendVariableDeclaration(classString);
appendGetter(classString);
appendSetter(classString);
appendRenderImpl(classString);
appendRenderSubTemplateImpl(classString);
appendClosingClass(classString);
return classString.toString();
}
private void appendPackageName(StringBuilder classString) {
classString.append("package ")
.append(getPackageName())
.append(";")
.append(BREAK_LINE)
.append(BREAK_LINE);
}
private void appendImports(StringBuilder classString) {
getImports()
.stream()
.map(importPackage -> "import " + importPackage + ";" + BREAK_LINE)
.forEach(classString::append);
classString.append(BREAK_LINE)
.append(BREAK_LINE);
}
private void appendOpeningClass(StringBuilder classString) {
classString.append("public class ")
.append(getClassName())
.append(" extends ")
.append(SUPER_CLASS)
.append(" {")
.append(BREAK_LINE)
.append(BREAK_LINE);
}
private void appendPlainHtmlVariables(StringBuilder classString) {
Map<StringBuilder, Integer> uniquePlainHtmlVariables = new HashMap<>();
getPlainHtmlVariables()
.forEach((name, value) -> uniquePlainHtmlVariables.putIfAbsent(value, name));
getPlainHtmlVariables()
.forEach(
(name, value) -> {
classString.append(getIndentations(1))
.append("private static final String ")
.append(PLAIN_HTML_VARIABLE_PREFIX)
.append(name)
.append(" = ")
.append(getPlainHtmlValue(name, value, uniquePlainHtmlVariables))
.append(";")
.append(BREAK_LINE);
}
);
classString.append(BREAK_LINE);
}
private StringBuilder getPlainHtmlValue(int name, StringBuilder value, Map<StringBuilder, Integer> uniquePlainHtmlVariables) {
if (uniquePlainHtmlVariables.containsKey(value) && uniquePlainHtmlVariables.containsValue(name)) {
return new StringBuilder("\"")
.append(value)
.append("\"");
} else {
return new StringBuilder(PLAIN_HTML_VARIABLE_PREFIX)
.append(uniquePlainHtmlVariables.get(value));
}
}
private void appendGetInstanceMethod(StringBuilder classString) {
classString.append(getIndentations(1))
.append("public static final ")
.append(getClassName())
.append(" getInstance() {")
.append(BREAK_LINE)
.append(getIndentations(2))
.append("return new ")
.append(getClassName())
.append("();")
.append(BREAK_LINE)
.append(getIndentations(1))
.append("}")
.append(BREAK_LINE)
.append(BREAK_LINE);
}
public void appendWriterInitialSize(StringBuilder classString) {
long size = getPlainHtmlVariables()
.values()
.stream()
.mapToLong(builder -> builder.length())
.sum()*2;
if (size > Integer.MAX_VALUE) {
size = Integer.MAX_VALUE;
}
classString.append(getIndentations(1))
.append("@Override")
.append(BREAK_LINE)
.append(getIndentations(1))
.append("public int writerInitialSize() {")
.append(BREAK_LINE)
.append(getIndentations(2))
.append("return ")
.append(size)
.append(";")
.append(BREAK_LINE)
.append(getIndentations(1))
.append("}")
.append(BREAK_LINE)
.append(BREAK_LINE);
}
private void appendVariableDeclaration(StringBuilder classString) {
getVariables(getRootTemplate())
.forEach((name, type) ->
classString.append(getIndentations(1))
.append("private ")
.append(covertFromPrimitiveToObjectType(type))
.append(" ")
.append(name)
.append(";")
.append(BREAK_LINE)
);
classString.append(BREAK_LINE);
}
private String covertFromPrimitiveToObjectType(String type) {
switch (type) {
case "byte":
return "Byte";
case "short":
return "Short";
case "int":
return "Integer";
case "long":
return "Long";
case "float":
return "Float";
case "double":
return "Double";
case "char":
return "Character";
case "boolean":
return "Boolean";
default:
return type;
}
}
private void appendGetter(StringBuilder classString) {
getVariables(getRootTemplate())
.forEach((name, type) ->
classString.append(getIndentations(1))
.append("private ")
.append(covertFromPrimitiveToObjectType(type))
.append(" ")
.append(name)
.append("() {")
.append(BREAK_LINE)
.append(getIndentations(2))
.append("return ")
.append(name)
.append(";")
.append(BREAK_LINE)
.append(getIndentations(1))
.append("}")
.append(BREAK_LINE)
.append(BREAK_LINE)
);
}
private void appendSetter(StringBuilder classString) {
getVariables(getRootTemplate())
.forEach((name, type) ->
classString.append(getIndentations(1))
.append("public ")
.append(getClassName())
.append(" ")
.append(name)
.append("(")
.append(covertFromPrimitiveToObjectType(type))
.append(" ")
.append(name)
.append(") {")
.append(BREAK_LINE)
.append(getIndentations(2))
.append("this.")
.append(name)
.append(" = ")
.append(name)
.append(";")
.append(BREAK_LINE)
.append(getIndentations(2))
.append("return this;")
.append(BREAK_LINE)
.append(getIndentations(1))
.append("}")
.append(BREAK_LINE)
.append(BREAK_LINE)
);
}
private void appendRenderImpl(StringBuilder classString) {
classString.append(getIndentations(1))
.append("@Override")
.append(BREAK_LINE)
.append(getIndentations(1))
.append("public void renderImpl(Writer ")
.append(getWriterVariableName())
.append(") throws IOException {")
.append(BREAK_LINE)
.append(renderCallRootTemplateRenderFunction())
.append(BREAK_LINE)
.append(getIndentations(1))
.append("}")
.append(BREAK_LINE)
.append(BREAK_LINE);
}
private StringBuilder renderCallRootTemplateRenderFunction() {
return this.getTemplateDataMap()
.get(getRootTemplate())
.getRenderFunctionBody();
}
private void appendRenderSubTemplateImpl(StringBuilder classString) {
getTemplateDataMap()
.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals(getRootTemplate()))
.forEachOrdered(entry -> renderSubTemplateFunction(classString, entry.getKey(), entry.getValue()));
}
private void renderSubTemplateFunction(StringBuilder classString, Template template, TemplateData templateData) {
classString.append(getIndentations(1))
.append("private void ")
.append(template.getFullyQualifiedName())
.append("(")
.append(getSubTemplateParameters(templateData))
.append(") throws IOException {")
.append(BREAK_LINE)
.append(templateData.getRenderFunctionBody())
.append(BREAK_LINE)
.append(getIndentations(1))
.append("}")
.append(BREAK_LINE)
.append(BREAK_LINE);
}
private StringBuilder getSubTemplateParameters(TemplateData templateData) {
return new StringBuilder("Writer ")
.append(getWriterVariableName())
.append(",")
.append(
templateData.getVariables()
.entrySet()
.stream()
.map(entry -> " " + entry.getValue() + " " + entry.getKey())
.collect(Collectors.joining(","))
);
}
private void appendClosingClass(StringBuilder classString) {
classString.append("}");
}
}
| 36.512658 | 130 | 0.483273 |
2d6a85e2a4ed670d78b0f5d431f662e2510b47c9 | 12,911 | /*
* 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 dex.counter;
import info.persistent.dex.DexMethodCounts;
import java.awt.FileDialog;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author kasper
*/
public class mainWindow extends javax.swing.JFrame {
/**
* Creates new form mainWindow
*/
public mainWindow() {
initComponents();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jCheckBox1 = new javax.swing.JCheckBox();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jSpinner1 = new javax.swing.JSpinner();
jLabel3 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Dex counter");
setModalExclusionType(java.awt.Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
setResizable(false);
jLabel1.setText("File");
jButton1.setText("...");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setToolTipText("the path");
jCheckBox1.setText(" Treat classes as packages ");
jLabel2.setText("Only consider methods whose fullly qualified name starts with this prefix.");
jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
jLabel3.setText("Limit depth");
jButton2.setText("run");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "all", "defined only", "referenced only", " " }));
jLabel4.setText("filter");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jCheckBox1)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField2)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox1, 0, 166, Short.MAX_VALUE)
.addComponent(jSpinner1))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jButton1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Android application", "apk");
fc.setFileFilter(filter);
int showOpenDialog = fc.showOpenDialog(this);
if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
jTextField1.setText(fc.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
jButton2.setEnabled(false);
jProgressBar1.setIndeterminate(true);
jProgressBar1.setEnabled(true);
Thread newThread = new Thread(() -> {
runWithSettings();
SwingUtilities.invokeLater(() -> {
jProgressBar1.setEnabled(false);
jProgressBar1.setIndeterminate(false);
jProgressBar1.setValue(0);
jButton2.setEnabled(true);
});
});
newThread.start();
}//GEN-LAST:event_jButton2ActionPerformed
private void runWithSettings() {
int val = (int) jSpinner1.getValue();
if (val == 0) {
val = Integer.MAX_VALUE;
}
DexMethodCounts.Filter currentFilter;
switch (jComboBox1.getSelectedIndex()) {
case 1:
currentFilter = DexMethodCounts.Filter.DEFINED_ONLY;
break;
case 2:
currentFilter = DexMethodCounts.Filter.REFERENCED_ONLY;
break;
default:
currentFilter = DexMethodCounts.Filter.ALL;
break;
}
String filterText = null;
if (jTextField2.getText().trim().length() > 0) {
filterText = jTextField2.getText().trim();
}
DexHandler dexHandler = new DexHandler(this);
try {
dexHandler.run(jTextField1.getText(), jCheckBox1.isSelected(), filterText, val, currentFilter);
} catch (IOException ex) {
Logger.getLogger(mainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
new mainWindow().setVisible(true);
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
}
| 48.355805 | 165 | 0.645109 |
d605a61b2f21a6c22d20b6b7a7f6fe230e752342 | 28,909 | package mandarin.packpack.supporter.server.holder;
import common.io.assets.UpdateCheck;
import common.system.files.VFile;
import common.util.Data;
import common.util.anim.MaAnim;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Attachment;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.channel.MessageChannel;
import mandarin.packpack.commands.Command;
import mandarin.packpack.supporter.StaticStore;
import mandarin.packpack.supporter.bc.AnimMixer;
import mandarin.packpack.supporter.bc.EntityHandler;
import mandarin.packpack.supporter.bc.cell.AbilityData;
import mandarin.packpack.supporter.bc.cell.CellData;
import mandarin.packpack.supporter.bc.CustomMaskUnit;
import mandarin.packpack.supporter.bc.DataToString;
import mandarin.packpack.supporter.bc.cell.FlagCellData;
import mandarin.packpack.supporter.lang.LangID;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("ForLoopReplaceableByForEach")
public class StatAnalyzerMessageHolder extends MessageHolder<MessageCreateEvent> {
private enum FILE {
STAT(-1),
LEVEL(-1),
BUY(-1),
ANIM(0),
ICON(0);
int index;
FILE(int ind) {
index = ind;
}
public void setIndex(int ind) {
index = ind;
}
}
private final List<CellData> cellData;
private final List<AbilityData> procData;
private final List<FlagCellData> abilityData;
private final List<FlagCellData> traitData;
private final int lang;
private final Message msg;
private final String channelID;
private final File container;
private final int uID;
private final boolean isSecond;
private final int lv;
private final String[] name;
private boolean statDone = false;
private boolean levelDone = false;
private boolean buyDone = false;
private final boolean[] animDone;
private final boolean[] iconDone;
private final AtomicReference<String> stat;
private final AtomicReference<String> level = new AtomicReference<>("LEVEL_CURVE (unitlevel.csv) : -");
private final AtomicReference<String> buy = new AtomicReference<>("BUY (unitbuy.csv) : -");
private final List<AtomicReference<String>> anim = new ArrayList<>();
private final List<AtomicReference<String>> icon = new ArrayList<>();
public StatAnalyzerMessageHolder(Message msg, Message author, int uID, int len, boolean isSecond, List<CellData> cellData, List<AbilityData> procData, List<FlagCellData> abilityData, List<FlagCellData> traitData, String channelID, File container, int lv, String[] name, int lang) throws Exception {
super(MessageCreateEvent.class);
this.cellData = cellData;
this.abilityData = abilityData;
this.procData = procData;
this.traitData = traitData;
this.lang = lang;
this.msg = msg;
this.channelID = channelID;
this.container = container;
this.uID = uID;
this.isSecond = isSecond;
this.lv = lv;
this.name = name;
animDone = new boolean[len];
iconDone = new boolean[len];
for(int i = 0; i < len; i++) {
anim.add(new AtomicReference<>(getMaanimTitle(i) + "-"));
icon.add(new AtomicReference<>(getIconTitle(i) + "-"));
}
stat = new AtomicReference<>("STAT (unit"+Data.trio(uID+1)+".csv) : -");
AtomicReference<Long> now = new AtomicReference<>(System.currentTimeMillis());
if(!author.getAttachments().isEmpty()) {
for(Attachment a : author.getAttachments()) {
if(a.getFilename().equals("unit"+ Data.trio(uID+1)+".csv") && !statDone) {
downloadAndValidate("STAT (unit"+ Data.trio(uID+1)+".csv) : ", a, FILE.STAT, now);
} else if(a.getFilename().equals("unitlevel.csv") && !levelDone) {
downloadAndValidate("LEVEL (unitlevel.csv) : ", a, FILE.LEVEL, now);
} else if(a.getFilename().endsWith("02.maanim")) {
int index = getIndexOfMaanim(a.getFilename());
if(index != -1) {
FILE.ANIM.setIndex(index);
if(index == 0 && a.getFilename().equals(Data.trio(uID)+"_f02.maanim")) {
downloadAndValidate(getMaanimTitle(index), a, FILE.ANIM, now);
} else if(index == 1 && a.getFilename().equals(Data.trio(uID)+"_c02.maanim")) {
downloadAndValidate(getMaanimTitle(index), a, FILE.ANIM, now);
} else if(index == 2 && a.getFilename().equals(Data.trio(uID)+"_s02.maanim")) {
downloadAndValidate(getMaanimTitle(index), a, FILE.ANIM, now);
}
}
} else if(a.getFilename().endsWith(".png") && getIndexOfIcon(a.getFilename()) != -1) {
int index = getIndexOfIcon(a.getFilename());
FILE.ICON.setIndex(index);
if(index == 0 && a.getFilename().equals("uni"+ Data.trio(uID)+"_f00.png")) {
downloadAndValidate(getIconTitle(index), a, FILE.ICON, now);
} else if(index == 1 && a.getFilename().equals("uni"+ Data.trio(uID)+"_c00.png")) {
downloadAndValidate(getIconTitle(index), a, FILE.ICON, now);
} else if(index == 2 && a.getFilename().equals("uni"+ Data.trio(uID)+"_s00.png")) {
downloadAndValidate(getIconTitle(index), a, FILE.ICON, now);
}
} else if(a.getFilename().equals("unitbuy.csv") && !buyDone) {
downloadAndValidate("BUY (unitbuy.csv) : ", a, FILE.BUY, now);
}
}
}
if(allDone()) {
new Thread(() -> {
Guild g = msg.getGuild().block();
if(g == null) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
try {
CustomMaskUnit[] units = new CustomMaskUnit[anim.size()];
File statFile = new File(container, "unit"+Data.trio(uID+1)+".csv");
File levelFile = new File(container, "unitlevel.csv");
File buyFile = new File(container, "unitbuy.csv");
if(!statFile.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Stat file isn't existing even though code finished validation : "+statFile.getAbsolutePath());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
if(!levelFile.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Level curve file isn't existing even though code finished validation : "+levelFile.getAbsolutePath());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
if(!buyFile.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Unit buy file isn't existing even though code finished validation : "+buyFile.getAbsolutePath());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
BufferedReader statReader = new BufferedReader(new FileReader(statFile, StandardCharsets.UTF_8));
BufferedReader levelReader = new BufferedReader(new FileReader(levelFile, StandardCharsets.UTF_8));
BufferedReader buyReader = new BufferedReader(new FileReader(buyFile, StandardCharsets.UTF_8));
int count = 0;
while(count < uID) {
levelReader.readLine();
buyReader.readLine();
count++;
}
String[] curve = levelReader.readLine().split(",");
String[] rare = buyReader.readLine().split(",");
levelReader.close();
buyReader.close();
System.gc();
for(int i = 0; i < units.length; i++) {
File maanim = new File(container, getMaanimFileName(i));
if(!maanim.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Maanim file isn't existing even though code finished validation : "+maanim.getAbsolutePath());
statReader.close();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
VFile vf = VFile.getFile(maanim);
if(vf == null) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Failed to generate vFile of maanim : "+maanim.getAbsolutePath());
statReader.close();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
MaAnim ma = MaAnim.newIns(vf.getData());
units[i] = new CustomMaskUnit(statReader.readLine().split(","), curve, ma, rare);
}
statReader.close();
EntityHandler.generateStatImage(msg.getChannel().block(), cellData, procData, abilityData, traitData, units, name, container, lv, !isSecond, uID, lang);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
} catch (Exception e) {
e.printStackTrace();
StaticStore.logger.uploadErrorLog(e, "Failed to generate CustomMaksUnit data");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
}
}).start();
} else {
author.getAuthor().ifPresent(u -> StaticStore.putHolder(u.getId().asString(), StatAnalyzerMessageHolder.this));
registerAutoFinish(this, msg, author, lang, "animanalyze_expire", TimeUnit.MINUTES.toMillis(5));
}
}
@Override
public int handleEvent(MessageCreateEvent event) {
try {
if(expired) {
StaticStore.logger.uploadLog("Expired Holder : "+this.getClass().getName());
return RESULT_FAIL;
}
System.out.println("1");
MessageChannel ch = event.getMessage().getChannel().block();
if(ch == null)
return RESULT_STILL;
System.out.println("2");
if(!ch.getId().asString().equals(channelID))
return RESULT_STILL;
System.out.println("3");
AtomicReference<Long> now = new AtomicReference<>(System.currentTimeMillis());
Message m = event.getMessage();
if(!m.getAttachments().isEmpty()) {
for(Attachment a : m.getAttachments()) {
if(a.getFilename().equals("unit"+Data.trio(uID+1)+".csv") && !statDone) {
downloadAndValidate("STAT (" + "unit" + Data.trio(uID+1) + ".csv" + ") : ", a, FILE.STAT, now);
} else if(a.getFilename().equals("unitlevel.csv") && !levelDone) {
downloadAndValidate("LEVEL (unitlevel.csv) : ", a, FILE.LEVEL, now);
} else if(a.getFilename().endsWith("02.maanim")) {
int index = getIndexOfMaanim(a.getFilename());
if(index != -1) {
FILE.ANIM.setIndex(index);
downloadAndValidate(getMaanimTitle(index), a, FILE.ANIM, now);
}
} else if(a.getFilename().endsWith(".png") && getIndexOfIcon(a.getFilename()) != -1) {
int index = getIndexOfIcon(a.getFilename());
FILE.ICON.setIndex(index);
downloadAndValidate(getIconTitle(index), a, FILE.ICON, now);
} else if(a.getFilename().equals("unitbuy.csv") && !buyDone) {
downloadAndValidate("BUY (unitbuy.csv) : ", a, FILE.BUY, now);
}
}
m.delete().subscribe();
if(allDone()) {
new Thread(() -> {
Guild g = msg.getGuild().block();
if(g == null) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
try {
CustomMaskUnit[] units = new CustomMaskUnit[anim.size()];
File statFile = new File(container, "unit"+Data.trio(uID+1)+".csv");
File levelFile = new File(container, "unitlevel.csv");
File buyFile = new File(container, "unitbuy.csv");
if(!statFile.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Stat file isn't existing even though code finished validation : "+statFile.getAbsolutePath());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
if(!levelFile.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Level curve file isn't existing even though code finished validation : "+levelFile.getAbsolutePath());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
if(!buyFile.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Unit buy file isn't existing even though code finished validation : "+buyFile.getAbsolutePath());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
BufferedReader statReader = new BufferedReader(new FileReader(statFile, StandardCharsets.UTF_8));
BufferedReader levelReader = new BufferedReader(new FileReader(levelFile, StandardCharsets.UTF_8));
BufferedReader buyReader = new BufferedReader(new FileReader(buyFile, StandardCharsets.UTF_8));
int count = 0;
while(count < uID) {
levelReader.readLine();
buyReader.readLine();
count++;
}
String[] curve = levelReader.readLine().split(",");
String[] rare = buyReader.readLine().split(",");
levelReader.close();
buyReader.close();
System.gc();
for(int i = 0; i < units.length; i++) {
File maanim = new File(container, getMaanimFileName(i));
if(!maanim.exists()) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Maanim file isn't existing even though code finished validation : "+maanim.getAbsolutePath());
statReader.close();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
VFile vf = VFile.getFile(maanim);
if(vf == null) {
StaticStore.logger.uploadLog("E/StatAnalyzerMessageHolder | Failed to generate vFile of maanim : "+maanim.getAbsolutePath());
statReader.close();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
return;
}
MaAnim ma = MaAnim.newIns(vf.getData());
units[i] = new CustomMaskUnit(statReader.readLine().split(","), curve, ma, rare);
}
statReader.close();
EntityHandler.generateStatImage(msg.getChannel().block(), cellData, procData, abilityData, traitData, units, name, container, lv, !isSecond, uID, lang);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
} catch (Exception e) {
e.printStackTrace();
StaticStore.logger.uploadErrorLog(e, "Failed to generate CustomMaksUnit data");
new Timer().schedule(new TimerTask() {
@Override
public void run() {
StaticStore.deleteFile(container, true);
}
}, 1000);
}
}).start();
}
} else if(m.getContent().equals("c")) {
Command.editMessage(msg, me -> me.content(wrap(LangID.getStringByID("animanalyze_cancel", lang))));
StaticStore.deleteFile(container, true);
return RESULT_FINISH;
}
} catch (Exception e) {
e.printStackTrace();
StaticStore.logger.uploadErrorLog(e, "Failed to perform StatAnalyzerHolder");
}
return RESULT_STILL;
}
@Override
public void clean() {
}
@Override
public void expire(String id) {
if(expired)
return;
expired = true;
StaticStore.removeHolder(id, this);
Command.editMessage(msg, m -> m.content(wrap(LangID.getStringByID("formst_expire", lang))));
}
private boolean allDone() {
for(int i = 0; i < animDone.length; i++) {
if(!animDone[i] || !iconDone[i])
return false;
}
return statDone && levelDone && buyDone;
}
private void downloadAndValidate(String prefix, Attachment attachment, FILE type, AtomicReference<Long> now) throws Exception {
UpdateCheck.Downloader down = StaticStore.getDownloader(attachment, container);
if(down != null) {
AtomicReference<String> reference = getReference(type);
down.run(d -> {
String p = prefix;
if(d == 1.0) {
p += "VALIDATING...";
} else {
p += DataToString.df.format(d * 100.0) + "%";
}
reference.set(p);
if(System.currentTimeMillis() - now.get() >= 1500) {
now.set(System.currentTimeMillis());
edit();
}
});
File res = new File(container, attachment.getFilename());
if(res.exists()) {
if(validFile(type, res)) {
reference.set(prefix+"SUCCESS");
switch (type) {
case STAT:
statDone = true;
break;
case LEVEL:
levelDone = true;
break;
case BUY:
buyDone = true;
break;
case ANIM:
animDone[FILE.ANIM.index] = true;
break;
case ICON:
iconDone[FILE.ICON.index] = true;
break;
}
} else {
reference.set(prefix+"INVALID");
}
} else {
reference.set(prefix+"DOWN FAILED");
}
edit();
}
}
private AtomicReference<String> getReference(FILE type) {
switch (type) {
case STAT:
return stat;
case LEVEL:
return level;
case BUY:
return buy;
case ANIM:
return anim.get(type.index);
case ICON:
return icon.get(type.index);
}
throw new IllegalStateException("Invalid file type : "+type);
}
private boolean validFile(FILE type, File file) throws Exception {
switch (type) {
case STAT:
if(!file.getName().equals("unit"+Data.trio(uID+1)+".csv"))
return false;
BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
int count = 0;
while(reader.readLine() != null) {
count++;
}
reader.close();
return count >= 3 && count < 5;
case LEVEL:
if(!file.getName().equals("unitlevel.csv"))
return false;
reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
count = 0;
String line;
while((line = reader.readLine()) != null) {
count++;
if(count == uID && !line.isBlank())
return true;
}
reader.close();
return false;
case BUY:
if(!file.getName().equals("unitbuy.csv"))
return false;
reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
count = 0;
while((line = reader.readLine()) != null) {
count++;
if(count == uID && !line.isBlank())
return true;
}
reader.close();
return false;
case ANIM:
return AnimMixer.validMaanim(file);
case ICON:
return AnimMixer.validPng(file);
}
return false;
}
private int getIndexOfMaanim(String fileName) {
if(fileName.endsWith("f02.maanim"))
return 0;
else if(fileName.endsWith("c02.maanim"))
return 1;
else if(fileName.endsWith("s02.maanim"))
return 2;
else
return -1;
}
private int getIndexOfIcon(String fileName) {
if(fileName.endsWith("f00.png"))
return 0;
else if(fileName.endsWith("c00.png"))
return 1;
else if(fileName.endsWith("s00.png"))
return 2;
else
return -1;
}
private String getMaanimTitle(int ind) {
switch (ind) {
case 0:
return "MAANIM F ATK ("+ Data.trio(uID)+"_f02.maanim) : ";
case 1:
return "MAANIM C ATK ("+ Data.trio(uID)+"_c02.maanim) : ";
case 2:
return "MAANIM S ATK ("+ Data.trio(uID)+"_s02.maanim) : ";
default:
return "MAANIM " + ind + " ATK : ";
}
}
private String getIconTitle(int ind) {
switch (ind) {
case 0:
return "ICON F (uni"+Data.trio(uID)+"_f00.png) : ";
case 1:
return "ICON C (uni"+Data.trio(uID)+"_c00.png) : ";
case 2:
return "ICON S (uni"+Data.trio(uID)+"_s00.png) : ";
default:
return "ICON " + ind + " : ";
}
}
private String getMaanimFileName(int ind) {
switch (ind) {
case 0:
return Data.trio(uID)+"_f02.maanim";
case 1:
return Data.trio(uID)+"_c02.maanim";
case 2:
return Data.trio(uID)+"_s02.maanim";
default:
return Data.trio(uID)+"_"+ind+"02.maanim";
}
}
private void edit() {
StringBuilder content = new StringBuilder(stat.get()+"\n"+level.get()+"\n"+buy.get()+"\n");
for(int i = 0; i < anim.size(); i++) {
content.append(anim.get(i).get()).append("\n");
}
for(int i = 0; i < icon.size(); i++) {
content.append(icon.get(i).get());
if(i < icon.size() - 1)
content.append("\n");
}
Command.editMessage(msg, m -> m.content(wrap(content.toString())));
}
}
| 38.804027 | 302 | 0.464838 |
7f6e24d9fd33c09a095973eab977ead19a5e9956 | 7,351 | package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.*;
import io.swagger.annotations.*;
import java.util.Objects;
import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope;
import com.fasterxml.jackson.annotation.JsonCreator;
import javax.validation.Valid;
public class APIProductInfoDTO {
private String id = null;
private String name = null;
private String context = null;
private String description = null;
private String provider = null;
private Boolean hasThumbnail = null;
@XmlType(name="StateEnum")
@XmlEnum(String.class)
public enum StateEnum {
CREATED("CREATED"),
PUBLISHED("PUBLISHED");
private String value;
StateEnum (String v) {
value = v;
}
public String value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static StateEnum fromValue(String v) {
for (StateEnum b : StateEnum.values()) {
if (String.valueOf(b.value).equals(v)) {
return b;
}
}
return null;
}
}
private StateEnum state = null;
private List<String> securityScheme = new ArrayList<String>();
/**
* UUID of the api product
**/
public APIProductInfoDTO id(String id) {
this.id = id;
return this;
}
@ApiModelProperty(example = "01234567-0123-0123-0123-012345678901", value = "UUID of the api product ")
@JsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Name of the API Product
**/
public APIProductInfoDTO name(String name) {
this.name = name;
return this;
}
@ApiModelProperty(example = "PizzaShackAPIProduct", value = "Name of the API Product")
@JsonProperty("name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
**/
public APIProductInfoDTO context(String context) {
this.context = context;
return this;
}
@ApiModelProperty(example = "pizzaproduct", value = "")
@JsonProperty("context")
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
/**
* A brief description about the API
**/
public APIProductInfoDTO description(String description) {
this.description = description;
return this;
}
@ApiModelProperty(example = "This is a simple API for Pizza Shack online pizza delivery store", value = "A brief description about the API")
@JsonProperty("description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* If the provider value is not given, the user invoking the API will be used as the provider.
**/
public APIProductInfoDTO provider(String provider) {
this.provider = provider;
return this;
}
@ApiModelProperty(example = "admin", value = "If the provider value is not given, the user invoking the API will be used as the provider. ")
@JsonProperty("provider")
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
/**
**/
public APIProductInfoDTO hasThumbnail(Boolean hasThumbnail) {
this.hasThumbnail = hasThumbnail;
return this;
}
@ApiModelProperty(example = "true", value = "")
@JsonProperty("hasThumbnail")
public Boolean isHasThumbnail() {
return hasThumbnail;
}
public void setHasThumbnail(Boolean hasThumbnail) {
this.hasThumbnail = hasThumbnail;
}
/**
* State of the API product. Only published api products are visible on the store
**/
public APIProductInfoDTO state(StateEnum state) {
this.state = state;
return this;
}
@ApiModelProperty(value = "State of the API product. Only published api products are visible on the store ")
@JsonProperty("state")
public StateEnum getState() {
return state;
}
public void setState(StateEnum state) {
this.state = state;
}
/**
* Types of API security, the current API secured with. It can be either OAuth2 or mutual SSL or both. If it is not set OAuth2 will be set as the security for the current API.
**/
public APIProductInfoDTO securityScheme(List<String> securityScheme) {
this.securityScheme = securityScheme;
return this;
}
@ApiModelProperty(example = "[\"oauth2\"]", value = "Types of API security, the current API secured with. It can be either OAuth2 or mutual SSL or both. If it is not set OAuth2 will be set as the security for the current API. ")
@JsonProperty("securityScheme")
public List<String> getSecurityScheme() {
return securityScheme;
}
public void setSecurityScheme(List<String> securityScheme) {
this.securityScheme = securityScheme;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
APIProductInfoDTO apIProductInfo = (APIProductInfoDTO) o;
return Objects.equals(id, apIProductInfo.id) &&
Objects.equals(name, apIProductInfo.name) &&
Objects.equals(context, apIProductInfo.context) &&
Objects.equals(description, apIProductInfo.description) &&
Objects.equals(provider, apIProductInfo.provider) &&
Objects.equals(hasThumbnail, apIProductInfo.hasThumbnail) &&
Objects.equals(state, apIProductInfo.state) &&
Objects.equals(securityScheme, apIProductInfo.securityScheme);
}
@Override
public int hashCode() {
return Objects.hash(id, name, context, description, provider, hasThumbnail, state, securityScheme);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class APIProductInfoDTO {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" context: ").append(toIndentedString(context)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" provider: ").append(toIndentedString(provider)).append("\n");
sb.append(" hasThumbnail: ").append(toIndentedString(hasThumbnail)).append("\n");
sb.append(" state: ").append(toIndentedString(state)).append("\n");
sb.append(" securityScheme: ").append(toIndentedString(securityScheme)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 28.164751 | 230 | 0.665352 |
49438d2172bd6465031fd8580ef414dc07fd5218 | 68 | package com.clx4399.common.vaild;
public interface UpdateGroup {
}
| 13.6 | 33 | 0.794118 |
d45653b0dfd8b4c870252baefabbe1bcde110833 | 4,674 | /*-
* #%L
* ImgLib2: a general-purpose, multidimensional image processing library.
* %%
* Copyright (C) 2009 - 2021 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld,
* John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke,
* Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner,
* Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert,
* Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin,
* Jean-Yves Tinevez and Michael Zinsmaier.
* %%
* 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.
*
* 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 HOLDERS 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.
* #L%
*/
package net.imglib2.algorithm.convolution;
import net.imglib2.RandomAccessible;
import net.imglib2.algorithm.convolution.fast_gauss.FastGauss;
import net.imglib2.algorithm.convolution.kernel.Kernel1D;
import net.imglib2.algorithm.convolution.kernel.SeparableKernelConvolution;
import net.imglib2.algorithm.gauss3.Gauss3;
import net.imglib2.algorithm.gauss3.SeparableSymmetricConvolution;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.view.Views;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@State( Scope.Benchmark )
public class GaussBenchmark
{
private double sigma = 2.0;
private long[] dims = { 200, 200, 200 };
private RandomAccessible< DoubleType > inImage = Views.extendBorder( ArrayImgs.doubles( dims ) );
private Img< DoubleType > outImage = ArrayImgs.doubles( dims );
@Benchmark
public void benchmarkSeparableKernelConvolution()
{
double[][] halfKernels = Gauss3.halfkernels( new double[] { sigma, sigma, sigma } );
final int numthreads = Runtime.getRuntime().availableProcessors();
final ExecutorService service = Executors.newFixedThreadPool( numthreads );
final Convolution< NumericType< ? > > convolution = SeparableKernelConvolution.convolution( Kernel1D.symmetric( halfKernels ) );
convolution.setExecutor( service );
convolution.process( inImage, outImage );
service.shutdown();
}
@Benchmark
public void benchmarkSeparableSymmetricConvolution()
{
double[][] halfKernels = Gauss3.halfkernels( new double[] { sigma, sigma, sigma } );
final int numthreads = Runtime.getRuntime().availableProcessors();
final ExecutorService service = Executors.newFixedThreadPool( numthreads );
SeparableSymmetricConvolution.convolve( halfKernels, inImage, outImage, service );
service.shutdown();
}
@Benchmark
public void benchmarkFastGauss()
{
FastGauss.convolution( sigma ).process( inImage, outImage );
}
public static void main( String[] args ) throws RunnerException
{
Options opt = new OptionsBuilder()
.include( GaussBenchmark.class.getSimpleName() )
.forks( 1 )
.warmupIterations( 8 )
.measurementIterations( 8 )
.warmupTime( TimeValue.milliseconds( 100 ) )
.measurementTime( TimeValue.milliseconds( 100 ) )
.build();
new Runner( opt ).run();
}
}
| 41.362832 | 130 | 0.77086 |
883d0207bc8f0bc1d9dbc2b671420fe8d29176b7 | 40,806 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
/*
*
* SystemIdImpInclTest.java
*
*/
package org.apache.qetest.trax;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.qetest.FileBasedTest;
import org.apache.qetest.Logger;
import org.apache.qetest.OutputNameManager;
import org.apache.qetest.QetestUtils;
import org.apache.qetest.xsl.XSLTestfileInfo;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
//-------------------------------------------------------------------------
/**
* Test behavior of imports/includes with various setSystemId sources.
* <b>Note:</b> This test is directory-dependent, so if there are
* any fails, check the code to see what the test file is expecting
* the path/directory/etc. to be.
* //@todo More variations on kinds of systemIds: file: id's that
* are absolute, etc.; any/all other forms of id's like http:
* (which will require network resources available).
*
* @author shane_curcuru@lotus.com
* @version $Id$
*/
public class SystemIdImpInclTest extends FileBasedTest
{
/**
* Provides nextName(), currentName() functionality for tests
* that may produce any number of output files.
*/
protected OutputNameManager outNames;
/**
* Name of a valid, known-good xsl/xml file pair we can use.
*/
protected XSLTestfileInfo testFileInfo = new XSLTestfileInfo();
/**
* Just basename of a valid, known-good file, both .xsl/.xml .
*/
protected String knownGoodBaseName = null;
/** Gold filename for level0, i.e. one directory above the testfile. */
protected String goldFileLevel0 = "SystemIdImpInclLevel0.out";
/** Gold filename for level1, i.e. the directory of the testfile. */
protected String goldFileLevel1 = "SystemIdImpInclLevel1.out";
/** Gold filename for level2, i.e. a directory below the testfile. */
protected String goldFileLevel2 = "SystemIdImpInclLevel2.out";
/** Gold filename for http, i.e. a from a webserver. */
protected String goldFileHttp = "SystemIdImpInclHttp.out";
/** Subdirectory under test\tests\api for our xsl/xml files. */
public static final String TRAX_SUBDIR = "trax";
/** Convenience variable for user.dir - cached during test. */
protected String savedUserDir = null;
/** Just initialize test name, comment, numTestCases. */
public SystemIdImpInclTest()
{
numTestCases = 3; // Set numTestCases to 3 to skip the 4th one that does http:
testName = "SystemIdImpInclTest";
testComment = "Test behavior of imports/includes with various setSystemId sources";
}
/**
* Initialize this test - Set names of xml/xsl test files,
* cache user.dir property.
*
* @param p Properties to initialize from (unused)
* @return false if we should abort the test; true otherwise
*/
public boolean doTestFileInit(Properties p)
{
// Used for all tests; just dump files in trax subdir
File outSubDir = new File(outputDir + File.separator + TRAX_SUBDIR);
if (!outSubDir.mkdirs())
reporter.logWarningMsg("Could not create output dir: " + outSubDir);
// Initialize an output name manager to that dir with .out extension
outNames = new OutputNameManager(outputDir + File.separator + TRAX_SUBDIR
+ File.separator + testName, ".out");
String testBasePath = inputDir
+ File.separator
+ TRAX_SUBDIR
+ File.separator;
String goldBasePath = goldDir
+ File.separator
+ TRAX_SUBDIR
+ File.separator;
// Just bare pathnames, not URI's
knownGoodBaseName = "SystemIdImpIncl";
testFileInfo.inputName = testBasePath + knownGoodBaseName + ".xsl";
testFileInfo.xmlName = testBasePath + knownGoodBaseName + ".xml";
testFileInfo.goldName = goldBasePath + knownGoodBaseName + ".out";
goldFileLevel0 = goldBasePath + goldFileLevel0; // just prepend path
goldFileLevel1 = goldBasePath + goldFileLevel1; // just prepend path
goldFileLevel2 = goldBasePath + goldFileLevel2; // just prepend path
goldFileHttp = goldBasePath + goldFileHttp; // just prepend path
// Cache user.dir property
savedUserDir = System.getProperty("user.dir");
reporter.logHashtable(Logger.STATUSMSG, System.getProperties(), "System.getProperties()");
reporter.logHashtable(Logger.STATUSMSG, testProps, "testProps");
return true;
}
/**
* Cleanup this test - uncache user.dir property.
*
* @param p Properties to initialize from (if needed)
* @return false if we should abort the test; true otherwise
*/
public boolean doTestFileClose(Properties p)
{
// Uncache user.dir property
System.getProperties().put("user.dir", savedUserDir);
return true;
}
/**
* Simple StreamSources with different setSystemIds.
*
* @return false if we should abort the test; true otherwise
*/
public boolean testCase1()
{
reporter.testCaseInit("Simple StreamSources with different setSystemIds");
TransformerFactory factory = null;
try
{
factory = TransformerFactory.newInstance();
}
catch (Throwable t)
{
reporter.checkFail("Problem creating factory; can't continue testcase");
reporter.logThrowable(reporter.ERRORMSG, t,
"Problem creating factory; can't continue testcase");
return true;
}
try
{
// Verify we can do basic transforms with readers/streams,
// with the 'normal' systemId
reporter.logInfoMsg("StreamSource.setSystemId(level1)");
InputStream xslStream1 = new FileInputStream(testFileInfo.inputName);
Source xslSource1 = new StreamSource(xslStream1);
xslSource1.setSystemId(QetestUtils.filenameToURL(testFileInfo.inputName));
InputStream xmlStream1 = new FileInputStream(testFileInfo.xmlName);
Source xmlSource1 = new StreamSource(xmlStream1);
xmlSource1.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
reporter.logTraceMsg("Create FileOutputStream to " + outNames.nextName());
FileOutputStream fos1 = new FileOutputStream(outNames.currentName());
Result result1 = new StreamResult(fos1);
Templates templates1 = factory.newTemplates(xslSource1);
Transformer transformer1 = templates1.newTransformer();
reporter.logInfoMsg("About to transform, systemId(level1)");
transformer1.transform(xmlSource1, result1);
fos1.close(); // must close ostreams we own
if (Logger.PASS_RESULT
!= fileChecker.check(reporter,
new File(outNames.currentName()),
new File(goldFileLevel1),
"transform after setSystemId(level1) into " + outNames.currentName())
)
reporter.logInfoMsg("transform after setSystemId(level1)... failure reason:" + fileChecker.getExtendedInfo());
}
catch (Throwable t)
{
reporter.checkFail("Problem with setSystemId(level1)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with after setSystemId(level1)");
}
try
{
// Verify we can do basic transforms with readers/streams,
// systemId set up one level
reporter.logInfoMsg("StreamSource.setSystemId(level0)");
InputStream xslStream1 = new FileInputStream(testFileInfo.inputName);
Source xslSource1 = new StreamSource(xslStream1);
xslSource1.setSystemId(QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"));
InputStream xmlStream1 = new FileInputStream(testFileInfo.xmlName);
Source xmlSource1 = new StreamSource(xmlStream1);
xmlSource1.setSystemId(QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xml"));
reporter.logTraceMsg("Create FileOutputStream to " + outNames.nextName());
FileOutputStream fos1 = new FileOutputStream(outNames.currentName());
Result result1 = new StreamResult(fos1);
Templates templates1 = factory.newTemplates(xslSource1);
Transformer transformer1 = templates1.newTransformer();
reporter.logInfoMsg("About to transform, systemId(level0)");
transformer1.transform(xmlSource1, result1);
fos1.close(); // must close ostreams we own
if (Logger.PASS_RESULT
!= fileChecker.check(reporter,
new File(outNames.currentName()),
new File(goldFileLevel0),
"transform after setSystemId(level0) into " + outNames.currentName())
)
reporter.logInfoMsg("transform after setSystemId(level0)... failure reason:" + fileChecker.getExtendedInfo());
}
catch (Throwable t)
{
reporter.checkFail("Problem with setSystemId(level0)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with setSystemId(level0)");
}
try
{
// Verify we can do basic transforms with readers/streams,
// with the systemId down one level
reporter.logInfoMsg("StreamSource.setSystemId(level2)");
InputStream xslStream1 = new FileInputStream(testFileInfo.inputName);
Source xslSource1 = new StreamSource(xslStream1);
xslSource1.setSystemId(QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"));
InputStream xmlStream1 = new FileInputStream(testFileInfo.xmlName);
Source xmlSource1 = new StreamSource(xmlStream1);
xmlSource1.setSystemId(QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xml"));
reporter.logTraceMsg("Create FileOutputStream to " + outNames.nextName());
FileOutputStream fos1 = new FileOutputStream(outNames.currentName());
Result result1 = new StreamResult(fos1);
Templates templates1 = factory.newTemplates(xslSource1);
Transformer transformer1 = templates1.newTransformer();
reporter.logInfoMsg("About to transform, systemId(level2)");
transformer1.transform(xmlSource1, result1);
fos1.close(); // must close ostreams we own
if (Logger.PASS_RESULT
!= fileChecker.check(reporter,
new File(outNames.currentName()),
new File(goldFileLevel2),
"transform after setSystemId(level2) into " + outNames.currentName())
)
reporter.logInfoMsg("transform after setSystemId(level2)... failure reason:" + fileChecker.getExtendedInfo());
}
catch (Throwable t)
{
reporter.checkFail("Problem with setSystemId(level2)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with setSystemId(level2)");
}
try
{
// Verify we can do basic transforms with readers/streams,
// with the systemId down one level
reporter.logInfoMsg("StreamSource.setSystemId(xslonly level2)");
InputStream xslStream1 = new FileInputStream(testFileInfo.inputName);
Source xslSource1 = new StreamSource(xslStream1);
xslSource1.setSystemId(QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"));
InputStream xmlStream1 = new FileInputStream(testFileInfo.xmlName);
Source xmlSource1 = new StreamSource(xmlStream1);
// Explicitly don't set the xmlId - shouldn't be needed
reporter.logTraceMsg("Create FileOutputStream to " + outNames.nextName());
FileOutputStream fos1 = new FileOutputStream(outNames.currentName());
Result result1 = new StreamResult(fos1);
Templates templates1 = factory.newTemplates(xslSource1);
Transformer transformer1 = templates1.newTransformer();
reporter.logInfoMsg("About to transform, systemId(xslonly level2)");
transformer1.transform(xmlSource1, result1);
fos1.close(); // must close ostreams we own
if (Logger.PASS_RESULT
!= fileChecker.check(reporter,
new File(outNames.currentName()),
new File(goldFileLevel2),
"transform after setSystemId(xslonly level2) into " + outNames.currentName())
)
reporter.logInfoMsg("transform after setSystemId(xslonly level2)... failure reason:" + fileChecker.getExtendedInfo());
}
catch (Throwable t)
{
reporter.checkFail("Problem with setSystemId(xslonly level2)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with setSystemId(xslonly level2)");
}
reporter.testCaseClose();
return true;
}
/**
* Verify simple SAXSources with systemIds.
*
* @return false if we should abort the test; true otherwise
*/
public boolean testCase2()
{
reporter.testCaseInit("Verify simple SAXSources with systemIds");
TransformerFactory factory = null;
SAXTransformerFactory saxFactory = null;
InputSource xslInpSrc = null;
Source xslSource = null;
Source xmlSource = null;
try
{
factory = TransformerFactory.newInstance();
saxFactory = (SAXTransformerFactory)factory;
}
catch (Throwable t)
{
reporter.checkFail("Problem creating factory; can't continue testcase");
reporter.logThrowable(reporter.ERRORMSG, t,
"Problem creating factory; can't continue testcase");
return true;
}
try
{
// Verify basic transforms with with various systemId
// and a SAXSource(InputSource(String))
// level0: one level up
/********************************
// SAXSource(impSrc(str)) level0, level2
// Note: these cases may not be valid to test, since the setSystemId
// call will effectively overwrite the underlying InputSource's
// real systemId, and thus the stylesheet can't be built
// Answer: write a custom test case that parses the stylesheet
// and builds it, but doesn't get imports/includes until later
// when we have setSystemId
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel0,
"SAXSource(inpSrc(str)).systemId(level0: one up)");
********************************/
// level1: same systemId as actual file
// @DEM changes are to allow test to run on various
// platforms regardeless of encodings; force it to
// be UTF-8 since that's what's checked in
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(testFileInfo.inputName),
xmlSource, goldFileLevel1,
"SAXSource(inpSrc(str)).systemId(level1: same level)");
// level2: one level down
/********************************
// SAXSource(impSrc(str)) level0, level2
// Note: these cases may not be valid to test, since the setSystemId
// call will effectively overwrite the underlying InputSource's
// real systemId, and thus the stylesheet can't be built
// Answer: write a custom test case that parses the stylesheet
// and builds it, but doesn't get imports/includes until later
// when we have setSystemId
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel2,
"SAXSource(inpSrc(str)).systemId(level2: one down)");
********************************/
reporter.logTraceMsg("@todo: add test for SAXSource with reset systemId (see code comments)");
}
catch (Throwable t)
{
reporter.checkFail("Problem with SAXSources(1)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with SAXSources(1)");
}
try
{
// Verify basic transforms with with various systemId
// and a SAXSource(InputSource(InputStream))
// level0: one level up
xslInpSrc = new InputSource(new FileInputStream(testFileInfo.inputName));
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel0,
"SAXSource(inpSrc(byteS)).systemId(level0: one up)");
// level1: same systemId as actual file
xslInpSrc = new InputSource(new FileInputStream(testFileInfo.inputName));
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(testFileInfo.inputName),
xmlSource, goldFileLevel1,
"SAXSource(inpSrc(byteS)).systemId(level1: same level)");
// level2: one level down
xslInpSrc = new InputSource(new FileInputStream(testFileInfo.inputName));
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel2,
"SAXSource(inpSrc(byteS)).systemId(level2: one down)");
// Verify basic transforms with with various systemId
// and a SAXSource(InputSource(Reader))
// level0: one level up
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel0,
"SAXSource(inpSrc(charS)).systemId(level0: one up)");
// level1: same systemId as actual file
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(testFileInfo.inputName),
xmlSource, goldFileLevel1,
"SAXSource(inpSrc(charS)).systemId(level1: same level)");
// level2: one level down
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel2,
"SAXSource(inpSrc(charS)).systemId(level2: one down)");
// Verify basic transforms with with various systemId
// and a SAXSource(XMLReader, InputSource(various))
// Be sure to use the JAXP methods only!
SAXParserFactory spfactory = SAXParserFactory.newInstance();
spfactory.setNamespaceAware(true);
SAXParser saxParser = spfactory.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
// level0: one level up, with a character stream
xslInpSrc = new InputSource(new InputStreamReader(new FileInputStream(testFileInfo.inputName), "UTF-8")); //@DEM
// xslInpSrc = new InputSource(new FileReader(testFileInfo.inputName)); @DEM
xslSource = new SAXSource(reader, xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel0,
"SAXSource(reader, inpSrc(charS)).systemId(level0: one up)");
// level1: same systemId as actual file, with a systemId
saxParser = spfactory.newSAXParser();
reader = saxParser.getXMLReader();
xslInpSrc = new InputSource(testFileInfo.inputName);
xslSource = new SAXSource(reader, xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(testFileInfo.inputName),
xmlSource, goldFileLevel1,
"SAXSource(reader, inpSrc(str)).systemId(level1: same level)");
// level2: one level down, with a byte stream
saxParser = spfactory.newSAXParser();
reader = saxParser.getXMLReader();
xslInpSrc = new InputSource(new FileInputStream(testFileInfo.inputName));
xslSource = new SAXSource(reader, xslInpSrc);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel2,
"SAXSource(reader, inpSrc(byteS)).systemId(level2: one down)");
}
catch (Throwable t)
{
reporter.checkFail("Problem with SAXSources(2)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with SAXSources(2)");
}
reporter.testCaseClose();
return true;
}
/**
* Verify simple DOMSources with systemIds.
*
* @return false if we should abort the test; true otherwise
*/
public boolean testCase3()
{
reporter.testCaseInit("Verify simple DOMSources with systemIds");
TransformerFactory factory = null;
DocumentBuilderFactory dfactory = null;
DocumentBuilder docBuilder = null;
Node xslNode = null;
Source xslSource = null;
Source xmlSource = null;
try
{
factory = TransformerFactory.newInstance();
dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
}
catch (Throwable t)
{
reporter.checkFail("Problem creating factory; can't continue testcase");
reporter.logThrowable(reporter.ERRORMSG, t,
"Problem creating factory; can't continue testcase");
return true;
}
try
{
docBuilder = dfactory.newDocumentBuilder();
// Verify basic transforms with with various systemId
// and a DOMSource(InputSource(String))
// level0: one level up
reporter.logTraceMsg("about to parse(InputSource(" + QetestUtils.filenameToURL(testFileInfo.inputName) + "))");
xslNode = docBuilder.parse(new InputSource(QetestUtils.filenameToURL(testFileInfo.inputName)));
xslSource = new DOMSource(xslNode);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel0,
"DOMSource(inpSrc(str)).systemId(level0: one up)");
// level1: same systemId as actual file
reporter.logTraceMsg("about to parse(InputSource(" + QetestUtils.filenameToURL(testFileInfo.inputName) + "))");
xslNode = docBuilder.parse(new InputSource(QetestUtils.filenameToURL(testFileInfo.inputName)));
xslSource = new DOMSource(xslNode);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(testFileInfo.inputName),
xmlSource, goldFileLevel1,
"DOMSource(inpSrc(str)).systemId(level1: same level)");
// level2: one level down
reporter.logTraceMsg("about to parse(InputSource(" + QetestUtils.filenameToURL(testFileInfo.inputName) + "))");
xslNode = docBuilder.parse(new InputSource(QetestUtils.filenameToURL(testFileInfo.inputName)));
xslSource = new DOMSource(xslNode);
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + "/trax/systemid/" + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel2,
"DOMSource(inpSrc(str)).systemId(level2: one down)");
// Sample extra test: DOMSource that had systemId set
// differently in the constructor - tests that you can
// later call setSystemId and have it work
// level0: one level up
reporter.logTraceMsg("about to parse(InputSource(" + QetestUtils.filenameToURL(testFileInfo.inputName) + "))");
xslNode = docBuilder.parse(new InputSource(QetestUtils.filenameToURL(testFileInfo.inputName)));
// Set the original systemId to itself, or level1
xslSource = new DOMSource(xslNode, QetestUtils.filenameToURL(testFileInfo.inputName));
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
// Test it with a level0, or one level up systemId
checkSourceWithSystemId(xslSource, QetestUtils.filenameToURL(inputDir + File.separator + knownGoodBaseName + ".xsl"),
xmlSource, goldFileLevel0,
"DOMSource(inpSrc(str),sysId-level1).systemId(level0: one up)");
}
catch (Throwable t)
{
reporter.checkFail("Problem with DOMSources(1)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with DOMSources(1)");
}
reporter.testCaseClose();
return true;
}
/**
* Verify various simple Sources with http: systemIds.
* Test may be commented out until we have a better way to
* maintain and check for existence and correct content of
* stylesheets on the http server.
*
* @return false if we should abort the test; true otherwise
*/
public boolean testCase4()
{
reporter.testCaseInit("Verify various simple Sources with http: systemIds");
// This is the name of a directory on the apache server
// that has impincl\SystemIdInclude.xsl and
// impincl\SystemIdImport.xsl files on it - obviously,
// your JVM must have access to this server to successfully
// run this portion of the test!
String httpSystemIdBase = "http://xml.apache.org/xalan-j/test";
// Verify http connectivity
// If your JVM environment can't connect to the http:
// server, then we can't complete the test
// This could happen due to various network problems,
// not being connected, firewalls, etc.
try
{
reporter.logInfoMsg("verifing http connectivity before continuing testCase");
// Note hard-coded path to one of the two files we'll be relying on
URL testURL = new URL(httpSystemIdBase + "/impincl/SystemIdInclude.xsl");
URLConnection urlConnection = testURL.openConnection();
// Ensure we don't get a cached copy
urlConnection.setUseCaches(false);
// Ensure we don't get asked interactive questions
urlConnection.setAllowUserInteraction(false);
// Actually connect to the document; will throw
// IOException if anything goes wrong
urlConnection.connect();
// Convenience: log out when the doc was last modified
reporter.logInfoMsg(testURL.toString() + " last modified: "
+ urlConnection.getLastModified());
int contentLen = urlConnection.getContentLength();
reporter.logStatusMsg("URL.getContentLength() was: " + contentLen);
if (contentLen < 1)
{
// if no content, throw 'fake' exception to
// short-circut test case
throw new IOException("URL.getContentLength() was: " + contentLen);
}
// Also verify that the file there contains (some of) the data we expect!
reporter.logTraceMsg("calling urlConnection.getContent()...");
Object content = urlConnection.getContent();
if (null == content)
{
// if no content, throw 'fake' exception to
// short-circut test case
throw new IOException("URL.getContent() was null!");
}
reporter.logTraceMsg("getContent().toString() is now: " + content.toString());
//@todo we should also verify some key strings in the
// expected .xsl file here, if possible
}
catch (IOException ioe)
{
reporter.logThrowable(Logger.ERRORMSG, ioe, "Can't connect threw");
reporter.logErrorMsg("Can't connect to: " + httpSystemIdBase
+ "/impincl/SystemIdInclude.xsl, skipping testcase");
reporter.checkPass("FAKE PASS RECORD; testCase was skipped");
// Skip the rest of the testcase
reporter.testCaseClose();
return true;
}
TransformerFactory factory = null;
Source xslSource = null;
Source xmlSource = null;
try
{
factory = TransformerFactory.newInstance();
}
catch (Throwable t)
{
reporter.checkFail("Problem creating factory; can't continue testcase");
reporter.logThrowable(reporter.ERRORMSG, t,
"Problem creating factory; can't continue testcase");
return true;
}
try
{
// Verify StreamSource from local disk with a
// http: systemId for imports/includes
xslSource = new StreamSource(new FileInputStream(testFileInfo.inputName));
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
// Note that the systemId set (the second argument below)
// must be the path to the proper 'directory' level
// on the webserver: setting it to just ".../test"
// will fail, since it be considered a file of that
// name, not the directory
checkSourceWithSystemId(xslSource, httpSystemIdBase + "/",
xmlSource, goldFileHttp,
"StreamSource().systemId(http:)");
xslSource = new StreamSource(new FileInputStream(testFileInfo.inputName));
xmlSource = new StreamSource(new FileInputStream(testFileInfo.xmlName));
xmlSource.setSystemId(QetestUtils.filenameToURL(testFileInfo.xmlName));
checkSourceWithSystemId(xslSource, httpSystemIdBase + "/" + knownGoodBaseName + ".xsl",
xmlSource, goldFileHttp,
"StreamSource().systemId(http:)");
}
catch (Throwable t)
{
reporter.checkFail("Problem with http systemIds(1)");
reporter.logThrowable(reporter.ERRORMSG, t, "Problem with http systemIds(1)");
}
reporter.testCaseClose();
return true;
}
/**
* Worker method to test setting SystemId and doing transform.
* Simply does:<pre>
* xslSrc.setSystemId(systemId);
* templates = factory.newTemplates(xslSrc);
* transformer = templates.newTransformer();
* transformer.transform(xmlSrc, StreamResult(...));
* fileChecker.check(... goldFileName, desc)
* </pre>
* Also catches any exceptions and logs them as fails.
*
* @param xslSrc Source to use for stylesheet
* @param systemId systemId to set on the stylesheet
* @param xmlSrc Source to use for XML input data
* @param goldFileName name of expected file to compare with
* @param desc description of this test
*/
public void checkSourceWithSystemId(Source xslSrc, String systemId,
Source xmlSrc, String goldFileName,
String desc)
{
reporter.logTraceMsg(desc + " (" + systemId + ")");
try
{
TransformerFactory factory = TransformerFactory.newInstance();
xslSrc.setSystemId(systemId);
// Use the next available output name for result
FileOutputStream fos = new FileOutputStream(outNames.nextName());
Result outputResult = new StreamResult(fos);
Templates templates = factory.newTemplates(xslSrc);
Transformer transformer = templates.newTransformer();
transformer.transform(xmlSrc, outputResult);
fos.close(); // must close ostreams we own
if (Logger.PASS_RESULT
!= fileChecker.check(reporter,
new File(outNames.currentName()),
new File(goldFileName),
desc + " (" + systemId + ") into: " + outNames.currentName())
)
reporter.logInfoMsg(desc + "... failure reason:" + fileChecker.getExtendedInfo());
}
catch (Throwable t)
{
reporter.checkFail(desc + " threw: " + t.toString());
reporter.logThrowable(reporter.ERRORMSG, t, desc + " threw");
}
}
/**
* Convenience method to print out usage information - update if needed.
* @return String denoting usage of this test class
*/
public String usage()
{
return ("Common [optional] options supported by SystemIdImpInclTest:\n"
+ "(Note: assumes inputDir=.\\tests\\api)\n"
+ "(Note: test is directory-dependent!)\n"
+ super.usage()); // Grab our parent classes usage as well
}
/**
* Main method to run test from the command line - can be left alone.
* @param args command line argument array
*/
public static void main(String[] args)
{
SystemIdImpInclTest app = new SystemIdImpInclTest();
app.doMain(args);
}
}
| 46.742268 | 134 | 0.62209 |
f1b98c6c5347516f1388574c5c13137855fd50b2 | 5,756 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package graphene.web.components.workspace;
import graphene.model.idl.G_ReportViewEvent;
import graphene.model.idl.G_User;
import graphene.model.idl.G_UserDataAccess;
import graphene.model.idl.G_Workspace;
import graphene.web.pages.workspace.Manage;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.avro.AvroRemoteException;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.annotations.Events;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.BeanModelSource;
import org.apache.tapestry5.services.Request;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
/**
* List of workspaces for CRUD
*
* @author djue
*
*/
@Events({ WorkspaceList.SELECTED })
public class WorkspaceList {
public static final String SELECTED = "selected";
// Parameters
@Property
private final DateTimeFormatter ISODate = ISODateTimeFormat.date();
@Inject
private BeanModelSource beanModelSource;
@Inject
private ComponentResources componentResources;
@InjectComponent
private Zone listZone;
@Inject
private Logger logger;
// The code
@Inject
private AlertManager alertManager;
@Persist
private BeanModel<G_Workspace> model;
// Screen fields
@Parameter(required = true)
@Property
private String partialName;
@Parameter(required = false)
@Property
private String title;
@Inject
private Request request;
@Inject
private ComponentResources resources;
@Parameter(required = true)
@Property
private String selectedWorkspaceId;
@Property
private G_ReportViewEvent currentReport;
@Inject
private G_UserDataAccess userDataAccess;
@SessionState(create = false)
private G_User user;
private boolean userExists;
@Property
private G_Workspace workspace;
@Property
@SessionState
private List<G_Workspace> workspaces;
public String getLinkCSSClass() {
if ((workspace != null) && (workspace.getId() != null) && (workspace.getId().equals(selectedWorkspaceId)))
return "active";
return "";
}
public List<G_Workspace> getListOfWorkspaces() {
if (userExists) {
try {
logger.debug("Updating list of workspaces");
workspaces = userDataAccess.getWorkspacesForUser(user.getId());
} catch (final AvroRemoteException e) {
logger.error(e.getMessage());
}
} else {
logger.error("No user name to get workspaces for.");
workspaces = null;
}
return workspaces;
}
// Generally useful bits and pieces
public BeanModel<G_Workspace> getModel() {
if (model == null) {
// TODO: Move the initialization to setupRender
model = beanModelSource.createDisplayModel(G_Workspace.class, resources.getMessages());
model.exclude("schema", "active", "reports", "id");
model.reorder("title", "description", "savedreports", "queryObjects", "modified", "created");
}
return model;
}
/**
* l - Length changing
*
* f - Filtering input
*
* t - The table!
*
* i - Information
*
* p - Pagination
*
* r - pRocessing
*
* < and > - div elements
*
* <"class" and > - div with a class
*
* Examples: <"wrapper"flipt>, <lf<t>ip>
*
* @return
*/
public JSONObject getOptions() {
final JSONObject json = new JSONObject(
"bJQueryUI",
"true",
"bAutoWidth",
"true",
"sDom",
"<\"col-sm-4\"f><\"col-sm-4\"i><\"col-sm-4\"l><\"row\"<\"col-sm-12\"p><\"col-sm-12\"r>><\"row\"<\"col-sm-12\"t>><\"row\"<\"col-sm-12\"ip>>");
// Sorts the columns of workspace tables.
json.put("aaSorting", new JSONArray().put(new JSONArray().put(0).put("asc")));
// new JSONObject().put("aTargets", new JSONArray().put(0, 4));
// final JSONObject sortType = new JSONObject("sType", "formatted-num");
// final JSONArray columnArray = new JSONArray();
// columnArray.put(4, sortType);
// json.put("aoColumns", columnArray);
json.put("oLanguage", new JSONObject("sSearch", "Filter:"));
return json;
}
// Getters
public boolean isAjax() {
return request.isXHR();
}
// Handle event "selected"
boolean onSelected(final String workspaceId) {
// Return false, which means we haven't handled the event so bubble it
// up.
// This method is here solely as documentation, because without this
// method the event would bubble up anyway.
return false;
}
} | 27.673077 | 145 | 0.725678 |
6957889c593edbdab38d75f898533b9e79d70de2 | 556 | package org.tek.code;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @Author Nick
* @CreateTime 2020/9/7
*/
@RestController
@RefreshScope
public class ConfigClientController {
@Value("$config.info")
private String configInfo;
@GetMapping("/config/info")
public String getConfigInfo() {
return configInfo;
}
}
| 24.173913 | 72 | 0.758993 |
e4920032a615e2ff09ab02f1949f41ea2d04b80f | 1,609 | package io.faucette.virtandroid;
import android.app.Activity;
import android.util.Log;
import io.faucette.messenger.Callback;
import io.faucette.virtandroid.websockets.FakeWebSocket;
import io.faucette.virtandroid.websockets.FakeWebSocketServer;
/**
* Created by nathan on 9/1/16.
*/
public class Server extends FakeWebSocketServer {
private Callback _callback;
private int _port;
private Activity _activity;
public Server(int port, Activity activity) {
_port = port;
_activity = activity;
}
public Server(Activity activity) {
this(9999, activity);
}
public void start() {
listen(_port);
}
@Override
public void onOpen(FakeWebSocket webSocket) {
Log.i("Server", "Open");
}
@Override
public void onClose(FakeWebSocket webSocket, boolean remote) {
Log.i("Server", "Close remote:" + remote);
}
@Override
public void onMessage(FakeWebSocket webSocket, String data) {
handleMessage(data);
}
@Override
public void onError(FakeWebSocket webSocket, Exception ex) {
Log.e("Server", ex.toString());
}
public void addListener(Callback callback) {
_callback = callback;
}
public void handleMessage(final String data) {
_activity.runOnUiThread(new Runnable() {
@Override
public void run() {
_callback.call(data);
}
});
}
public void sendToAll(String data) {
for (FakeWebSocket webSocket: getWebSockets()) {
webSocket.send(data);
}
}
} | 24.378788 | 66 | 0.63207 |
9c94238b962f8668eaa291a386846a2edba42248 | 324 | package com.catfish.ums.entity.dto;
import lombok.Data;
import java.util.List;
/**
* 用户资源
* @author chenyj
* 2020/5/24 - 23:40.
**/
@Data
public class MenuPermissionDTO {
//资源或菜单的id列表
private List<String> resourceIds;
//资源状态,true->启用资源,false->禁用资源,就算用户角色中有这个资源也不会生效
private Boolean status = true;
}
| 15.428571 | 51 | 0.685185 |
c34b47c788e2eae612ff216274cb4773de4fbba2 | 1,470 | package com.github.chen0040.bootslingshot.controllers;
import com.github.chen0040.bootslingshot.services.AccountApi;
import com.github.chen0040.bootslingshot.viewmodels.Account;
import com.github.chen0040.bootslingshot.viewmodels.LoginObj;
import com.github.chen0040.bootslingshot.viewmodels.TokenObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AccountController {
@Autowired
private AccountApi service;
@RequestMapping(value="/erp/login-api-json", method= RequestMethod.POST, consumes = "application/json")
public @ResponseBody Account login(@RequestBody LoginObj loginObj) {
return service.login(loginObj);
}
@RequestMapping(value="/erp/validate-api-json", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody
TokenObj validateUser(@RequestBody TokenObj tokenObj) {
return service.validateUser(tokenObj);
}
@RequestMapping(value="/erp/logout-api-json", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody TokenObj logout(@RequestBody TokenObj tokenObj) {
return service.logout(tokenObj);
}
}
| 40.833333 | 111 | 0.787755 |
f67456892460bc1717f4e416a3829421d8f16614 | 450 | package org.jco.applications.domain.core;
import java.util.HashMap;
public abstract class AbstractDomainObject {
private HashMap<String, PropertyGroup> propertyGroupList = new HashMap<>();
public void addPropertyGroup(PropertyGroup propertyGroup, String pgName){
propertyGroupList.put(pgName, propertyGroup);
}
public PropertyGroup getPropertyGroup(String pgName){
return propertyGroupList.get(pgName);
}
} | 22.5 | 79 | 0.748889 |
c933344b22744cc38c11f1666faf8e45f812683f | 4,880 | package com.github.platymemo.alaskanativecraft.recipe;
import com.github.platymemo.alaskanativecraft.item.AlaskaItems;
import com.github.platymemo.alaskanativecraft.tags.AlaskaTags;
import com.google.common.collect.ImmutableList;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.recipe.RecipeSerializer;
import net.minecraft.recipe.SpecialCraftingRecipe;
import net.minecraft.util.Identifier;
import net.minecraft.util.Pair;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
public class AkutaqRecipe extends SpecialCraftingRecipe {
private static final ImmutableList<Pair<StatusEffect, Integer>> POSSIBLE_EFFECTS = ImmutableList.of(
new Pair<>(StatusEffects.ABSORPTION, 20),
new Pair<>(StatusEffects.REGENERATION, 10),
new Pair<>(StatusEffects.RESISTANCE, 10),
new Pair<>(StatusEffects.FIRE_RESISTANCE, 10),
new Pair<>(StatusEffects.HASTE, 10),
new Pair<>(StatusEffects.STRENGTH, 5),
new Pair<>(StatusEffects.SPEED, 12),
new Pair<>(StatusEffects.JUMP_BOOST, 10),
new Pair<>(StatusEffects.SATURATION, 10)
);
public AkutaqRecipe(Identifier id) {
super(id);
}
// Can't use SuspiciousStewItem.addEffectToStew because it overwrites the list tag each time
public static void addEffectToAkutaq(@NotNull ItemStack stew, StatusEffect effect, int duration) {
NbtCompound compoundTag = stew.getOrCreateNbt();
NbtList listTag = compoundTag.getList("Effects", 10);
boolean effectExists = false;
byte effectId = (byte) StatusEffect.getRawId(effect);
int actualDuration = duration;
for (int i = 0; i < listTag.size(); ++i) {
NbtCompound previousEffect = listTag.getCompound(i);
if (previousEffect.contains("EffectDuration", 3) && effectId == previousEffect.getByte("EffectId")) {
actualDuration += previousEffect.getInt("EffectDuration");
previousEffect.putInt("EffectDuration", actualDuration);
effectExists = true;
}
}
if (!effectExists) {
NbtCompound newEffect = new NbtCompound();
newEffect.putByte("EffectId", effectId);
newEffect.putInt("EffectDuration", actualDuration);
listTag.add(newEffect);
}
compoundTag.put("Effects", listTag);
}
@Override
public boolean matches(@NotNull CraftingInventory inv, World world) {
boolean hasMeat = false;
boolean hasBerries = false;
boolean hasBowl = false;
for (int i = 0; i < inv.size(); ++i) {
ItemStack itemStack = inv.getStack(i);
if (!itemStack.isEmpty()) {
// Need at least 1 berry but can have more
if (itemStack.isIn(AlaskaTags.AKUTAQ_BERRIES)) {
hasBerries = true;
}
// Can only have one piece of meat
else if (itemStack.isIn(AlaskaTags.AKUTAQ_MEATS) && !hasMeat) {
hasMeat = true;
} else {
// Checks for bowl, if not a bowl or anything but a bowl, returns false
if (itemStack.getItem() != Items.BOWL || hasBowl) {
return false;
}
hasBowl = true;
}
}
}
return hasMeat && hasBerries && hasBowl;
}
@Override
public ItemStack craft(@NotNull CraftingInventory inv) {
ItemStack akutaq = new ItemStack(AlaskaItems.AKUTAQ, 1);
Random random = new Random();
ItemStack currentItemstack;
for (int i = 0; i < inv.size(); ++i) {
currentItemstack = inv.getStack(i);
if (!currentItemstack.isEmpty() && currentItemstack.isIn(AlaskaTags.AKUTAQ_BERRIES)) {
Pair<StatusEffect, Integer> pair = POSSIBLE_EFFECTS.get(random.nextInt(POSSIBLE_EFFECTS.size()));
StatusEffect statusEffect = pair.getLeft();
int duration = pair.getRight();
if (!statusEffect.isInstant()) {
duration *= 20;
}
// Add effect
addEffectToAkutaq(akutaq, statusEffect, duration);
}
}
return akutaq;
}
@Override
public boolean fits(int width, int height) {
return width >= 2 && height >= 2;
}
@Override
public RecipeSerializer<?> getSerializer() {
return AlaskaRecipes.AKUTAQ;
}
}
| 36.691729 | 113 | 0.616189 |
c069e34d57097ff3848441e1f3feb759502a6081 | 1,354 | package victor.kryz.hrfusion.entities;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import victor.kryz.hrfusion.hrdb.Employee;
import victor.kryz.hrfusion.jni.PocoException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* HRFusion (unit tests)
*
* @author Victor Kryzhanivskyi
*/
@RunWith(AndroidJUnit4.class)
public class ReadEmployeesTest extends JUnitTestBase
{
String mDepartment;
@Before
public void setUpDepartment() {
mDepartment = "50"; // Shipping
}
@Test
public void test() throws PocoException
{
List<Employee> items = getSession().getEmployees(mDepartment);
assertEquals(items.size(), 45);
Employee item0 = items.get(0);
assertEquals("Adam", item0.getName());
assertEquals("Fripp", item0.getLastName());
assertEquals("Stock Manager", item0.getJobTitle());
assertTrue(item0.isMngr());
Employee item44 = items.get(44);
assertEquals("Winston", item44.getName());
assertEquals("Taylor", item44.getLastName());
assertEquals("Shipping Clerk", item44.getJobTitle());
assertFalse(item44.isMngr());
}
}
| 26.54902 | 70 | 0.694239 |
38b379f02f1dec383d5d7f874b53dd3745d38cfc | 755 | package program.classes;
import java.io.Serializable;
public class Lorry extends Vehicle implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3499630700596375118L;
protected double loadingCapacity;
/**
* Constructor for the child Class of Vehicle, Lorry.
*/
public Lorry(String model, String make, String registrationNumber, double topSpeed, double dailyHireRate, double loadingCapacity,Boolean rented) {
super(model, make, registrationNumber, topSpeed, dailyHireRate,rented);
this.loadingCapacity = dailyHireRate;
}
public double getLoadingCapacity() {
return loadingCapacity;
}
public void setLoadingCapacity(double loadingCapacity) {
this.loadingCapacity = loadingCapacity;
}
}
| 19.868421 | 147 | 0.760265 |
0948fa22f7254ca1eb30e4f374b3438fa10f78af | 1,803 | /*
Copyright (c) 2014 Ahomé Innovation Technologies. 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.ait.toolkit.sencha.ext.client.core;
import com.ait.toolkit.sencha.ext.client.core.handlers.WindowResizeHandler;
/**
* Registers event handlers that want to receive a normalized EventObject
* instead of the standard browser event and provides several useful events
* directly.
* <p>
* See {@link EventObject} for more details on normalized event objects.
*
*/
public class ExtEventManager {
private ExtEventManager() {
}
/**
* Adds a listener to be notified when the browser window is resized and
* provides resize event buffering (100 milliseconds), passes new viewport
* width and height to handlers.
*
* @param handler
* , The handler function the window resize event invokes.
*/
public static native void addWindowResizeHandler(WindowResizeHandler handler)/*-{
$wnd.Ext.EventManager
.onWindowResize(function(w, h) {
var event = @com.ait.toolkit.sencha.ext.client.events.WindowResizeEvent::new(II)(w,h);
handler.@com.ait.toolkit.sencha.ext.client.core.handlers.WindowResizeHandler::onWindowResize(Lcom/ait/toolkit/sencha/ext/client/events/WindowResizeEvent;)(event);
});
}-*/;
}
| 35.352941 | 167 | 0.735996 |
8fa9acb40ceeff4855aa83e3644742c85a37d739 | 2,001 | package com.mateus.burble;
import com.mateus.burble.command.CommandManager;
import com.mateus.burble.command.types.MemeCommands;
import com.mateus.burble.command.types.TextCommands;
import com.mateus.burble.config.CoreConfig;
import com.mateus.burble.listener.MainListener;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import javax.annotation.Nonnull;
import javax.security.auth.login.LoginException;
import java.io.File;
/**
* A Discord bot, it uses JDA, it doesn’t have a specific reason to exist
* if I find something interesting, I’ll implement it
* @author Mateus F
* @version 1.0
* @since 2020-07-19
*/
public class Burble extends ListenerAdapter {
private static JDA jda;
public static void main(String[] args) throws LoginException {
CoreConfig coreConfig = CoreConfig.getInstance();
coreConfig.setup();
String token = coreConfig.getConfig().get("token").getAsString();
if (token.equals("<default-token>")) {
System.err.println("Set the token");
return;
}
JDA jda = JDABuilder.createDefault(token).build();
jda.addEventListener(new MainListener(), new Burble());
CommandManager.getInstance().registerCommands(new TextCommands());
CommandManager.getInstance().registerCommands(new MemeCommands());
}
/**
* Returns the folder that will be used for data storage
* @return The data folder
*/
public static File getDataFolder() {
File folder = new File(System.getProperty("user.dir") + "/data");
if (!folder.exists()) folder.mkdirs();
return folder;
}
/**
* Returns the main JDA instance
* @return Main JDA instance
*/
public static JDA getJDA() {
return jda;
}
@Override
public void onReady(@Nonnull ReadyEvent event) {
jda = event.getJDA();
}
}
| 30.318182 | 74 | 0.68066 |
f4ac628d8723d86bf3d08a8a67c47990781c9be0 | 1,358 | package org.smyld.util;
import org.smyld.SMYLDObject;
public class ProcessTimeCalculator extends SMYLDObject {
/**
*
*/
private static final long serialVersionUID = 1L;
long minTime = -1, maxTime = -1, totalTime, curTime;
String processName;
public ProcessTimeCalculator(String processName) {
this.processName = processName;
}
public void processStart() {
curTime = System.currentTimeMillis();
}
public void processEnd() {
calculateEndOfTranProcessTime(System.currentTimeMillis() - curTime);
}
private void calculateEndOfTranProcessTime(long curPeriod) {
if (minTime == -1)
minTime = curPeriod;
if (maxTime == -1)
maxTime = curPeriod;
if (curPeriod > maxTime)
maxTime = curPeriod;
if (curPeriod < minTime)
minTime = curPeriod;
totalTime += curPeriod;
curTime = 0;
}
public void printTimeResults() {
System.out.println("Process " + processName + " time results :");
System.out.println("Total time " + totalTime);
System.out.println("Maximum time " + maxTime);
System.out.println("Minimum time " + minTime);
}
public void reset() {
maxTime = 0;
minTime = 0;
totalTime = 0;
curTime = 0;
}
public long getTotalProcessingTime() {
return totalTime;
}
public long getMaximumProcessingTime() {
return maxTime;
}
public long getMinimumProcessingTime() {
return minTime;
}
}
| 20.892308 | 70 | 0.699558 |
00f4e99aa8dc74f9f08f60cdd2061961ca7f75a0 | 1,130 | package com.ywh.ds.sorting;
/**
* 选择排序
* [排序] [不稳定排序]
*
* @author ywh
* @since 13/11/2019
*/
public class SelectionSort {
private void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* Time: O(n^2), Space: O(1)
*
* @param arr
*/
public void sort(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
for (int i = 0; i < arr.length; i++) {
int minIdx = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
swap(arr, i, minIdx);
}
}
public void sortFromEnd(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
for (int i = arr.length - 1; i > 0; --i) {
int maxIdx = i;
for (int j = 0; j < i; j++) {
if (arr[j] > arr[maxIdx]) {
maxIdx = j;
}
}
swap(arr, i, maxIdx);
}
}
}
| 21.320755 | 54 | 0.366372 |
708925aa7d01f3d900fcbe3c47252355d3a6397f | 8,569 | package org.terraform.biome.flat;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.block.data.Rotatable;
import org.terraform.biome.BiomeBank;
import org.terraform.biome.BiomeHandler;
import org.terraform.coregen.PopulatorDataAbstract;
import org.terraform.data.SimpleLocation;
import org.terraform.data.TerraformWorld;
import org.terraform.main.config.TConfigOption;
import org.terraform.tree.FractalTreeBuilder;
import org.terraform.tree.FractalTypes;
import org.terraform.tree.MushroomBuilder;
import org.terraform.tree.TreeDB;
import org.terraform.utils.BlockUtils;
import org.terraform.utils.GenUtils;
import java.util.ArrayList;
import java.util.Random;
public class DarkForestHandler extends BiomeHandler {
@Override
public boolean isOcean() {
return false;
}
@Override
public Biome getBiome() {
return Biome.DARK_FOREST;
}
@Override
public Material[] getSurfaceCrust(Random rand) {
return new Material[]{
Material.GRASS_BLOCK,
Material.DIRT,
Material.DIRT,
GenUtils.randMaterial(rand, Material.DIRT, Material.STONE),
GenUtils.randMaterial(rand, Material.DIRT, Material.STONE)};
}
@Override
public void populateSmallItems(TerraformWorld tw, Random random, PopulatorDataAbstract data) {
boolean spawnHeads = TConfigOption.BIOME_DARK_FOREST_SPAWN_HEADS.getBoolean()
&& GenUtils.chance(random, 1, 100);
//Small decorations
for (int x = data.getChunkX() * 16; x < data.getChunkX() * 16 + 16; x++) {
for (int z = data.getChunkZ() * 16; z < data.getChunkZ() * 16 + 16; z++) {
int y = GenUtils.getHighestGround(data, x, z);
if (data.getType(x, y, z) == Material.GRASS_BLOCK) {
if (GenUtils.chance(random, 1, 10)) {
if (data.getType(x, y + 1, z) != Material.AIR) continue;
//Only grass and mushrooms
data.setType(x, y + 1, z, Material.GRASS);
if (random.nextInt(3) != 0) {
BlockUtils.setDoublePlant(data, x, y + 1, z, Material.TALL_GRASS);
} else {
Material mushroom = Material.RED_MUSHROOM;
if (random.nextBoolean())
mushroom = Material.BROWN_MUSHROOM;
data.setType(x, y + 1, z, mushroom);
}
}
}
if (spawnHeads && GenUtils.chance(random, 1, 50)) {
if (BlockUtils.isDirtLike(data.getType(x, y, z))) {
Rotatable skull = (Rotatable) Bukkit.createBlockData(Material.PLAYER_HEAD);
skull.setRotation(BlockUtils.getXZPlaneBlockFace(random));
data.setBlockData(x, y + 1, z, skull);
}
}
}
}
}
@Override
public void populateLargeItems(TerraformWorld tw, Random random, PopulatorDataAbstract data) {
SimpleLocation[] bigTrees = GenUtils.randomObjectPositions(tw, data.getChunkX(), data.getChunkZ(), 32);
SimpleLocation[] trees = GenUtils.randomObjectPositions(tw, data.getChunkX(), data.getChunkZ(), 10);
SimpleLocation[] smallDecorations = GenUtils.randomObjectPositions(tw, data.getChunkX(), data.getChunkZ(), 7);
// Big trees and giant mushrooms
for (SimpleLocation sLoc : bigTrees) {
int treeY = GenUtils.getHighestGround(data, sLoc.getX(),sLoc.getZ());
sLoc.setY(treeY);
if (data.getBiome(sLoc.getX(),sLoc.getZ()) == getBiome() &&
BlockUtils.isDirtLike(data.getType(sLoc.getX(),sLoc.getY(),sLoc.getZ()))) {
if (GenUtils.chance(random, 2, 10)) {
int choice = random.nextInt(3);
FractalTypes.Mushroom type;
switch(choice) {
case 0:
type = FractalTypes.Mushroom.GIANT_RED_MUSHROOM;
break;
case 1:
type = FractalTypes.Mushroom.GIANT_BROWN_MUSHROOM;
break;
default:
type = FractalTypes.Mushroom.GIANT_BROWN_FUNNEL_MUSHROOM;
break;
}
new MushroomBuilder(type).build(tw, data, sLoc.getX(),sLoc.getY(),sLoc.getZ());
} else if (TConfigOption.TREES_DARK_FOREST_BIG_ENABLED.getBoolean()) {
TreeDB.spawnBigDarkOakTree(tw, data, sLoc.getX(),sLoc.getY(),sLoc.getZ());
}
}
}
// Small trees
for (SimpleLocation sLoc : trees) {
int treeY = GenUtils.getHighestGround(data, sLoc.getX(), sLoc.getZ());
sLoc.setY(treeY);
if (data.getBiome(sLoc.getX(), sLoc.getZ()) == getBiome() &&
BlockUtils.isDirtLike(data.getType(sLoc.getX(),sLoc.getY(),sLoc.getZ()))) {
new FractalTreeBuilder(FractalTypes.Tree.DARK_OAK_SMALL)
.build(tw, data, sLoc.getX(),sLoc.getY()+1,sLoc.getZ());
}
}
// Small mushrooms and rocks
for (SimpleLocation sLoc : smallDecorations) {
int treeY = GenUtils.getHighestGround(data, sLoc.getX(), sLoc.getZ());
sLoc.setY(treeY);
if (data.getBiome(sLoc.getX(), sLoc.getZ()) == getBiome() &&
BlockUtils.isDirtLike(data.getType(sLoc.getX(),sLoc.getY(),sLoc.getZ()))) {
int choice = random.nextInt(5);
switch(choice) {
case 0:
new MushroomBuilder(FractalTypes.Mushroom.SMALL_POINTY_RED_MUSHROOM).build(tw, data, sLoc.getX(),sLoc.getY()+1,sLoc.getZ());
break;
case 1:
new MushroomBuilder(FractalTypes.Mushroom.SMALL_BROWN_MUSHROOM).build(tw, data, sLoc.getX(),sLoc.getY()+1,sLoc.getZ());
break;
case 2:
new MushroomBuilder(FractalTypes.Mushroom.SMALL_RED_MUSHROOM).build(tw, data, sLoc.getX(),sLoc.getY()+1,sLoc.getZ());
break;
case 3:
for (int i = 0; i < GenUtils.randInt(3, 6); i++) {
spawnRock(random, data, sLoc.getX(), sLoc.getY() + i + 1, sLoc.getZ());
}
break;
default:
new MushroomBuilder(FractalTypes.Mushroom.TINY_RED_MUSHROOM).build(tw, data, sLoc.getX(),sLoc.getY()+1,sLoc.getZ());
break;
}
}
}
}
private static void spawnRock(Random rand, PopulatorDataAbstract data, int x, int y, int z) {
ArrayList<int[]> locations = new ArrayList<>();
locations.add(new int[]{x, y, z});
locations.add(new int[]{x, y + 2, z});
locations.add(new int[]{x, y + 1, z});
locations.add(new int[]{x + 1, y + 1, z});
locations.add(new int[]{x - 1, y + 1, z});
locations.add(new int[]{x, y + 1, z + 1});
locations.add(new int[]{x, y + 1, z - 1});
locations.add(new int[]{x + 1, y, z});
locations.add(new int[]{x - 1, y, z});
locations.add(new int[]{x, y, z + 1});
locations.add(new int[]{x, y, z - 1});
locations.add(new int[]{x + 1, y, z});
locations.add(new int[]{x - 1, y, z + 1});
locations.add(new int[]{x + 1, y, z + 1});
locations.add(new int[]{x - 1, y, z - 1});
for (int[] coords : locations) {
int Tx = coords[0];
int Ty = coords[1];
int Tz = coords[2];
if (!data.getType(Tx, Ty, Tz).isSolid() ||
data.getType(Tx, Ty, Tz).toString().contains("LEAVES")) {
BlockUtils.setDownUntilSolid(Tx, Ty, Tz, data,
Material.COBBLESTONE, Material.MOSSY_COBBLESTONE,
Material.STONE, Material.CHISELED_STONE_BRICKS,
Material.STONE_BRICKS, Material.CRACKED_STONE_BRICKS,
Material.MOSSY_STONE_BRICKS);
}
}
}
public BiomeBank getBeachType() {
return BiomeBank.DARK_FOREST_BEACH;
}
//River type. This will be used instead if the heightmap got carved into a river.
public BiomeBank getRiverType() {
return BiomeBank.DARK_FOREST_RIVER;
}
}
| 42.211823 | 141 | 0.55269 |
f47ff4f0e1ec4bdf1306ca363c0c2a985d95e870 | 3,765 | /*
* Created by Orchextra
*
* Copyright (C) 2016 Gigigo Mobile Services SL
*
* 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 gigigo.com.orchextra.data.datasources.db.model.mappers;
import com.gigigo.gggjavalib.general.utils.DateFormatConstants;
import com.gigigo.gggjavalib.general.utils.DateUtils;
import com.gigigo.ggglib.mappers.Mapper;
import com.gigigo.ggglib.mappers.MapperUtils;
import com.gigigo.orchextra.domain.model.ProximityItemType;
import com.gigigo.orchextra.domain.model.entities.geofences.OrchextraGeofence;
import com.gigigo.orchextra.domain.model.vo.OrchextraLocationPoint;
import gigigo.com.orchextra.data.datasources.db.model.GeofenceRealm;
import gigigo.com.orchextra.data.datasources.db.model.RealmPoint;
public class GeofenceRealmMapper implements Mapper<OrchextraGeofence, GeofenceRealm> {
private final Mapper<OrchextraLocationPoint, RealmPoint> realmPointMapper;
public GeofenceRealmMapper(Mapper realmPointMapper) {
this.realmPointMapper = realmPointMapper;
}
@Override
public GeofenceRealm modelToExternalClass(OrchextraGeofence geofence) {
GeofenceRealm geofenceRealm = new GeofenceRealm();
geofenceRealm.setRadius(geofence.getRadius());
geofenceRealm.setPoint(MapperUtils.checkNullDataRequest(realmPointMapper, geofence.getPoint()));
geofenceRealm.setCode(geofence.getCode());
geofenceRealm.setId(geofence.getId());
geofenceRealm.setName(geofence.getName());
geofenceRealm.setNotifyOnEntry(geofence.isNotifyOnEntry());
geofenceRealm.setNotifyOnExit(geofence.isNotifyOnExit());
geofenceRealm.setStayTime(geofence.getStayTime());
if (geofence.getType() != null) {
geofenceRealm.setType(geofence.getType().getStringValue());
}
geofenceRealm.setCreatedAt(
DateUtils.dateToStringWithFormat(geofence.getCreatedAt(), DateFormatConstants.DATE_FORMAT_TIME));
geofenceRealm.setUpdatedAt(
DateUtils.dateToStringWithFormat(geofence.getUpdatedAt(), DateFormatConstants.DATE_FORMAT_TIME));
return geofenceRealm;
}
@Override
public OrchextraGeofence externalClassToModel(GeofenceRealm geofenceRealm) {
OrchextraGeofence geofence = new OrchextraGeofence();
geofence.setRadius(geofenceRealm.getRadius());
geofence.setPoint(
MapperUtils.checkNullDataResponse(realmPointMapper, geofenceRealm.getPoint()));
geofence.setCode(geofenceRealm.getCode());
geofence.setId(geofenceRealm.getId());
geofence.setName(geofenceRealm.getName());
geofence.setNotifyOnEntry(geofenceRealm.getNotifyOnEntry());
geofence.setNotifyOnExit(geofenceRealm.getNotifyOnExit());
geofence.setStayTime(geofenceRealm.getStayTime());
geofence.setType(ProximityItemType.getProximityPointTypeValue(geofenceRealm.getType()));
geofence.setCreatedAt(DateUtils.stringToDateWithFormat(geofenceRealm.getCreatedAt(),
DateFormatConstants.DATE_FORMAT_TIME));
geofence.setUpdatedAt(DateUtils.stringToDateWithFormat(geofenceRealm.getUpdatedAt(),
DateFormatConstants.DATE_FORMAT_TIME));
return geofence;
}
}
| 40.483871 | 113 | 0.74927 |
0d33b430c798fd53039d7de666543517c8603531 | 3,416 | /*
* Copyright 2017 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.spring;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import org.assertj.core.api.Condition;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.linecorp.armeria.common.metric.MoreMeters;
import com.linecorp.armeria.spring.ArmeriaMeterBindersConfigurationTest.TestConfiguration;
import io.micrometer.core.instrument.MeterRegistry;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@ActiveProfiles({ "local", "autoConfTest" })
@DirtiesContext
public class ArmeriaMeterBindersConfigurationTest {
@SpringBootApplication
@Import(ArmeriaOkServiceConfiguration.class)
public static class TestConfiguration {
}
@Rule
public TestRule globalTimeout = new DisableOnDebug(new Timeout(10, TimeUnit.SECONDS));
@Inject
private MeterRegistry registry;
@Test
public void testDefaultMetrics() throws Exception {
final Map<String, Double> measurements = MoreMeters.measureAll(registry);
assertThat(measurements).containsKeys(
"jvm.buffer.count#value{id=direct}",
"jvm.classes.loaded#value",
"jvm.threads.daemon#value",
"logback.events#count{level=debug}",
"process.uptime#value",
"system.cpu.count#value");
// Use prefix-matching for meter IDs because JVM memory meters differ between JVM versions.
assertThat(measurements).hasKeySatisfying(new Condition<>(
key -> key.startsWith("jvm.memory.max#value{area=nonheap,id="),
"MeterRegistry must contain JVM memory meters"));
final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
boolean hasOpenFdCount = false;
try {
os.getClass().getDeclaredMethod("getOpenFileDescriptorCount");
hasOpenFdCount = true;
} catch (Exception ignored) {
// Not supported
}
if (hasOpenFdCount) {
assertThat(measurements).containsKeys("process.files.open#value");
}
}
}
| 36.731183 | 99 | 0.732436 |
f09383feaea4cb0d868f9730b49e655b6b915d8f | 8,414 | package com.plume.code.core;
import cn.hutool.core.util.ZipUtil;
import com.plume.code.core.common.enums.ControllerOption;
import com.plume.code.core.common.enums.PortalOption;
import com.plume.code.core.common.enums.ServiceOption;
import com.plume.code.core.common.helper.PathHelper;
import com.plume.code.core.common.model.ConnectionModel;
import com.plume.code.core.common.model.GeneratorConfigModel;
import com.plume.code.core.common.model.SettingModel;
import com.plume.code.core.database.DatabaseBehavior;
import com.plume.code.core.database.DatabaseBehaviorFactory;
import com.plume.code.core.database.model.ClassModel;
import com.plume.code.core.database.model.ContextModel;
import com.plume.code.core.database.model.FieldModel;
import com.plume.code.core.database.model.ResultModel;
import com.plume.code.core.generator.GeneratorBehavior;
import com.plume.code.core.generator.GeneratorBehaviorFactory;
import lombok.SneakyThrows;
import org.h2.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class GeneratorFacade {
private static final Logger logger = LoggerFactory.getLogger(GeneratorFacade.class);
@Autowired
protected DatabaseBehaviorFactory databaseBehaviorFactory;
@Autowired
protected GeneratorBehaviorFactory generatorBehaviorFactory;
public ResultModel generate(GeneratorConfigModel generatorConfigModel) {
handleTemplate(generatorConfigModel);
return generate(generatorConfigModel.getConnectionModel(), generatorConfigModel.getSettingModel());
}
private void handleTemplate(GeneratorConfigModel generatorConfigModel) {
if (!CollectionUtils.isEmpty(generatorConfigModel.getSettingModel().getTemplateNameSet())) {
return;
}
Set<String> templateSet = new HashSet<>();
if (generatorConfigModel.getPortal().contains(PortalOption.ElementUI)) {
templateSet.addAll(Arrays.asList(
"ElementUi-api.js.tpl",
"ElementUi-Dialog.vue.tpl",
"ElementUi-index.js.tpl",
"ElementUi-Main.vue.tpl",
"ElementUi-object.js.tpl",
"ElementUi-Search.vue.tpl"));
}
if (generatorConfigModel.getController().contains(ControllerOption.VO)) {
templateSet.add("VO.java.tpl");
}
if (generatorConfigModel.getController().contains(ControllerOption.Query)) {
templateSet.add("Query.java.tpl");
}
if (generatorConfigModel.getService().contains(ServiceOption.DTO)) {
templateSet.add("DTO.java.tpl");
}
switch (generatorConfigModel.getRepository()) {
case MybatisPlus:
templateSet.addAll(Arrays.asList("MybatisPlus-ENT.java.tpl", "MybatisPlus-Mapper.java.tpl"));
templateSet.addAll(Arrays.asList("MybatisPlus-Service.java.tpl", "MybatisPlus-ServiceImpl.java.tpl"));
templateSet.addAll(Arrays.asList("MybatisPlus-Controller.java.tpl"));
break;
case JPA:
case Hibernate:
templateSet.addAll(Arrays.asList("Jpa-ENT.java.ftl", "Jpa-ENT-PK.java.ftl", "Jpa-Repository.java.tpl"));
templateSet.addAll(Arrays.asList("Jpa-Service.java.tpl", "Jpa-ServiceImpl.java.tpl"));
templateSet.addAll(Arrays.asList("Jpa-Controller.java.tpl"));
break;
case Mybatis:
templateSet.addAll(Arrays.asList("Mybatis-ENT.java.tpl", "Mybatis-Mapper.xml.tpl", "Mybatis-Mapper.java.tpl"));
templateSet.addAll(Arrays.asList("Mybatis-Service.java.tpl", "Mybatis-ServiceImpl.java.tpl"));
templateSet.addAll(Arrays.asList("Mybatis-Controller.java.tpl"));
break;
case TkMybatis:
templateSet.addAll(Arrays.asList("Mybatis-ENT.java.tpl", "Mybatis-TK-Mapper.xml.tpl", "Mybatis-TK-Mapper.java.tpl"));
templateSet.addAll(Arrays.asList("Mybatis-Service.java.tpl", "Mybatis-TK-ServiceImpl.java.tpl"));
templateSet.addAll(Arrays.asList("Mybatis-Controller.java.tpl"));
break;
default:
templateSet.addAll(Arrays.asList("Service.java.tpl", "ServiceImpl.java.tpl", "Jpa-ENT.java.tpl"));
templateSet.addAll(Arrays.asList("Controller.java.tpl"));
}
generatorConfigModel.getSettingModel().setTemplateNameSet(templateSet);
}
@SneakyThrows
public ResultModel generate(ConnectionModel connectionModel, SettingModel settingModel) {
setDefault(settingModel);
List<GeneratorBehavior> generatorBehaviorList = getGeneratorBehaviorList(connectionModel, settingModel);
if (CollectionUtils.isEmpty(generatorBehaviorList)) {
throw new RuntimeException("generatorBehaviorList is empty");
}
generatorBehaviorList.forEach(GeneratorBehavior::generate);
String downloadPath = PathHelper.getDownloadPath(settingModel.getDownloadPath());
String directoryPath = downloadPath.concat(settingModel.getBatchNo());
if (!(new File(directoryPath).exists())) {
throw new FileNotFoundException(directoryPath);
}
logger.info("[plume-code] 文件生成完毕 目录:{}", directoryPath);
File zip = ZipUtil.zip(directoryPath);
logger.info("[plume-code] 文件zip生成 路径:{}", zip.getAbsolutePath());
return ResultModel.builder()
.batchNo(settingModel.getBatchNo())
.directoryPath(directoryPath)
.zipPath(zip.getPath())
.build();
}
public List<GeneratorBehavior> getGeneratorBehaviorList(ConnectionModel connectionModel, SettingModel settingModel) {
List<ContextModel> contextModelList = getContextModelList(connectionModel, settingModel);
return contextModelList.stream().map(contextModel ->
generatorBehaviorFactory.getGeneratorBehaviorList(contextModel)
).flatMap(Collection::stream).collect(Collectors.toList());
}
public List<ContextModel> getContextModelList(ConnectionModel connectionModel, SettingModel settingModel) {
DatabaseBehavior databaseBehavior = databaseBehaviorFactory.getDatabaseBehavior(connectionModel);
if (CollectionUtils.isEmpty(settingModel.getTableNameSet())) {
return Collections.emptyList();
}
List<ClassModel> classModels = databaseBehavior.listClassModel(settingModel);
List<ContextModel> contextModels = new ArrayList<>();
for (ClassModel classModel : classModels) {
if (!settingModel.getTableNameSet().contains(classModel.getTableName())) {
continue;
}
List<FieldModel> fieldModels = databaseBehavior.listFieldModel(settingModel, classModel.getTableName());
ContextModel contextModel = ContextModel.builder()
.connectionModel(connectionModel)
.settingModel(settingModel)
.classModel(classModel)
.fieldModelList(fieldModels)
.build();
contextModels.add(contextModel);
}
return contextModels;
}
private void setDefault(SettingModel settingModel) {
if (StringUtils.isNullOrEmpty(settingModel.getBatchNo())) {
settingModel.setBatchNo(String.valueOf(System.currentTimeMillis()));
}
if (StringUtils.isNullOrEmpty(settingModel.getDtoPostfix())) {
settingModel.setDtoPostfix("DTO");
}
if (StringUtils.isNullOrEmpty(settingModel.getEntPostfix())) {
settingModel.setEntPostfix("ENT");
}
if (StringUtils.isNullOrEmpty(settingModel.getVoPostfix())) {
settingModel.setVoPostfix("VO");
}
if (StringUtils.isNullOrEmpty(settingModel.getQueryPostfix())) {
settingModel.setQueryPostfix("Query");
}
if (null == settingModel.getLombokState()) {
settingModel.setLombokState(false);
}
}
}
| 42.928571 | 133 | 0.677086 |
b8dda96801d2713257ca955d90ae46b20e447a40 | 3,056 | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.samplers;
import java.lang.management.ManagementFactory;
import java.text.MessageFormat;
import java.util.logging.Level;
import com.newrelic.agent.Agent;
import com.newrelic.agent.MetricNames;
import com.newrelic.agent.stats.StatsEngine;
import com.newrelic.agent.util.TimeConversion;
/**
* Samples CPU utilization using JMX. Java 1.5 required.
*
* This class is not thread-safe.
*/
public abstract class AbstractCPUSampler {
private double lastCPUTimeSeconds;
private long lastTimestampNanos;
private final int processorCount;
protected AbstractCPUSampler() {
processorCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
Agent.LOG.finer(processorCount + " processor(s)");
}
/**
* Returns the process cpu time in seconds.
*
*/
protected abstract double getProcessCpuTime();
protected void recordCPU(StatsEngine statsEngine) {
double currentProcessTime = getProcessCpuTime();
double dCPU = currentProcessTime - lastCPUTimeSeconds;
lastCPUTimeSeconds = currentProcessTime;
long now = System.nanoTime();
long elapsedNanos = now - lastTimestampNanos;
lastTimestampNanos = now;
double elapsedTime = TimeConversion.convertNanosToSeconds(elapsedNanos);
double utilization = dCPU / (elapsedTime * processorCount);
boolean shouldLog = Agent.LOG.isLoggable(Level.FINER);
if (shouldLog) {
String msg = MessageFormat.format("Recorded CPU time: {0} ({1}) {2}", dCPU, utilization,
getClass().getName());
Agent.LOG.finer(msg);
}
if (lastCPUTimeSeconds > 0 && dCPU >= 0) {
if (Double.isNaN(dCPU) || Double.isInfinite(dCPU)) {
if (shouldLog) {
String msg = MessageFormat.format("Infinite or non-number CPU time: {0} (current) - {1} (last)",
currentProcessTime, lastCPUTimeSeconds);
Agent.LOG.finer(msg);
}
} else {
statsEngine.getStats(MetricNames.CPU).recordDataPoint((float) dCPU);
}
if (Double.isNaN(utilization) || Double.isInfinite(utilization)) {
if (shouldLog) {
String msg = MessageFormat.format("Infinite or non-number CPU utilization: {0} ({1})", utilization,
dCPU);
Agent.LOG.finer(msg);
}
} else {
statsEngine.getStats(MetricNames.CPU_UTILIZATION).recordDataPoint((float) utilization);
}
} else {
if (shouldLog) {
String msg = MessageFormat.format("Bad CPU time: {0} (current) - {1} (last)", currentProcessTime,
lastCPUTimeSeconds);
Agent.LOG.finer(msg);
}
}
}
}
| 35.126437 | 119 | 0.608312 |
1b5895eb3f94c201d9f61734b595866c0ced34f5 | 4,885 | package com.rank.rss;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import javax.xml.ws.Response;
import org.apache.log4j.BasicConfigurator;
import org.apache.lucene.search.vectorhighlight.FieldQuery;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryBuilders.*;
import edu.stanford.nlp.dcoref.CoNLL2011DocumentReader.Document;
import static org.elasticsearch.node.NodeBuilder.*;
public class ElasticSearch {
private Client client;
// A bulk request holds an ordered IndexRequests and DeleteRequests and
// allows to executes it in a single batch
private BulkRequestBuilder bulkRequest;
public ElasticSearch() {
Node node = nodeBuilder()
.settings(Settings.settingsBuilder().put("http.enabled", false).put("path.home", "/elasticsearch"))
.client(true).node();
client = node.client();
bulkRequest = client.prepareBulk();
}
public Client getClient() {
return this.client;
}
public void bulkIndexDocument(String document, String index, String type, String id) {
// adds an index request to the list of actions to execute.
bulkRequest.add(client.prepareIndex(index, type, id).setSource(document));
}
public boolean outputJson(String content) {
try {
File file = new File("C:\\Users\\ACA4\\Documents\\Debug.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\r\n");
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void excuteBulkIndex() {
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
///
if (bulkResponse.hasFailures()) {
// process failures by iterating through each bulk response item
System.out.println("Iterate through each bulk item to find the error");
outputJson(bulkResponse.buildFailureMessage());
}
}
public void deleteIndex(String index) {
try {
System.out.printf("deleting search index {%s}", index);
client.admin().indices().delete(new DeleteIndexRequest(index)).actionGet();
} catch (Exception ex) {
System.out.printf("Cannot delete index {%s} because it doesn't exist.", index);
}
}
public String searchByDate(int dateRange, String index) {
Calendar currentDate = Calendar.getInstance(); // Get the current date
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); // format
// it as
// per
// your
// requirement
String dateNow = formatter.format(currentDate.getTime());
currentDate.add(Calendar.DATE, -1 * dateRange);
String fromNow = formatter.format(currentDate.getTime());
SearchResponse response = client.prepareSearch(index)
.setQuery(QueryBuilders.rangeQuery("_type").to(dateNow).from(fromNow)).execute().actionGet();
return response.toString();
}
public String searchByKeywordList(ArrayList<String> keySet, String index) {
MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keySet, "keywords");
SearchResponse response = client.prepareSearch(index).setQuery(queryBuilder).execute().actionGet();
return response.toString();
}
public void showAllData() {
SearchResponse response = client.prepareSearch().execute().actionGet();
System.out.println(response.toString());
}
public void refresh() {
client.admin().indices().prepareRefresh().execute().actionGet();
}
public static void main(String[] args) {
// BasicConfigurator.configure();
ElasticSearch es = new ElasticSearch();
// es.indexDocument("");
// es.indexDocument("");
// es.getResponse();
// es.SearchResponse2();
}
}
| 33.689655 | 104 | 0.723439 |
609d1edea952648f9f732c33e354f60fe8ed147a | 12,146 | /*
* Copyright 2013-2016, Kasra Faghihi
*
* 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.offbynull.portmapper.mappers.pcp.externalmessages;
import com.offbynull.portmapper.helpers.NetworkUtils;
import java.net.InetAddress;
import java.nio.BufferUnderflowException; // NOPMD Javadoc not recognized (fixed in latest PMD but maven plugin has to catch up)
import java.util.Arrays;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
/**
* Represents a MAP PCP response. From the RFC:
* <pre>
* The following diagram shows the format of Opcode-specific information
* in a response packet for the MAP Opcode:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* | Mapping Nonce (96 bits) |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Protocol | Reserved (24 bits) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Internal Port | Assigned External Port |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* | Assigned External IP Address (128 bits) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Figure 10: MAP Opcode Response
*
* These fields are described below:
*
* Lifetime (in common header): On an error response, this indicates
* how long clients should assume they'll get the same error response
* from the PCP server if they repeat the same request. On a success
* response, this indicates the lifetime for this mapping, in
* seconds.
*
* Mapping Nonce: Copied from the request.
*
* Protocol: Copied from the request.
*
* Reserved: 24 reserved bits, MUST be sent as 0 and MUST be ignored
* when received.
*
* Internal Port: Copied from the request.
*
* Assigned External Port: On a success response, this is the assigned
* external port for the mapping. On an error response, the
* suggested external port is copied from the request.
*
* Assigned External IP Address: On a success response, this is the
* assigned external IPv4 or IPv6 address for the mapping. An IPv4
* address is encoded using IPv4-mapped IPv6 address. On an error
* response, the suggested external IP address is copied from the
* request.
* </pre>
* @author Kasra Faghihi
*/
public final class MapPcpResponse extends PcpResponse {
private static final int OPCODE = 1;
private static final int DATA_LENGTH = 36;
private static final int NONCE_LENGTH = 12;
private byte[] mappingNonce;
private int protocol;
private int internalPort;
private int assignedExternalPort;
private InetAddress assignedExternalIpAddress;
/**
* Constructs a {@link MapPcpResponse} object.
* @param mappingNonce random value used to map requests to responses
* @param protocol IANA protocol number
* @param internalPort internal port
* @param assignedExternalPort assigned external port
* @param assignedExternalIpAddress assigned external IP address
* @param lifetime lifetime in seconds
* @param epochTime server's epoch time in seconds
* @param resultCode result code
* @param options PCP options to use
* @throws NullPointerException if any argument is {@code null} or contains {@code null}
* @throws IllegalArgumentException if {@code 0L > lifetime > 0xFFFFFFFFL || mappingNonce.length != 12 || 0 > protocol > 255
* || 0 > internalPort > 65535 || (resultCode == 0 ? 1 > assignedExternalPort > 65535 : 0 > assignedExternalPort > 65535)}
*/
public MapPcpResponse(byte[] mappingNonce, int protocol, int internalPort, int assignedExternalPort,
InetAddress assignedExternalIpAddress, int resultCode, long lifetime, long epochTime, PcpOption ... options) {
super(OPCODE, resultCode, lifetime, epochTime, DATA_LENGTH, options);
Validate.notNull(mappingNonce);
Validate.notNull(assignedExternalIpAddress);
this.mappingNonce = Arrays.copyOf(mappingNonce, mappingNonce.length);
this.protocol = protocol;
this.internalPort = internalPort;
this.assignedExternalPort = assignedExternalPort;
this.assignedExternalIpAddress = assignedExternalIpAddress; // for any ipv4 must be ::ffff:0:0, for any ipv6 must be ::
validateState();
}
/**
* Constructs a {@link MapPcpResponse} object by parsing a buffer.
* @param buffer buffer containing PCP response data
* @throws NullPointerException if any argument is {@code null}
* @throws BufferUnderflowException if not enough data is available in {@code buffer}
* @throws IllegalArgumentException if there's not enough or too much data remaining in the buffer, or if the version doesn't match the
* expected version (must always be {@code 2}), or if the r-flag isn't set, or if there's an unsuccessful/unrecognized result code,
* or if the op code doesn't match the MAP opcode, or if the response has a {@code 0} for its {@code internalPort} or
* {@code assignedExternalPort} field, or if there were problems parsing options
* @throws IllegalArgumentException if any numeric argument is negative, or if {@code buffer} isn't the right size (max of 1100 bytes)
* or is malformed ({@code r-flag != 1 || op != 1 || 0L > lifetime > 0xFFFFFFFFL || mappingNonce.length != 12 || 0 > protocol > 255
* || 0 > internalPort > 65535 || (resultCode == 0 && lifetime != 0 ? 1 > assignedExternalPort > 65535 : 0 > assignedExternalPort >
* 65535)}) or contains an unparseable options region.
*/
public MapPcpResponse(byte[] buffer) {
super(buffer, DATA_LENGTH);
Validate.isTrue(super.getOp() == OPCODE);
int offset = HEADER_LENGTH;
mappingNonce = new byte[NONCE_LENGTH];
System.arraycopy(buffer, offset, mappingNonce, 0, mappingNonce.length);
offset += mappingNonce.length;
protocol = buffer[offset] & 0xFF;
offset++;
offset += 3; // 3 reserved bytes
internalPort = InternalUtils.bytesToShort(buffer, offset) & 0xFFFF;
offset += 2;
assignedExternalPort = InternalUtils.bytesToShort(buffer, offset) & 0xFFFF;
offset += 2;
assignedExternalIpAddress = NetworkUtils.convertBytesToAddress(buffer, offset, 16);
offset += 16;
validateState();
}
private void validateState() {
Validate.notNull(mappingNonce);
Validate.isTrue(mappingNonce.length == NONCE_LENGTH);
Validate.inclusiveBetween(0, 255, protocol); // copied from the request, see javadoc for request to see what 0 means
Validate.inclusiveBetween(0, 65535, internalPort); // copied from the request, see javadoc for request to see what 0 means...
// 0 is valid in certain cases, but those cases can't be checked here.
if (getResultCode() == 0 && getLifetime() != 0L) { // lifetime of 0 meeans delete
Validate.inclusiveBetween(1, 65535, assignedExternalPort); // on success, this is the assigned external port for the mapping
// ... which must be between 1 and 65535 (unless its a delete)
} else {
Validate.inclusiveBetween(0, 65535, assignedExternalPort); // on error, 'suggested external port' copied from request (can be 0)
}
Validate.notNull(assignedExternalIpAddress);
}
@Override
public byte[] getData() {
byte[] data = new byte[DATA_LENGTH];
int offset = 0;
System.arraycopy(mappingNonce, 0, data, offset, mappingNonce.length);
offset += mappingNonce.length;
data[offset] = (byte) protocol;
offset++;
offset += 3; // 3 reserved bytes
InternalUtils.shortToBytes(data, offset, (short) internalPort);
offset += 2;
InternalUtils.shortToBytes(data, offset, (short) assignedExternalPort);
offset += 2;
byte[] ipv6Array = NetworkUtils.convertAddressToIpv6Bytes(assignedExternalIpAddress);
System.arraycopy(ipv6Array, 0, data, offset, ipv6Array.length);
offset += ipv6Array.length;
return data;
}
/**
* Get nonce.
* @return nonce
*/
public byte[] getMappingNonce() {
return Arrays.copyOf(mappingNonce, mappingNonce.length);
}
/**
* Get IANA protocol number.
* @return IANA protocol number
*/
public int getProtocol() {
return protocol;
}
/**
* Get internal port number.
* @return internal port number
*/
public int getInternalPort() {
return internalPort;
}
/**
* Get assigned external port number.
* @return assigned external port number
*/
public int getAssignedExternalPort() {
return assignedExternalPort;
}
/**
* Get assigned external IP address.
* @return assigned external IP address
*/
public InetAddress getAssignedExternalIpAddress() {
return assignedExternalIpAddress;
}
@Override
public String toString() {
return "MapPcpResponse{super=" + super.toString() + "mappingNonce=" + Arrays.toString(mappingNonce) + ", protocol=" + protocol
+ ", internalPort=" + internalPort + ", assignedExternalPort=" + assignedExternalPort + ", assignedExternalIpAddress="
+ assignedExternalIpAddress + '}';
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 79 * hash + Arrays.hashCode(this.mappingNonce);
hash = 79 * hash + this.protocol;
hash = 79 * hash + this.internalPort;
hash = 79 * hash + this.assignedExternalPort;
hash = 79 * hash + Objects.hashCode(this.assignedExternalIpAddress);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MapPcpResponse other = (MapPcpResponse) obj;
if (this.protocol != other.protocol) {
return false;
}
if (this.internalPort != other.internalPort) {
return false;
}
if (this.assignedExternalPort != other.assignedExternalPort) {
return false;
}
if (!Arrays.equals(this.mappingNonce, other.mappingNonce)) {
return false;
}
if (!Objects.equals(this.assignedExternalIpAddress, other.assignedExternalIpAddress)) {
return false;
}
return true;
}
}
| 41.172881 | 140 | 0.593446 |
b48103b303b2b9980506feda8fc3858e9c76d43d | 2,252 | package model;
import exceptions.CarWrongDataException;
public class Car {
private String model;
private int year;
private double engine;
private boolean ac;
public Car() {
}
public Car(String model,int year,double engine,boolean ac) throws CarWrongDataException {
try {
setModel(model);
} catch (CarWrongDataException e) {
System.out.println("model is set to default:\"no model name\"");
this.model = "no model name";
}
try {
setYear(year);
} catch (CarWrongDataException e) {
System.out.println("year is set to default: -10000");
this.year = -10000;
}
try {
setEngine(engine);
} catch (CarWrongDataException e) {
System.out.println("engine is set to default: -1.0");
this.engine = -1.;
}
try {
setAc(ac);
} catch (CarWrongDataException e) {
System.out.println("ac is set to default: false");
this.ac=false;
}
}
public String getModel() {
return model;
}
public void setModel(String model) throws CarWrongDataException {
if(model==null) {
throw new CarWrongDataException("model is null");
}
else if (model.length()==0) {
throw new CarWrongDataException("model is empty");
}
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) throws CarWrongDataException {
if(year<1930) {
throw new CarWrongDataException("year before 1930: " + year);
}
else if(year > 2019) {
throw new CarWrongDataException("year is greather than 2019");
}
this.year = year;
}
public double getEngine() {
return engine;
}
public void setEngine(double engine) throws CarWrongDataException {
if(engine<0.3) {
throw new CarWrongDataException("engine volume less than 0.3: " + engine);
}
else if(engine>5.) {
throw new CarWrongDataException("engine volume greather than 5.: " + engine);
}
this.engine = engine;
}
public boolean isAc() {
return ac;
}
public void setAc(boolean ac) throws CarWrongDataException {
if(year<1990 && ac) {
throw new CarWrongDataException("AC can't exist by Cars where year less then 1990");
}
this.ac = ac;
}
@Override
public String toString() {
return "Car [model=" + model + ", year=" + year + ", engine=" + engine + ", ac=" + ac + "]";
}
}
| 21.864078 | 94 | 0.665187 |
e81bac30578c163f0715110b91675f70adaac33c | 1,698 | /**
* Copyright (C) 2009 Lambico Team <lucio.benfante@gmail.com>
*
* This file is part of Lambico Example - Console Spring Hibernate.
*
* 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.lambico.example.consolespringhibernate.dao;
import org.lambico.example.consolespringhibernate.dao.BookDao;
import java.util.List;
import javax.annotation.Resource;
import org.lambico.example.consolespringhibernate.po.Book;
import org.lambico.example.consolespringhibernate.po.Person;
import org.lambico.example.consolespringhibernate.test.BaseTest;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author Enrico Giurin
*/
public class BookDaoTest extends BaseTest {
@Resource
private BookDao bookDao;
public void testAllBooksByBorrower() {
List<Book> list = bookDao.allBooksByBorrower("Ugo", "Benfante");
assertEquals(2, list.size());
}
public void testFindByAuthor() {
List<Book> books = bookDao.findByAuthor("Doug Lea");
assertEquals(1, books.size());
assertEquals(books.get(0).getTitle(), "Concurrent programming in java second edition");
}
}
| 29.789474 | 95 | 0.71967 |
4de3269873b1733cb4beb40aeec19c78c1e2561c | 66 | package com.pk.timeapi.instant;
public class InstantTest {
}
| 13.2 | 32 | 0.727273 |
e499849abf0de6bf212cbbdf8537b4112bd34e89 | 808 | /**
* Leetcode - remove_element
*/
package com.duol.leetcode.y21.m3.d30.no27.remove_element;
import java.util.*;
import com.duol.common.*;
/**
* log instance is defined in Solution interface
* this is how slf4j will work in this class:
* =============================================
* if (log.isDebugEnabled()) {
* log.debug("a + b = {}", sum);
* }
* =============================================
*/
class Solution1 implements Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
}
| 21.837838 | 57 | 0.438119 |
48736a46340ba9f06e882b2e8a21244e26fe0786 | 20,771 | /*
* Copyright (c) 2018, Tomas Slusny <slusnucky@gmail.com>
* Copyright (c) 2018, PandahRS <https://github.com/PandahRS>
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.machpi.runelite.influxdb.activity;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.runelite.api.Client;
import net.runelite.api.Skill;
import net.runelite.api.Varbits;
import javax.annotation.Nullable;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
enum LocationType {
BOSSES,
CITIES,
DUNGEONS,
MINIGAMES,
RAIDS,
POI,
;
}
@AllArgsConstructor
@Getter
public enum GameEvent {
IN_GAME("In Game", -3),
IN_MENU("In Menu", -3),
PLAYING_DEADMAN("Playing Deadman Mode", -3),
PLAYING_PVP("Playing in a PVP world", -3),
WILDERNESS("Wilderness", -2),
TRAINING_ATTACK(Skill.ATTACK),
TRAINING_DEFENCE(Skill.DEFENCE),
TRAINING_STRENGTH(Skill.STRENGTH),
TRAINING_HITPOINTS(Skill.HITPOINTS, -1),
TRAINING_SLAYER(Skill.SLAYER, 1),
TRAINING_RANGED(Skill.RANGED),
TRAINING_MAGIC(Skill.MAGIC),
TRAINING_PRAYER(Skill.PRAYER),
TRAINING_COOKING(Skill.COOKING),
TRAINING_WOODCUTTING(Skill.WOODCUTTING),
TRAINING_FLETCHING(Skill.FLETCHING),
TRAINING_FISHING(Skill.FISHING, 1),
TRAINING_FIREMAKING(Skill.FIREMAKING),
TRAINING_CRAFTING(Skill.CRAFTING),
TRAINING_SMITHING(Skill.SMITHING),
TRAINING_MINING(Skill.MINING),
TRAINING_HERBLORE(Skill.HERBLORE),
TRAINING_AGILITY(Skill.AGILITY),
TRAINING_THIEVING(Skill.THIEVING),
TRAINING_FARMING(Skill.FARMING),
TRAINING_RUNECRAFT(Skill.RUNECRAFT),
TRAINING_HUNTER(Skill.HUNTER),
TRAINING_CONSTRUCTION(Skill.CONSTRUCTION),
// Bosses
BOSS_ABYSSAL_SIRE("Abyssal Sire", LocationType.BOSSES, 11851, 11850, 12363, 12362),
BOSS_CERBERUS("Cerberus", LocationType.BOSSES, 4883, 5140, 5395),
BOSS_COMMANDER_ZILYANA("Commander Zilyana", LocationType.BOSSES, 11602),
BOSS_DKS("Dagannoth Kings", LocationType.BOSSES, 11588, 11589),
BOSS_GENERAL_GRAARDOR("General Graardor", LocationType.BOSSES, 11347),
BOSS_GIANT_MOLE("Giant Mole", LocationType.BOSSES, 6993, 6992),
BOSS_GROTESQUE_GUARDIANS("Grotesque Guardians", LocationType.BOSSES, 6727),
BOSS_HYDRA("Alchemical Hydra", LocationType.BOSSES, 5536),
BOSS_KING_BLACK_DRAGON("King Black Dragon", LocationType.BOSSES), // no region id.. custom logic for kbd/nmz
BOSS_KQ("Kalphite Queen", LocationType.BOSSES, 13972),
BOSS_KRAKEN("Kraken", LocationType.BOSSES, 9116),
BOSS_KREEARRA("Kree'arra", LocationType.BOSSES, 11346),
BOSS_KRIL_TSUTSAROTH("K'ril Tsutsaroth", LocationType.BOSSES, 11603),
BOSS_SKOTIZO("Skotizo", LocationType.BOSSES, 6810),
BOSS_SMOKE_DEVIL("Thermonuclear smoke devil", LocationType.BOSSES, 9363, 9619),
BOSS_VORKATH("Vorkath", LocationType.BOSSES, 9023),
BOSS_WINTERTODT("Wintertodt", LocationType.BOSSES, 6462),
BOSS_ZALCANO("Zalcano", LocationType.BOSSES, 13250),
BOSS_ZULRAH("Zulrah", LocationType.BOSSES, 9007, 9008),
BOSS_NIGHTMARE("Nightmare of Ashihama", LocationType.BOSSES, 15515),
// Cities
CITY_AL_KHARID("Al Kharid", LocationType.CITIES, 13105, 13106),
CITY_APE_ATOLL("Ape Atoll", LocationType.CITIES, 10795, 11051, 10974, 11050),
CITY_ARCEUUS_HOUSE("Arceuus", LocationType.CITIES, 6459, 6715, 6458, 6714),
CITY_ARDOUGNE("Ardougne", LocationType.CITIES, 10548, 10547, 10292, 10291, 10036, 10035, 9780, 9779),
CITY_BARBARIAN_VILLAGE("Barbarian Village", LocationType.CITIES, 12341),
CITY_BANDIT_CAMP("Bandit Camp", LocationType.CITIES, 12591),
CITY_BEDABIN_CAMP("Bedabin Camp", LocationType.CITIES, 12590),
CITY_BRIMHAVEN("Brimhaven", LocationType.CITIES, 11057, 11058),
CITY_BURGH_DE_ROTT("Burgh de Rott", LocationType.CITIES, 13874, 13873, 14130, 14129),
CITY_BURTHORPE("Burthorpe", LocationType.CITIES, 11319, 11575),
CITY_CANIFIS("Canifis", LocationType.CITIES, 13878),
CITY_CATHERBY("Catherby", LocationType.CITIES, 11317, 11318, 11061),
CITY_CORSAIR_CAVE("Corsair Cove", LocationType.CITIES, 10028, 10284),
CITY_DARKMEYER("Darkmeyer", LocationType.CITIES, 14388),
CITY_DORGESH_KAAN("Dorgesh-Kaan", LocationType.CITIES, 10835, 10834),
CITY_DRAYNOR("Draynor", LocationType.CITIES, 12338),
CITY_EDGEVILLE("Edgeville", LocationType.CITIES, 12342),
CITY_ENTRANA("Entrana", LocationType.CITIES, 11060, 11316),
CITY_FALADOR("Falador", LocationType.CITIES, 11828, 11572, 11571, 11827, 12084),
CITY_GOBLIN_VILLAGE("Goblin Village", LocationType.CITIES, 11830),
CITY_GUTANOTH("Gu'Tanoth", LocationType.CITIES, 10031),
CITY_GWENITH("Gwenith", LocationType.CITIES, 8501, 8757, 9013),
CITY_HOSIDIUS_HOUSE("Hosidius", LocationType.CITIES, 6713, 6712, 6455, 6711, 6710, 6965, 6966, 7222, 7223, 6967),
CITY_JATISZO("Jatizso", LocationType.CITIES, 9531),
CITY_JIGGIG("Jiggig", LocationType.CITIES, 9775),
CITY_KARAMJA("Karamja", LocationType.CITIES, 11569, 11568, 11567, 11566, 11313, 11312, 11311),
CITY_KELDAGRIM("Keldagrim", LocationType.CITIES, 11423, 11422, 11679, 11678),
CITY_LLETYA("Lletya", LocationType.CITIES, 9265),
CITY_LOVAKENGJ_HOUSE("Lovakengj", LocationType.CITIES, 5692, 5948, 5691, 5947, 6203, 6202, 5690, 5946),
CITY_LUMBRIDGE("Lumbridge", LocationType.CITIES, 12850),
CITY_LUNAR_ISLE("Lunar Isle", LocationType.CITIES, 8253, 8252, 8509, 8508),
CITY_MEIYERDITCH("Meiyerditch", LocationType.CITIES, 14132, 14387, 14386, 14385),
CITY_MISCELLANIA("Miscellania", LocationType.CITIES, 10044, 10300),
CITY_MOS_LE_HARMLESS("Mos Le'Harmless", LocationType.CITIES, 14638),
CITY_MORTTON("Mort'ton", LocationType.CITIES, 13875),
CITY_MOR_UI_REK("Mor UI Rek", LocationType.CITIES, 9808, 9807, 10064, 10063),
CITY_MOUNT_KARUULM("Mount Karuulm", LocationType.CITIES, 5179, 4923, 5180),
CITY_MOUNT_QUIDAMORTEM("Mount Quidamortem", LocationType.CITIES, 4919),
CITY_NARDAH("Nardah", LocationType.CITIES, 13613),
CITY_NEITIZNOT("Neitiznot", LocationType.CITIES, 9275),
CITY_PISCATORIS("Piscatoris", LocationType.CITIES, 9273),
CITY_POLLNIVNEACH("Pollnivneach", LocationType.CITIES, 13358),
CITY_PORT_KHAZARD("Port Khazard", LocationType.CITIES, 10545),
CITY_PORT_PHASMATYS("Port Phasmatys", LocationType.CITIES, 14646),
CITY_PORT_SARIM("Port Sarim", LocationType.CITIES, 12082),
CITY_PISCARILIUS_HOUSE("Port Piscarilius", LocationType.CITIES, 6971, 7227, 6970, 7226),
CITY_PRIFDDINAS("Prifddinas", LocationType.CITIES, 12894, 12895, 13150, 13151),
CITY_RELLEKKA("Rellekka", LocationType.CITIES, 10553),
CITY_RIMMINGTON("Rimmington", LocationType.CITIES, 11826, 11570),
CITY_SEERS_VILLAGE("Seers' Village", LocationType.CITIES, 10806),
CITY_SHAYZIEN_HOUSE("Shayzien", LocationType.CITIES, 5944, 5943, 6200, 6199, 5688),
CITY_SHILO_VILLAGE("Shilo Village", LocationType.CITIES, 11310),
CITY_SOPHANEM("Sophanem", LocationType.CITIES, 13099),
CITY_TAI_BWO_WANNAI("Tai Bwo Wannai", LocationType.CITIES, 11056, 11055),
CITY_TAVERLEY("Taverley", LocationType.CITIES, 11574, 11573),
CITY_TREE_GNOME_STRONGHOLD("Tree Gnome Stronghold", LocationType.CITIES, 9782, 9781),
CITY_TREE_GNOME_VILLAGE("Tree Gnome Village", LocationType.CITIES, 10033),
CITY_TROLL_STRONGHOLD("Troll Stronghold", LocationType.CITIES, 11321),
CITY_TYRAS_CAMP("Tyras Camp", LocationType.CITIES, 8753, 8752),
CITY_UZER("Uzer", LocationType.CITIES, 13872),
CITY_VARROCK("Varrock", LocationType.CITIES, 12596, 12597, 12598, 12852, 12853, 12854, 13108, 13109, 13110),
CITY_WITCHHAVEN("Witchaven", LocationType.CITIES, 10803),
CITY_WOODCUTTING_GUILD("Woodcutting Guild", LocationType.CITIES, 6454, 6198, 6298),
CITY_YANILLE("Yanille", LocationType.CITIES, 10288, 10032),
CITY_ZANARIS("Zanaris", LocationType.CITIES, 9285, 9541, 9540, 9797),
CITY_ZULANDRA("Zul-Andra", LocationType.CITIES, 8751),
// Dungeons
DUNGEON_ABANDONED_MINE("Abandoned Mine", LocationType.DUNGEONS, 13718, 11079, 11078, 11077, 10823, 10822, 10821),
DUNGEON_AH_ZA_RHOON("Ah Za Rhoon", LocationType.DUNGEONS, 11666),
DUNGEON_ANCIENT_CAVERN("Ancient Cavern", LocationType.DUNGEONS, 6483, 6995),
DUNGEON_APE_ATOLL("Ape Atoll Dungeon", LocationType.DUNGEONS, 11150, 10894),
DUNGEON_ARDY_SEWERS("Ardougne Sewers", LocationType.DUNGEONS, 10136),
DUNGEON_ASGARNIAN_ICE_CAVES("Asgarnian Ice Caves", LocationType.DUNGEONS, 12181),
DUNGEON_BRIMHAVEN("Brimhaven Dungeon", LocationType.DUNGEONS, 10901, 10900, 10899, 10645, 10644, 10643),
DUNGEON_BRINE_RAT_CAVERN("Brine Rat Cavern", LocationType.DUNGEONS, 10910),
DUNGEON_CATACOMBS_OF_KOUREND("Catacombs of Kourend", LocationType.DUNGEONS, 6557, 6556, 6813, 6812),
DUNGEON_CHASM_OF_FIRE("Chasm of Fire", LocationType.DUNGEONS, 5789),
DUNGEON_CLOCK_TOWER("Clock Tower Basement", LocationType.DUNGEONS, 10390),
DUNGEON_CORSAIR_COVE("Corsair Cove Dungeon", LocationType.DUNGEONS, 8076, 8332),
DUNGEON_CRABCLAW_CAVES("Crabclaw Caves", LocationType.DUNGEONS, 6553, 6809),
DUNGEON_DIGSITE("Digsite Dungeon", LocationType.DUNGEONS, 13465),
DUNGEON_DORGESHKAAN("Dorgesh-Kaan South Dungeon", LocationType.DUNGEONS, 10833),
DUNGEON_DORGESHUUN_MINES("Dorgeshuun Mines", LocationType.DUNGEONS, 12950, 13206),
DUNGEON_DRAYNOR_SEWERS("Draynor Sewers", LocationType.DUNGEONS, 12439, 12438),
DUNGEON_DWARVEN_MINES("Dwarven Mines", LocationType.DUNGEONS, 12185, 12184, 12183),
DUNGEON_EAGLES_PEAK("Eagles' Peak Dungeon", LocationType.DUNGEONS, 8013),
DUNGEON_EDGEVILLE("Edgeville Dungeon", LocationType.DUNGEONS, 12441, 12442, 12443, 12698),
DUNGEON_ELEMENTAL_WORKSHOP("Elemental Workshop", LocationType.DUNGEONS, 10906, 7760),
DUNGEON_ENAKHRAS_TEMPLE("Enakhra's Temple", LocationType.DUNGEONS, 12423),
DUNGEON_ENTRANA("Entrana Dungeon", LocationType.DUNGEONS, 11416),
DUNGEON_EVIL_CHICKENS_LAIR("Evil Chicken's Lair", LocationType.DUNGEONS, 9796),
DUNGEON_EXPERIMENT_CAVE("Experiment Cave", LocationType.DUNGEONS, 14235, 13979),
DUNGEON_FREMENNIK_SLAYER("Fremennik Slayer Dungeon", LocationType.DUNGEONS, 10908, 11164),
DUNGEON_GOBLIN_CAVE("Goblin Cave", LocationType.DUNGEONS, 10393),
DUNGEON_GRAND_TREE_TUNNELS("Grand Tree Tunnels", LocationType.DUNGEONS, 9882),
DUNGEON_HAM("H.A.M Dungeon", LocationType.DUNGEONS, 12694, 10321),
DUNGEON_IORWERTH("Iorwerth Dungeon", LocationType.DUNGEONS, 12737, 12738, 12993, 12994),
DUNGEON_JATIZSO_MINES("Jatizso Mines", LocationType.DUNGEONS, 9631),
DUNGEON_JIGGIG_BURIAL_TOMB("Jiggig Burial Tomb", LocationType.DUNGEONS, 9875, 9874),
DUNGEON_JOGRE("Jogre Dungeon", LocationType.DUNGEONS, 11412),
DUNGEON_KARAMJA_VOLCANO("Karamja Volcano", LocationType.DUNGEONS, 11413, 11414),
DUNGEON_KARUULM("Karuulm Slayer Dungeon", LocationType.DUNGEONS, 5280, 5279, 5023, 5535, 5022, 4766, 4510, 4511, 4767, 4768, 4512),
DUNGEON_KHARAZI("Khazari Dungeon", LocationType.DUNGEONS, 11153),
DUNGEON_LIGHTHOUSE("Lighthouse", LocationType.DUNGEONS, 10140),
DUNGEON_LIZARDMAN_CAVES("Lizardman Caves", LocationType.DUNGEONS, 5275),
DUNGEON_LUMBRIDGE_SWAMP_CAVES("Lumbridge Swamp Caves", LocationType.DUNGEONS, 12693, 12949),
DUNGEON_LUNAR_ISLE_MINE("Lunar Isle Mine", LocationType.DUNGEONS, 9377),
DUNGEON_MISCELLANIA("Miscellania Dungeon", LocationType.DUNGEONS, 10144, 10400),
DUNGEON_MOGRE_CAMP("Mogre Camp", LocationType.DUNGEONS, 11924),
DUNGEON_MOS_LE_HARMLESS_CAVES("Mos Le'Harmless Caves", LocationType.DUNGEONS, 14994, 14995, 15251),
DUNGEON_MOUSE_HOLE("Mouse Hole", LocationType.DUNGEONS, 9046),
DUNGEON_OBSERVATORY("Observatory Dungeon", LocationType.DUNGEONS, 9362),
DUNGEON_OGRE_ENCLAVE("Ogre Enclave", LocationType.DUNGEONS, 10387),
DUNGEON_QUIDAMORTEM_CAVE("Quidamortem Cave", LocationType.DUNGEONS, 4763),
DUNGEON_RASHILIYIAS_TOMB("Rashiliyta's Tomb", LocationType.DUNGEONS, 11668),
DUNGEON_SARADOMINSHRINE("Saradomin Shrine (Paterdomus)", LocationType.DUNGEONS, 13722),
DUNGEON_SHADE_CATACOMBS("Shade Catacombs", LocationType.DUNGEONS, 13975),
DUNGEON_SHAYZIEN_CRYPTS("Shayzien Crypts", LocationType.DUNGEONS, 6043),
DUNGEON_SMOKE("Smoke Dungeon", LocationType.DUNGEONS, 12946, 13202),
DUNGEON_SOPHANEM("Sophanem Dungeon", LocationType.DUNGEONS, 13200),
DUNGEON_STRONGHOLD_SECURITY("Stronghold of Security", LocationType.DUNGEONS, 7505, 8017, 8530, 9297),
DUNGEON_TARNS_LAIR("Tarn's Lair", LocationType.DUNGEONS, 12616, 12615),
DUNGEON_TAVERLEY("Taverley Dungeon", LocationType.DUNGEONS, 11673, 11672, 11929, 11928, 11417),
DUNGEON_TEMPLE_OF_IKOV("Temple of Ikov", LocationType.DUNGEONS, 10649, 10905, 10650),
DUNGEON_TEMPLE_OF_MARIMBO("Temple of Marimbo", LocationType.DUNGEONS, 11151),
DUNGEON_THE_WARRENS("The Warrens", LocationType.DUNGEONS, 7070, 7326),
DUNGEON_TOLNA("Dungeon of Tolna", LocationType.DUNGEONS, 13209),
DUNGEON_TOWER_OF_LIFE("Tower of Life Basement", LocationType.DUNGEONS, 12100),
DUNGEON_TRAHAEARN_MINE("Trahaearn Mine", LocationType.DUNGEONS, 13249),
DUNGEON_TUNNEL_OF_CHAOS("Tunnel of Chaos", LocationType.DUNGEONS, 12625),
DUNGEON_UNDERGROUND_PASS("Underground Pass", LocationType.DUNGEONS, 9369, 9370),
DUNGEON_VARROCKSEWERS("Varrock Sewers", LocationType.DUNGEONS, 12954, 13210),
DUNGEON_WATER_RAVINE("Water Ravine", LocationType.DUNGEONS, 13461),
DUNGEON_WATERBIRTH("Waterbirth Dungeon", LocationType.DUNGEONS, 9886, 10142, 7492, 7748),
DUNGEON_WATERFALL("Waterfall Dungeon", LocationType.DUNGEONS, 10394),
DUNGEON_WHITE_WOLF_MOUNTAIN_CAVES("White Wolf Mountain Caves", LocationType.DUNGEONS, 11418, 11419, 11675),
DUNGEON_WITCHAVEN_SHRINE("Witchhaven Shrine Dungeon", LocationType.DUNGEONS, 10903),
DUNGEON_YANILLE_AGILITY("Yanille Agility Dungeon", LocationType.DUNGEONS, 10388),
DUNGEON_MOTHERLODE_MINE("Motherlode Mine", LocationType.DUNGEONS, 14679, 14680, 14681, 14935, 14936, 14937, 15191, 15192, 15193),
DUNGEON_NIGHTMARE("Nightmare Dungeon", LocationType.DUNGEONS, 14999, 15000, 15001, 15255, 15256, 15257, 15511, 15512, 15513),
// Minigames
MG_BARBARIAN_ASSAULT("Barbarian Assault", LocationType.MINIGAMES, 10332),
MG_BARROWS("Barrows", LocationType.MINIGAMES, 14131, 14231),
MG_BLAST_FURNACE("Blast Furnace", LocationType.MINIGAMES, 7757),
MG_BRIMHAVEN_AGILITY_ARENA("Brimhaven Agility Arena", LocationType.MINIGAMES, 11157),
MG_BURTHORPE_GAMES_ROOM("Burthorpe Games Room", LocationType.MINIGAMES, 8781),
MG_CASTLE_WARS("Castle Wars", LocationType.MINIGAMES, 9520),
MG_CLAN_WARS("Clan Wars", LocationType.MINIGAMES, 13135, 13134, 13133, 13131, 13130, 13387, 13386),
MG_DUEL_ARENA("Duel Arena", LocationType.MINIGAMES, 13362),
MG_FISHING_TRAWLER("Fishing Trawler", LocationType.MINIGAMES, 7499),
MG_GAUNTLET("Gauntlet", LocationType.MINIGAMES, 12995),
MG_INFERNO("The Inferno", LocationType.MINIGAMES, 9043),
MG_LAST_MAN_STANDING("Last Man Standing", LocationType.MINIGAMES, 13660, 13659, 13658, 13916, 13915, 13914),
MG_HALLOWED_SEPULCHRE("Hallowed Sepulchre", LocationType.MINIGAMES, 8797, 9051, 9052, 9053, 9054, 9309, 9563, 9565, 9821, 10074, 10075, 10077),
MG_MAGE_TRAINING_ARENA("Mage Training Arena", LocationType.MINIGAMES, 13462, 13463),
MG_NIGHTMARE_ZONE("Nightmare Zone", LocationType.MINIGAMES, 9033),
MG_PEST_CONTROL("Pest Control", LocationType.MINIGAMES, 10536),
MG_PYRAMID_PLUNDER("Pyramid Plunder", LocationType.MINIGAMES, 7749),
MG_ROGUES_DEN("Rogues' Den", LocationType.MINIGAMES, 11855, 11854, 12111, 12110),
MG_SORCERESS_GARDEN("Sorceress's Garden", LocationType.MINIGAMES, 11605),
MG_TEMPLE_TREKKING("Temple Trekking", LocationType.MINIGAMES, 8014, 8270, 8256, 8782, 9038, 9294, 9550, 9806),
MG_TITHE_FARM("Tithe Farm", LocationType.MINIGAMES, 6968),
MG_TROUBLE_BREWING("Trouble Brewing", LocationType.MINIGAMES, 15150),
MG_TZHAAR_FIGHT_CAVES("Tzhaar Fight Caves", LocationType.MINIGAMES, 9551),
MG_TZHAAR_FIGHT_PITS("Tzhaar Fight Pits", LocationType.MINIGAMES, 9552),
MG_VOLCANIC_MINE("Volcanic Mine", LocationType.MINIGAMES, 15263, 15262),
// Raids
RAIDS_CHAMBERS_OF_XERIC("Chambers of Xeric", LocationType.RAIDS, Varbits.IN_RAID),
RAIDS_THEATRE_OF_BLOOD("Theatre of Blood", LocationType.RAIDS, Varbits.THEATRE_OF_BLOOD),
POI_FISHING_GUILD("Fishing Guild", LocationType.POI, 10293),
POI_OTTOS_GROTTO("Otto's Grotto", LocationType.POI, 10038),
POI_PLAYER_OWNED_HOUSE("Player Owned House", LocationType.POI, 7769),
;
private static final Map<Integer, GameEvent> FROM_REGION;
private static final List<GameEvent> FROM_VARBITS;
private static final EnumMap<Skill, GameEvent> FROM_SKILL = new EnumMap<Skill, GameEvent>(Skill.class);
static {
ImmutableMap.Builder<Integer, GameEvent> regionMapBuilder = new ImmutableMap.Builder<>();
ImmutableList.Builder<GameEvent> fromVarbitsBuilder = ImmutableList.builder();
for (GameEvent gameEvent : GameEvent.values()) {
if (gameEvent.getVarbits() != null) {
fromVarbitsBuilder.add(gameEvent);
continue;
}
if (gameEvent.getSkill() != null) {
FROM_SKILL.put(gameEvent.getSkill(), gameEvent);
continue;
}
if (gameEvent.getRegionIds() == null) {
continue;
}
for (int region : gameEvent.getRegionIds()) {
regionMapBuilder.put(region, gameEvent);
}
}
FROM_REGION = regionMapBuilder.build();
FROM_VARBITS = fromVarbitsBuilder.build();
}
@Nullable
private String location;
@Nullable
private Skill skill;
private final int priority;
private boolean shouldClear;
private boolean shouldTimeout;
@Nullable
private LocationType locationType;
@Nullable
private Varbits varbits;
@Nullable
private int[] regionIds;
GameEvent(Skill skill) {
this(skill, 0);
}
GameEvent(Skill skill, int priority) {
this.skill = skill;
this.priority = priority;
this.shouldTimeout = true;
}
GameEvent(String areaName, LocationType locationType, int... regionIds) {
this.location = areaName;
this.priority = -2;
this.locationType = locationType;
this.regionIds = regionIds;
this.shouldClear = true;
}
GameEvent(String state, int priority) {
this.location = state;
this.priority = priority;
this.shouldClear = true;
}
GameEvent(String areaName, LocationType locationType, Varbits varbits) {
this.location = areaName;
this.priority = -2;
this.locationType = locationType;
this.varbits = varbits;
this.shouldClear = true;
}
public static GameEvent fromSkill(final Skill skill) {
return FROM_SKILL.get(skill);
}
public static GameEvent fromRegion(final int regionId) {
return FROM_REGION.get(regionId);
}
public static GameEvent fromVarbit(final Client client) {
for (GameEvent fromVarbit : FROM_VARBITS) {
if (client.getVar(fromVarbit.getVarbits()) != 0) {
return fromVarbit;
}
}
return null;
}
}
| 53.810881 | 147 | 0.739637 |
07568c239423bed7412ed37cb6cb22ea686b34ab | 332 | package com.github.nhojpatrick.cucumber.json.core.exceptions;
import com.github.nhojpatrick.cucumber.core.exceptions.IllegalOperationException;
public class IllegalPathOperationException
extends IllegalOperationException {
public IllegalPathOperationException(final String message) {
super(message);
}
}
| 25.538462 | 81 | 0.792169 |
364499134f7d7264cd8e062f9593d2ffb07aaf1e | 5,708 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2020 wcm.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,
* 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.
* #L%
*/
package io.wcm.devops.conga.plugins.aem.maven.allpackage;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import io.wcm.devops.conga.plugins.aem.maven.model.InstallableFile;
final class RunModeUtil {
static final String RUNMODE_AUTHOR = "author";
static final String RUNMODE_PUBLISH = "publish";
private RunModeUtil() {
// static methods only
}
/**
* Checks if the given package is to be installed on both author and publish instances
* @param file Content package
* @return true if author and publish run mode (or no run mode = no restriction)
*/
public static boolean isAuthorAndPublish(InstallableFile file) {
Set<String> runModes = mapVariantsToRunModes(file.getVariants());
return (!runModes.contains(RUNMODE_AUTHOR) && !runModes.contains(RUNMODE_PUBLISH))
|| (runModes.contains(RUNMODE_AUTHOR) && runModes.contains(RUNMODE_PUBLISH));
}
/**
* Checks if the given variants map to author run mode, but not to publish run mode.
* @param file Content package
* @return true if only author run modes
*/
public static boolean isOnlyAuthor(InstallableFile file) {
Set<String> runModes = mapVariantsToRunModes(file.getVariants());
return runModes.contains(RUNMODE_AUTHOR) && !runModes.contains(RUNMODE_PUBLISH);
}
/**
* Checks if the given variants map to publish run mode, but not to author run mode.
* @param file Content package
* @return true if only publish run modes
*/
public static boolean isOnlyPublish(InstallableFile file) {
Set<String> runModes = mapVariantsToRunModes(file.getVariants());
return runModes.contains(RUNMODE_PUBLISH) && !runModes.contains(RUNMODE_AUTHOR);
}
private static Set<String> mapVariantsToRunModes(Collection<String> variants) {
return variants.stream()
.map(RunModeUtil::mapVariantToRunMode)
.collect(Collectors.toSet());
}
/**
* Maps well-known variant names from CONGA AEM definitions to the corresponding run modes.
* If the variant name is not well-known the variant name is used as run mode.
* @param variant Variant
* @return Run mode
*/
private static String mapVariantToRunMode(String variant) {
if ("aem-author".equals(variant)) {
return RUNMODE_AUTHOR;
}
else if ("aem-publish".equals(variant)) {
return RUNMODE_PUBLISH;
}
return variant;
}
/**
* Builds an optimized list of file sets separated for each environment run mode, but combined for author and publish
* variant files. Those files are reduced to single items if they are present in both author and publish variants. The
* order of the resulting file sets if driven by the first file set(s) in the list, additional files from other file
* sets are added at the end of the result list(s).
* @param fileSets Existing list of filesets
* @param fileSetFactory Creates a new (empty) file set for given environment run mode
* @return Optimized list of file sets (one per environment run mode)
*/
public static <T extends InstallableFile, S extends FileSet<T>> Collection<S> eliminateAuthorPublishDuplicates(
List<S> fileSets, Function<String, S> fileSetFactory) {
Map<String, S> result = new LinkedHashMap<>();
fileSets.forEach(fileSet -> fileSet.getEnvironmentRunModes().forEach(environmentRunMode -> {
FileSet<T> resultFileSet = result.computeIfAbsent(environmentRunMode, fileSetFactory);
fileSet.getFiles().forEach(file -> {
Optional<T> existingFile = resultFileSet.getFiles().stream()
.filter(item -> isSameFileNameHash(item, file))
.findFirst();
if (existingFile.isPresent()) {
// if file was already added from other file set: eliminate duplicate, but add run modes
existingFile.get().getVariants().addAll(file.getVariants());
}
else {
resultFileSet.getFiles().add(file);
}
});
}));
// eliminate author+publish run modes if both are set on same file
result.values().forEach(
fileSet -> fileSet.getFiles().forEach(file -> removeAuthorPublishRunModeIfBothPresent(file.getVariants())));
return result.values();
}
private static boolean isSameFileNameHash(InstallableFile file1, InstallableFile file2) {
if (!StringUtils.equals(file1.getFile().getName(), file2.getFile().getName())) {
return false;
}
return file1.getHashCode().equals(file2.getHashCode());
}
/**
* Removes author and publish runmodes from given set if both are present.
* @param runModes Run modes
*/
private static void removeAuthorPublishRunModeIfBothPresent(Set<String> runModes) {
if (runModes.contains(RUNMODE_AUTHOR) && runModes.contains(RUNMODE_PUBLISH)) {
runModes.remove(RUNMODE_AUTHOR);
runModes.remove(RUNMODE_PUBLISH);
}
}
}
| 38.308725 | 120 | 0.709355 |
043d93e2ef12282e83c6294c8f0cb449d2d80548 | 543 | package seedu.address.model.person;
import javafx.collections.ObservableList;
/**
* Unmodifiable view of an address book
*/
public interface ReadOnlyAddressBook {
/**
* Returns an unmodifiable view of the persons list.
* This list will not contain any duplicate persons.
*/
ObservableList<Person> getPersonList();
/**
* Returns a person by name inside the Addresbook.
* Returns null if person not found.
* @param name
* @return
*/
public Person getPersonByName(PersonName name);
}
| 22.625 | 56 | 0.679558 |
19d0eda7790bc5918fcd980298cd68d830451289 | 71 | package com.atul.gitbook.learn.users.models;
public class UserDto {
}
| 14.2 | 44 | 0.774648 |
7e6bdc3607d9ca6bcb5e178fbc638fa0819b28ea | 617 | package com.rektapps.greendictionary.view.adapter.viewholder;
import android.arch.lifecycle.ViewModel;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
public abstract class BaseViewModelViewHolder<VM extends ViewModel, DB extends ViewDataBinding, T> extends RecyclerView.ViewHolder {
protected VM viewModel;
protected DB dataBinding;
protected BaseViewModelViewHolder(VM viewModel, DB dataBinding) {
super(dataBinding.getRoot());
this.viewModel = viewModel;
this.dataBinding = dataBinding;
}
public abstract void bind(T t);
}
| 32.473684 | 132 | 0.769854 |
6ab9eb13fd5c451844702abcc03b65da171a30fc | 10,503 | package jetbrains.mps.vcs.core.mergedriver;
/*Generated by MPS */
import jetbrains.mps.annotations.GeneratedClass;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
import org.jetbrains.mps.openapi.model.SModelName;
import jetbrains.mps.core.platform.Platform;
import org.jetbrains.annotations.Nullable;
import jetbrains.mps.baseLanguage.tuples.runtime.Tuples;
import jetbrains.mps.RuntimeFlags;
import jetbrains.mps.project.MPSExtentions;
import org.jetbrains.mps.openapi.model.SModel;
import org.apache.log4j.Level;
import jetbrains.mps.vcs.diff.merge.MergeSession;
import jetbrains.mps.internal.collections.runtime.Sequence;
import jetbrains.mps.internal.collections.runtime.IWhereFilter;
import jetbrains.mps.vcs.diff.changes.ModelChange;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.vcspersistence.VCSPersistenceUtil;
import jetbrains.mps.extapi.persistence.ModelFactoryService;
import jetbrains.mps.baseLanguage.tuples.runtime.MultiTuple;
import java.io.File;
import jetbrains.mps.vcs.util.MergeDriverBackupUtil;
import java.io.IOException;
import jetbrains.mps.persistence.PersistenceVersionAware;
import org.jetbrains.mps.openapi.persistence.ModelFactory;
import org.jetbrains.mps.openapi.persistence.PersistenceFacade;
import org.jetbrains.mps.openapi.persistence.ContentOption;
import jetbrains.mps.persistence.MetaModelInfoProvider;
import org.jetbrains.mps.openapi.persistence.ModelLoadException;
import org.jetbrains.mps.openapi.persistence.UnsupportedDataSourceException;
import jetbrains.mps.smodel.DefaultSModel;
import jetbrains.mps.extapi.model.SModelBase;
import jetbrains.mps.extapi.model.SModelData;
@GeneratedClass(node = "r:a178d3c3-970e-4352-b61c-4e55abc3bc24(jetbrains.mps.vcs.core.mergedriver)/3342666646761698167", model = "r:a178d3c3-970e-4352-b61c-4e55abc3bc24(jetbrains.mps.vcs.core.mergedriver)")
/*package*/ class ModelMerger extends SimpleMerger {
private static final Logger LOG = LogManager.getLogger(ModelMerger.class);
private SModelName myModelName;
private String myExtension;
private final Platform myPlatform;
public ModelMerger(Platform mpsPlatform, String extension) {
myExtension = extension;
myPlatform = mpsPlatform;
}
@Override
@Nullable
public Tuples._2<Integer, byte[]> mergeContents(FileContent baseContent, FileContent localContent, FileContent latestContent) {
if (Boolean.getBoolean("mps.mergedriver.model.fail")) {
// fail, so the merge will be done in full MPS
return null;
}
RuntimeFlags.setMergeDriverMode(true);
String ext = (myExtension == null ? MPSExtentions.MODEL : myExtension);
if (MPSExtentions.MODEL_HEADER.equals(myExtension) || MPSExtentions.MODEL_ROOT.equals(myExtension)) {
// special support for per-root persistence
ext = MPSExtentions.MODEL;
}
if (LOG.isInfoEnabled()) {
LOG.info("Reading models...");
}
SModel baseModel = loadModel(baseContent, ext);
SModel localModel = loadModel(localContent, ext);
SModel latestModel = loadModel(latestContent, ext);
if (baseModel == null || localModel == null || latestModel == null) {
return backup(baseContent, localContent, latestContent);
}
myModelName = baseModel.getName();
int baseP = getPersistenceVersion(baseModel);
int localP = getPersistenceVersion(localModel);
int latestP = getPersistenceVersion(latestModel);
if (baseP >= 7 && localP >= 7 && latestP >= 7 || baseP < 7 && localP < 7 && latestP < 7) {
// ok, can merge
} else {
if (LOG.isEnabledFor(Level.ERROR)) {
LOG.error(String.format("%s: Conflicting model persistence versions", myModelName));
}
return backup(baseContent, localContent, latestContent);
}
try {
if (LOG.isInfoEnabled()) {
LOG.info("Merging " + baseModel.getReference() + "...");
}
final MergeSession mergeSession = MergeSession.createMergeSession(baseModel, localModel, latestModel);
int conflictingChangesCount = Sequence.fromIterable(mergeSession.getAllChanges()).where(new IWhereFilter<ModelChange>() {
public boolean accept(ModelChange c) {
return Sequence.fromIterable(mergeSession.getConflictedWith(c)).isNotEmpty();
}
}).count();
if (conflictingChangesCount == 0) {
if (LOG.isInfoEnabled()) {
LOG.info(String.format("%s: %d changes detected: %d local and %d latest.", myModelName, Sequence.fromIterable(mergeSession.getAllChanges()).count(), ListSequence.fromList(mergeSession.getMyChangeSet().getModelChanges()).count(), ListSequence.fromList(mergeSession.getRepositoryChangeSet().getModelChanges()).count()));
}
mergeSession.applyChanges(mergeSession.getAllChanges());
} else {
if (LOG.isInfoEnabled()) {
LOG.info(String.format("%s: %d changes detected, %d of them are conflicting", myModelName, Sequence.fromIterable(mergeSession.getAllChanges()).count(), conflictingChangesCount));
}
return backup(baseContent, localContent, latestContent);
}
if (mergeSession.hasIdsToRestore()) {
if (LOG.isInfoEnabled()) {
LOG.info(String.format("%s: node id duplication detected, should merge in UI.", myModelName));
}
} else {
byte[] resultBytes;
SModel resultModel = mergeSession.getResultModel();
if (LOG.isInfoEnabled()) {
LOG.info(String.format("%s: Saving merged model...", myModelName));
}
updateMetaModelInfo(resultModel, baseModel, localModel, latestModel);
resultBytes = VCSPersistenceUtil.saveModel(myPlatform.findComponent(ModelFactoryService.class), resultModel, myExtension, ext);
if (resultBytes == null) {
if (LOG.isEnabledFor(Level.ERROR)) {
LOG.error("Error while saving result model");
}
return backup(baseContent, localContent, latestContent);
}
if (LOG.isInfoEnabled()) {
LOG.info(String.format("%s: merged successfully.", myModelName));
}
backup(baseContent, localContent, latestContent);
return MultiTuple.<Integer,byte[]>from(MERGED, resultBytes);
}
} catch (Throwable e) {
if (LOG.isEnabledFor(Level.ERROR)) {
LOG.error("Exception while merging", e);
}
}
return backup(baseContent, localContent, latestContent);
}
private Tuples._2<Integer, byte[]> backup(FileContent baseContent, FileContent localContent, FileContent latestContent) {
try {
File zipModel = MergeDriverBackupUtil.zipModel(new byte[][]{baseContent.getData(), localContent.getData(), latestContent.getData()}, myModelName);
if (zipModel != null) {
if (LOG.isInfoEnabled()) {
LOG.info("Saved merge backup to " + zipModel);
}
}
} catch (IOException e) {
if (LOG.isEnabledFor(Level.ERROR)) {
LOG.error(String.format("%s: exception while backuping", myModelName), e);
}
}
return null;
}
private static int getPersistenceVersion(SModel model) {
if (model instanceof PersistenceVersionAware) {
return ((PersistenceVersionAware) model).getPersistenceVersion();
}
return -1;
}
/*package*/ static SModel loadModel(FileContent content, String fnameExtension) {
ModelFactory modelFactory = PersistenceFacade.getInstance().getModelFactory(fnameExtension);
if (modelFactory == null) {
return null;
}
try {
SModel model = modelFactory.load(content, ContentOption.CONTENT_ONLY, MetaModelInfoProvider.MetaInfoLoadingOption.KEEP_READ);
return (VCSPersistenceUtil.isModelFullyLoaded(model) ? model : null);
} catch (ModelLoadException ex) {
if (LOG.isEnabledFor(Level.WARN)) {
LOG.warn("Failed to read model", ex);
}
} catch (UnsupportedDataSourceException ex) {
if (LOG.isEnabledFor(Level.WARN)) {
LOG.warn("Failed to read model", ex);
}
}
return null;
}
private static void updateMetaModelInfo(SModel resultModel, SModel baseModel, SModel localModel, SModel remoteModel) {
// we don't care to fix MetaModelInfoProvider for versions it was not utilized in.
if (getPersistenceVersion(resultModel) < 9) {
return;
}
DefaultSModel resultModelInternal = tryInternalModelData(resultModel);
if (resultModelInternal == null) {
return;
}
DefaultSModel baseModelInternal = tryInternalModelData(baseModel);
DefaultSModel localModelInternal = tryInternalModelData(localModel);
DefaultSModel remoteModelInternal = tryInternalModelData(remoteModel);
// if there's nothing collected during model read, can't help but let it go
if (baseModelInternal == null && localModelInternal == null && remoteModelInternal == null) {
return;
}
// build sequence of meta-info providers, so that result model would consult local, remote, base and own MMIP sequentially, trying to find meta-info
// If none succeed, fail with null values from BaseMetaModelInfo. Allow MMIP from result model to answer differently
MetaModelInfoProvider delegate = resultModelInternal.getSModelHeader().getMetaInfoProvider();
if (delegate == null) {
delegate = new MetaModelInfoProvider.BaseMetaModelInfo();
}
for (DefaultSModel m : new DefaultSModel[]{baseModelInternal, remoteModelInternal, localModelInternal}) {
MetaModelInfoProvider.StuffedMetaModelInfo provider;
if ((provider = tryStuffedProvider(m)) != null) {
MetaModelInfoProvider.StuffedMetaModelInfo nextInChain = new MetaModelInfoProvider.StuffedMetaModelInfo(delegate);
provider.populate(nextInChain);
delegate = nextInChain;
}
}
resultModelInternal.getSModelHeader().setMetaInfoProvider(delegate);
return;
}
private static DefaultSModel tryInternalModelData(SModel model) {
if (model instanceof SModelBase) {
SModelData modelData = ((SModelBase) model).getModelData();
return (modelData instanceof DefaultSModel ? ((DefaultSModel) modelData) : null);
}
return null;
}
private static MetaModelInfoProvider.StuffedMetaModelInfo tryStuffedProvider(DefaultSModel model) {
if (model == null) {
return null;
}
MetaModelInfoProvider p = model.getSModelHeader().getMetaInfoProvider();
if (p instanceof MetaModelInfoProvider.StuffedMetaModelInfo) {
return ((MetaModelInfoProvider.StuffedMetaModelInfo) p);
}
return null;
}
}
| 44.884615 | 328 | 0.719604 |
6cdfedd0f443225106594670fca03efb267a9e7d | 4,030 | /*
* Copyright 2014-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spectator.ipcservlet;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.ipc.IpcLogger;
import com.netflix.spectator.ipc.http.HttpClient;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.AfterAll;
import javax.inject.Singleton;
import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.EnumSet;
import static com.netflix.spectator.ipcservlet.TestUtils.*;
public class GuiceServletFilterTest {
// https://github.com/google/guice/issues/807
private static Server server;
private static URI baseUri;
@BeforeAll
public static void init() throws Exception {
server = new Server(new InetSocketAddress("localhost", 0));
ServletContextHandler handler = new ServletContextHandler(server, "/");
handler.addEventListener(new TestListener());
handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
server.setHandler(handler);
server.start();
baseUri = server.getURI();
}
@AfterAll
public static void shutdown() throws Exception {
server.stop();
}
private Registry registry;
private HttpClient client;
@BeforeEach
public void before() {
registry = new DefaultRegistry();
client = HttpClient.create(new IpcLogger(registry));
Spectator.globalRegistry().removeAll();
Spectator.globalRegistry().add(registry);
}
@Test
public void validateIdTest() throws Exception {
client.get(baseUri.resolve("/test/foo/12345")).send();
checkEndpoint(registry, "/test/foo");
}
@Test
public void validateIdApi() throws Exception {
client.get(baseUri.resolve("/api/v1/asgs/12345")).send();
checkEndpoint(registry, "/api");
}
@Test
public void validateIdRoot() throws Exception {
client.get(baseUri.resolve("/12345")).send();
checkEndpoint(registry, "/");
}
@Singleton
public static class TestServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setStatus(200);
}
}
@Singleton
public static class TestListener extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Registry.class).toInstance(Spectator.globalRegistry());
}
},
new ServletModule() {
@Override
protected void configureServlets() {
serve("/test/foo/*").with(TestServlet.class);
serve("/api/*").with(TestServlet.class);
serve("/*").with(TestServlet.class);
filter("/*").through(IpcServletFilter.class);
}
}
);
}
}
}
| 30.763359 | 84 | 0.712407 |
2b043e94915f20afff3d4c8939cd7a50831d81ac | 1,827 | /*
* This file is part of kdk. It is subject to the license terms in the LICENSE file found in the top-level
* directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of kdk,
* including this file, may be copied, modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
package wtf.metio.kdk.validate.meta;
import wtf.metio.kdk.construct.meta.Annotation;
import wtf.metio.kdk.validate.ValidationError;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import static wtf.metio.kdk.validate.ValidationError.of;
import static wtf.metio.kdk.validate.internal.StringValidators.blank;
/**
* Validators for {@link Annotation}s.
*/
public final class AnnotationValidators {
//region presets
public static List<Function<Annotation, Stream<ValidationError>>> all() {
return List.of(keyBlank(), valueBlank());
}
public static List<Function<Annotation, Stream<ValidationError>>> recommended() {
return List.of(keyBlank(), valueBlank());
}
//endregion
/**
* Checks that no annotation key is blank
*/
public static Function<Annotation, Stream<ValidationError>> keyBlank() {
return annotation -> Stream.of(annotation)
.filter(blank(Annotation::key))
.map(object -> of("annotation:key-blank", object));
}
/**
* Checks that no annotation value is blank
*/
public static Function<Annotation, Stream<ValidationError>> valueBlank() {
return annotation -> Stream.of(annotation)
.filter(blank(Annotation::value))
.map(object -> of("annotation:value-blank", object));
}
private AnnotationValidators() {
// factory class
}
}
| 31.5 | 115 | 0.684182 |
0875e251f357181c922de65542fc67b7d14e287f | 641 | package org.flowable.community.external.worker.model;
public class EngineVariable {
private String name;
private Object value;
private String type;
private String valueUrl;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValueUrl() {
return valueUrl;
}
public void setValueUrl(String valueUrl) {
this.valueUrl = valueUrl;
}
}
| 14.906977 | 53 | 0.695788 |
37f27e623d187d093a8f41720c28222c9a0992fe | 6,950 | /*
* Cardinal-Components-API
* Copyright (C) 2019-2021 OnyxStudios
*
* 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 dev.onyxstudios.cca.internal.base;
import dev.onyxstudios.cca.api.v3.component.Component;
import dev.onyxstudios.cca.api.v3.component.ComponentContainer;
import dev.onyxstudios.cca.api.v3.component.ComponentKey;
import dev.onyxstudios.cca.api.v3.component.ComponentRegistry;
import dev.onyxstudios.cca.api.v3.component.CopyableComponent;
import net.fabricmc.fabric.api.util.NbtType;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.util.Identifier;
import java.util.Iterator;
/**
* Implementing class for {@link ComponentContainer}.
*/
public abstract class AbstractComponentContainer implements ComponentContainer {
public static final String NBT_KEY = "cardinal_components";
@Override
public void copyFrom(ComponentContainer other) {
for (ComponentKey<?> key : this.keys()) {
Component theirs = key.getInternal(other);
Component ours = key.getInternal(this);
assert ours != null;
if (theirs != null && !ours.equals(theirs)) {
if (ours instanceof CopyableComponent) {
@SuppressWarnings("unchecked") CopyableComponent<Component> copyable = (CopyableComponent<Component>) ours;
copyable.copyFrom(theirs);
} else {
NbtCompound tag = new NbtCompound();
theirs.writeToNbt(tag);
ours.readFromNbt(tag);
}
}
}
}
/**
* {@inheritDoc}
*
* @implSpec This implementation first checks if {@code tag} has a tag list
* mapped to the "cardinal_components" key; if not it returns immediately.
* Then it iterates over the list's tags, casts them to {@code NbtCompound},
* and passes them to the associated component's {@code fromTag} method.
* If this container lacks a corresponding component for a serialized component
* type, the component tag is skipped.
*/
@Override
public void fromTag(NbtCompound tag) {
if(tag.contains(NBT_KEY, NbtType.LIST)) {
NbtList componentList = tag.getList(NBT_KEY, NbtType.COMPOUND);
for (int i = 0; i < componentList.size(); i++) {
NbtCompound nbt = componentList.getCompound(i);
ComponentKey<?> type = ComponentRegistry.get(new Identifier(nbt.getString("componentId")));
if (type != null) {
Component component = type.getInternal(this);
if (component != null) {
component.readFromNbt(nbt);
}
}
}
} else if (tag.contains("cardinal_components", NbtType.COMPOUND)) {
NbtCompound componentMap = tag.getCompound(NBT_KEY);
for (ComponentKey<?> key : this.keys()) {
String keyId = key.getId().toString();
if (componentMap.contains(keyId, NbtType.COMPOUND)) {
Component component = key.getInternal(this);
assert component != null;
component.readFromNbt(componentMap.getCompound(keyId));
componentMap.remove(keyId);
}
}
for (String missedKeyId : componentMap.getKeys()) {
Identifier id = Identifier.tryParse(missedKeyId);
String cause;
if (id == null) cause = "invalid identifier";
else if (ComponentRegistry.get(id) == null) cause = "unregistered key";
else cause = "provider does not have ";
ComponentsInternals.LOGGER.warn("Failed to deserialize component: {} {}", cause, missedKeyId);
}
}
}
/**
* {@inheritDoc}
*
* @implSpec This implementation first checks if the container is empty; if so it
* returns immediately. Then, it iterates over this container's mappings, and creates
* a compound tag for each component. The tag is then passed to the component's
* {@link Component#writeToNbt(NbtCompound)} method. Every such serialized component is appended
* to a {@code NbtCompound}, using the component type's identifier as the key.
* The serialized map is finally appended to the passed in tag using the "cardinal_components" key.
*/
@Override
public NbtCompound toTag(NbtCompound tag) {
if(this.hasComponents()) {
NbtCompound componentMap = null;
NbtCompound componentTag = new NbtCompound();
for (ComponentKey<?> type : this.keys()) {
Component component = type.getFromContainer(this);
component.writeToNbt(componentTag);
if (!componentTag.isEmpty()) {
if (componentMap == null) {
componentMap = new NbtCompound();
tag.put(NBT_KEY, componentMap);
}
componentMap.put(type.getId().toString(), componentTag);
componentTag = new NbtCompound(); // recycle tag objects if possible
}
}
}
return tag;
}
@Override
public String toString() {
Iterator<ComponentKey<?>> i = this.keys().iterator();
if (! i.hasNext()) {
return "{}";
}
StringBuilder sb = new StringBuilder();
sb.append('{');
for (;;) {
ComponentKey<?> key = i.next();
Component value = key.getInternal(this);
sb.append(key);
sb.append('=');
sb.append(value);
if (! i.hasNext()) {
return sb.append('}').toString();
}
sb.append(',').append(' ');
}
}
}
| 40.406977 | 127 | 0.609928 |
856c380edbc8d265315ca46e94028c858b4da88b | 1,362 | package org.semanticweb.rulewerk.rpq.parser;
/*-
* #%L
* Rulewerk Parser
* %%
* Copyright (C) 2018 - 2020 Rulewerk Developers
* %%
* 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.
* #L%
*/
import org.semanticweb.rulewerk.core.model.api.DatatypeConstant;
/**
* Handler for parsing a custom Datatype constant.
*
* @author Maximilian Marx
*/
@FunctionalInterface
public interface DatatypeConstantHandler {
/**
* Parse a datatype constant.
*
* @param lexicalForm lexical representation of the constant.
*
* @throws ParsingException when the given representation is invalid for this
* datatype.
*
* @return a {@link DatatypeConstant} corresponding to the lexical form.
*/
public DatatypeConstant createConstant(String lexicalForm) throws ParsingException;
}
| 30.954545 | 85 | 0.700441 |
05b006c64332e4488d576a7de300b3b3dd33406a | 6,766 | package pixelartengine.ui.views;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import pixelartengine.ui.components.GamePanel;
import pixelartengine.ui.logic.PixelArtEngineLogic;
public class PixelArtEngineView extends PixelArtEngineLogic {
private JFrame frame;
private JMenuItem mntmNewGame;
/**
* @wbp.parser.entryPoint
*/
public void openView() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
initialize();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initialize() {
frame = new JFrame("PixelArtEngine");
frame.setBounds(100, 100, 1600, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.9);
GridBagConstraints gbc_splitPane = new GridBagConstraints();
gbc_splitPane.fill = GridBagConstraints.BOTH;
gbc_splitPane.gridx = 0;
gbc_splitPane.gridy = 2;
frame.getContentPane().add(splitPane, gbc_splitPane);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
splitPane.setLeftComponent(tabbedPane);
GamePanel panel = new GamePanel();
tabbedPane.addTab("Game", null, panel, null);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Logic", null, panel_1, null);
JSplitPane splitPane_1 = new JSplitPane();
splitPane_1.setResizeWeight(0.5);
splitPane_1.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitPane.setRightComponent(splitPane_1);
JPanel panel_2 = new JPanel();
splitPane_1.setLeftComponent(panel_2);
GridBagLayout gbl_panel_2 = new GridBagLayout();
gbl_panel_2.columnWidths = new int[]{0, 0};
gbl_panel_2.rowHeights = new int[]{0, 0, 0, 0};
gbl_panel_2.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_2.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
panel_2.setLayout(gbl_panel_2);
JLabel lblProperties = new JLabel("Objects");
lblProperties.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblProperties = new GridBagConstraints();
gbc_lblProperties.anchor = GridBagConstraints.WEST;
gbc_lblProperties.insets = new Insets(0, 0, 5, 0);
gbc_lblProperties.gridx = 0;
gbc_lblProperties.gridy = 0;
panel_2.add(lblProperties, gbc_lblProperties);
JPanel panel_4 = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel_4.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
GridBagConstraints gbc_panel_4 = new GridBagConstraints();
gbc_panel_4.insets = new Insets(0, 0, 5, 0);
gbc_panel_4.fill = GridBagConstraints.BOTH;
gbc_panel_4.gridx = 0;
gbc_panel_4.gridy = 1;
panel_2.add(panel_4, gbc_panel_4);
JButton btnNewButton = new JButton("Add");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddObjectDialog();
}
});
panel_4.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Delete");
panel_4.add(btnNewButton_1);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 2;
panel_2.add(scrollPane, gbc_scrollPane);
JList list = new JList();
scrollPane.setViewportView(list);
JPanel panel_3 = new JPanel();
splitPane_1.setRightComponent(panel_3);
GridBagLayout gbl_panel_3 = new GridBagLayout();
gbl_panel_3.columnWidths = new int[]{0, 0};
gbl_panel_3.rowHeights = new int[]{0, 0, 0, 0};
gbl_panel_3.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_3.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
panel_3.setLayout(gbl_panel_3);
JLabel lblObjects = new JLabel("Properties");
GridBagConstraints gbc_lblObjects = new GridBagConstraints();
gbc_lblObjects.anchor = GridBagConstraints.WEST;
gbc_lblObjects.insets = new Insets(0, 0, 5, 0);
gbc_lblObjects.gridx = 0;
gbc_lblObjects.gridy = 0;
panel_3.add(lblObjects, gbc_lblObjects);
JPanel panel_5 = new JPanel();
FlowLayout flowLayout_1 = (FlowLayout) panel_5.getLayout();
flowLayout_1.setAlignment(FlowLayout.LEFT);
GridBagConstraints gbc_panel_5 = new GridBagConstraints();
gbc_panel_5.insets = new Insets(0, 0, 5, 0);
gbc_panel_5.fill = GridBagConstraints.BOTH;
gbc_panel_5.gridx = 0;
gbc_panel_5.gridy = 1;
panel_3.add(panel_5, gbc_panel_5);
JButton btnAdd = new JButton("Add");
panel_5.add(btnAdd);
JButton btnDelete = new JButton("Delete");
panel_5.add(btnDelete);
JScrollPane scrollPane_1 = new JScrollPane();
GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints();
gbc_scrollPane_1.fill = GridBagConstraints.BOTH;
gbc_scrollPane_1.gridx = 0;
gbc_scrollPane_1.gridy = 2;
panel_3.add(scrollPane_1, gbc_scrollPane_1);
JList list_1 = new JList();
scrollPane_1.setViewportView(list_1);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
mntmNewGame = new JMenuItem("New game");
mntmNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openNewGameDialog();
}
});
mnFile.add(mntmNewGame);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit();
}
});
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAboutDialog();
}
});
mnHelp.add(mntmAbout);
}
}
| 31.179724 | 75 | 0.737659 |
709b6775cbfa4098345b055005187fc8e0679a94 | 516 | package ggc.core;
public class Acquisition extends Transaction {
Acquisition(int id, Date paymentDate, double baseValue, int quantity, Product product, Partner partner) {
super(id, paymentDate, baseValue, quantity, product, partner);
}
@Override
public String toString() {
return "COMPRA" + "|" + getID() + "|" + getPartner().getID() + "|" + getProduct().getID() + "|" + getQuantity()
+ "|" + Math.round(getBaseValue()) + "|" + getPaymentDate().getDays();
}
}
| 32.25 | 119 | 0.612403 |
494092e59e417bc7763761ca8651c6b5435fdb95 | 3,431 | package game.play;
import processing.core.PShape;
import processing.core.PVector;
import static game.Game.getPApplet;
import static processing.core.PConstants.GROUP;
import static processing.core.PConstants.RECT;
public class AlienSquid extends Alien {
private PShape[] children = new PShape[18];
public AlienSquid(float x, float y, boolean movementLeader, int colNo) {
super(x, y, movementLeader, colNo);
getPApplet().fill(37, 232, 36);
children[0] = getPApplet().createShape(RECT, 12, 15, 3, 3);
children[1] = getPApplet().createShape(RECT, 21, 15, 3, 3);
children[2] = getPApplet().createShape(RECT, 9, 18, 3, 3);
children[3] = getPApplet().createShape(RECT, 15, 18, 3, 3);
children[4] = getPApplet().createShape(RECT, 18, 18, 3, 3);
children[5] = getPApplet().createShape(RECT, 24, 18, 3, 3);
children[6] = getPApplet().createShape(RECT, 6, 21, 3, 3);
children[7] = getPApplet().createShape(RECT, 12, 21, 3, 3);
children[8] = getPApplet().createShape(RECT, 21, 21, 3, 3);
children[9] = getPApplet().createShape(RECT, 27, 21, 3, 3);
children[10] = getPApplet().createShape(RECT, 9, 15, 3, 3);
children[11] = getPApplet().createShape(RECT, 15, 15, 3, 3);
children[12] = getPApplet().createShape(RECT, 18, 15, 3, 3);
children[13] = getPApplet().createShape(RECT, 24, 15, 3, 3);
children[14] = getPApplet().createShape(RECT, 6, 18, 3, 3);
children[15] = getPApplet().createShape(RECT, 27, 18, 3, 3);
children[16] = getPApplet().createShape(RECT, 9, 21, 3, 3);
children[17] = getPApplet().createShape(RECT, 24, 21, 3, 3);
create();
for(int i = 0; i <= 9; i++)
getShape().addChild(children[i]);
}
@Override
public void create() {
getPApplet().fill(37, 232, 36);
setShape(getPApplet().createShape(GROUP));
for(int i = 3; i <= 9; i+=3)
for(int j = 18; j <= 15 + (2 * i); j+=3)
getShape().addChild(getPApplet().createShape(RECT, j - i, i - 3, 3, 3));
getShape().addChild(getPApplet().createShape(RECT, 6, 9, 3, 3));
getShape().addChild(getPApplet().createShape(RECT, 9, 9, 3, 3));
getShape().addChild(getPApplet().createShape(RECT, 15, 9, 3, 3));
getShape().addChild(getPApplet().createShape(RECT, 18, 9, 3, 3));
getShape().addChild(getPApplet().createShape(RECT, 24, 9, 3, 3));
getShape().addChild(getPApplet().createShape(RECT, 27, 9, 3, 3));
for(int i = 6; i <= 27; i+=3)
getShape().addChild(getPApplet().createShape(RECT, i, 12, 3, 3));
}
@Override
public void animate() {
if(getShape().getChildCount() == 36) {
create();
for(int i = 10; i <= 17; i++)
getShape().addChild(children[i]);
} else {
create();
for(int i = 0; i <= 9; i++)
getShape().addChild(children[i]);
}
}
@Override
public float getPotentialXPosOfShotSpawn() {
float shotSpawnPosX = getPos().x + 9;
if(isMovingRight())
shotSpawnPosX = getPos().x + 15;
return shotSpawnPosX;
}
@Override
public PVector getExplosionPos() {
return new PVector(getPos().x - 3, getPos().y);
}
@Override
public int getPoints() {
return 30;
}
}
| 38.988636 | 88 | 0.573885 |
22fafe9dba7a9f2762c4b8c5fe9e5b99d100471a | 5,018 | package com.bina.varsim.fastqLiftover.types;
import com.google.common.base.Joiner;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class SimulatedRead {
private final static Logger log = Logger.getLogger(SimulatedRead.class.getName());
private static final Joiner joiner = Joiner.on(",").skipNulls();
private static final int MAX_SEQ_SELECT = 2;
public List<GenomeLocation> locs1; // List of locations of the alignment of the first end
public List<GenomeLocation> locs2; // List of locations of the alignment of the second end
public List<GenomeLocation> origLocs1; // Original alignment location as reported by the read simulator for the first end
public List<GenomeLocation> origLocs2; // Original alignment location as reported by the read simulator for the second end
public int random1 = 0;
public int random2 = 0;
public int seqErrors1 = 0;
public int snps1 = 0;
public int indels1 = 0;
public int seqErrors2 = 0;
public int snps2 = 0;
public int indels2 = 0;
public int fragment = 1;
public int laneId = 0;
public String sequence;
public String quality;
public int alignedBases1 = 0;
public int alignedBases2 = 0;
protected String readId = "";
public SimulatedRead() {
locs1 = new ArrayList<>();
locs2 = new ArrayList<>();
origLocs1 = new ArrayList<>();
origLocs2 = new ArrayList<>();
}
/* Parses the VarSim generated read-name and fills the fields, except for the quality and sequence */
public SimulatedRead(final String readName) {
final String fields[] = readName.split("[:/]", -1);
random1 = decodeInt(fields[4]);
random2 = decodeInt(fields[5]);
seqErrors1 = decodeInt(fields[6]);
snps1 = decodeInt(fields[7]);
indels1 = decodeInt(fields[8]);
seqErrors2 = decodeInt(fields[9]);
snps2 = decodeInt(fields[10]);
indels2 = decodeInt(fields[11]);
readId = fields[12];
laneId = Integer.parseInt(fields[13]);
locs1 = parseLocations(fields[0]);
locs2 = parseLocations(fields[1]);
origLocs1 = parseLocations(fields[2]);
origLocs2 = parseLocations(fields[3]);
}
public List<GenomeLocation> parseLocations(final String locationsString) {
final String fields[] = locationsString.split(",", -1);
List<GenomeLocation> locations = new ArrayList<>();
for (String field : fields) {
if (!("".equals(field))) {
locations.add(new GenomeLocation(field));
}
}
return locations;
}
public int getLength() {
return sequence.length();
}
public String encodeInt(int n) {
return (n == 0) ? "" : Integer.toString(n);
}
public int decodeInt(String n) {
return "".equals(n) ? 0 : Integer.parseInt(n);
}
public String encodeInts(int... numbers) {
StringBuilder sb = new StringBuilder();
for (int number : numbers) {
sb.append(":");
if (number != 0) {
sb.append(number);
}
}
return sb.toString();
}
public String getName() {
return joiner.join(locs1) + ":" + joiner.join(locs2) + ":" + joiner.join(origLocs1) + ":" + joiner.join(origLocs2)
+ encodeInts(random1, random2, seqErrors1, snps1, indels1, seqErrors2, snps2, indels2) + ":" + readId + ":" + laneId + "/" + fragment;
}
private List<GenomeLocation> selectLocs(final List<GenomeLocation> locs) {
List<GenomeLocation> selected = new ArrayList<>();
int seqSelected = 0;
for (GenomeLocation g : locs) {
if ("S".equals(g.feature) || "".equals(g.feature)) {
if (seqSelected < MAX_SEQ_SELECT) {
selected.add(g);
seqSelected++;
}
} else {
selected.add(g);
}
}
return selected;
}
public String getShortName() {
return joiner.join(selectLocs(locs1)) + ":" + joiner.join(selectLocs(locs2)) + ":" + joiner.join(origLocs1) + ":" + joiner.join(origLocs2)
+ encodeInts(random1, random2, seqErrors1, snps1, indels1, seqErrors2, snps2, indels2) + ":" + readId + ":" + laneId + "/" + fragment;
}
public String getReadId() {
return readId;
}
public void setReadId(String readId) {
this.readId = readId;
}
public String toString() {
String name = getName();
if (name.length() > 255) {
log.warn("Read name " + name + " too long " + name.length() + " chars. Using only a few locations instead.");
name = getShortName();
}
return "@" + name + "\n" + sequence + "\n+\n" + quality;
}
public Collection<GenomeLocation> getLocs(int index) {
return (index == 0) ? locs1 : locs2;
}
}
| 34.847222 | 150 | 0.594659 |
bb575eb0f284b42bbaa72f2d7c27490b5db6dbad | 13,775 | package dev.util.crypto;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import dev.util.HexUtil;
import java.nio.file.Paths;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
public class RSAUtil
{
private final static String NAME = "RSA";
private final static String PEM_PREFIX_PRIVATE = "-----BEGIN PRIVATE KEY-----";
//private final static String PEM_PREFIX_RSA_PRIVATE = "-----BEGIN RSA PRIVATE KEY-----";
private final static String PEM_POSTFIX_PRIVATE = "-----END PRIVATE KEY-----";
//private final static String PEM_POSTFIX_RSA_PRIVATE = "-----END RSA PRIVATE KEY-----";
private final static String PEM_PREFIX_PUBLIC = "-----BEGIN PUBLIC KEY-----";
//private final static String PEM_PREFIX_RSA_PUBLIC = "-----BEGIN RSA PUBLIC KEY-----";
private final static String PEM_POSTFIX_PUBLIC = "-----END PUBLIC KEY-----";
//private final static String PEM_POSTFIX_RSA_PUBLIC = "-----END RSA PUBLIC KEY-----";
private final static String PEM_PREFIX_PRIVATE_KEY_REGEX = "-----BEGIN( RSA)? PRIVATE KEY-----";
private final static String PEM_POSTFIX_PRIVATE_KEY_REGEX = "-----END( RSA)? PRIVATE KEY-----";
private final static String PEM_PREFIX_PUBLIC_KEY_REGEX = "-----BEGIN( RSA)? PUBLIC KEY-----";
private final static String PEM_POSTFIX_PUBLIC_KEY_REGEX = "-----END( RSA)? PUBLIC KEY-----";
public enum KEY_SIZE {
KS_512(512), KS_1024(1024), KS_2048(2048), KS_3072(3072);
private final int mKeySize;
KEY_SIZE(int keySize) { mKeySize = keySize; }
public int getKeySize() { return mKeySize; }
public int getKeySizeByte() { return mKeySize / 8; }
}
public static byte[] encryptData( PublicKey key, byte[] planeData ) {
try {
Cipher encoder = Cipher.getInstance(NAME);
encoder.init(Cipher.ENCRYPT_MODE, key);
return encoder.doFinal(planeData);
}
catch(NoSuchAlgorithmException nsae) {
// Never Reach Here!!
}
catch(NoSuchPaddingException nspe) {
// Never Reach Here!!
}
catch(InvalidKeyException ike) {
// Fail
}
catch(IllegalBlockSizeException ibse) {
// Fail
}
catch(BadPaddingException bpe) {
// Fail
}
return null;
}
public static String encryptDataToBase64( PublicKey key, byte[] planeData ) {
byte[] encData = encryptData( key, planeData );
if( encData != null ) {
return Base64.getEncoder().encodeToString(encData);
}
return null;
}
public static String encryptDataToHex( PublicKey key, byte[] planeData, boolean isUpperCase ) {
return HexUtil.toHexString( encryptData(key, planeData), isUpperCase );
}
public static String encryptDataToHex( PublicKey key, byte[] planeData ) {
return encryptDataToHex( key, planeData, true );
}
public static byte[] decryptData( PrivateKey key, byte[] encryptedData ) {
try {
Cipher decoder = Cipher.getInstance(NAME);
decoder.init(Cipher.DECRYPT_MODE, key);
return decoder.doFinal(encryptedData);
}
catch(NoSuchAlgorithmException nsae) {
// Never Reach Here!!
}
catch(NoSuchPaddingException nspe) {
// Never Reach Here!!
}
catch(InvalidKeyException ike) {
// Fail
}
catch(IllegalBlockSizeException ibse) {
// Fail
}
catch(BadPaddingException bpe) {
// Fail
}
return null;
}
public static byte[] decryptDataFromBase64( PrivateKey key, String encryptedDataBase64 ) {
return decryptData( key, Base64.getDecoder().decode(encryptedDataBase64) );
}
public static byte[] decryptDataFromHex( PrivateKey key, String encryptedDataHex ) {
return decryptData( key, HexUtil.toByteArray(encryptedDataHex) );
}
public static KeyPair generateKeyPair( KEY_SIZE keySize ) {
try {
KeyPairGenerator keygen = KeyPairGenerator.getInstance(NAME);
keygen.initialize(keySize.getKeySize());
return keygen.generateKeyPair();
}catch(NoSuchAlgorithmException e) {
// Never Reach Here!!
}
return null;
}
public static PublicKey generatePublicKeyFromPrivateKey(PrivateKey privKey) {
try {
KeyFactory keygen = KeyFactory.getInstance(NAME);
RSAPrivateCrtKey rsaPrivKey = (RSAPrivateCrtKey)privKey;
return keygen.generatePublic( new RSAPublicKeySpec(rsaPrivKey.getModulus(), rsaPrivKey.getPublicExponent()) );
} catch(NoSuchAlgorithmException nsae) {
// Never Reach Here!!
} catch(InvalidKeySpecException ikse ) {
// Never Reach Here!!
}
return null;
}
public static boolean checkKeyPair(PrivateKey privKey, PublicKey pubKey)
{
if( privKey instanceof RSAPrivateKey && pubKey instanceof RSAPublicKey ) {
RSAPrivateKey rsaPrivKey = (RSAPrivateKey)privKey;
RSAPublicKey rsaPubKey = (RSAPublicKey)pubKey;
if( rsaPrivKey.getModulus().equals( rsaPubKey.getModulus() ) ) {
return BigInteger.valueOf(2).modPow(
rsaPubKey.getPublicExponent().multiply( rsaPrivKey.getPrivateExponent() ).subtract( BigInteger.ONE ),
rsaPubKey.getModulus()
).equals( BigInteger.ONE );
}
}
return false;
}
public static String generateSignatureFromPublicKey(KeyPair key) {
return generateSignatureFromPublicKey(key.getPublic());
}
public static String generateSignatureFromPublicKey(PublicKey pubKey) {
byte[] keyBytes = pubKey.getEncoded();
MessageDigest digest = null;
try { digest = MessageDigest.getInstance("SHA-1"); } catch(Exception ignore) {}
digest.reset();
digest.update(keyBytes);
return Base64.getEncoder().encodeToString( digest.digest() );
}
public static String privateKeyToPEMString(PrivateKey privKey) {
return _makePEMString( Base64.getEncoder().encodeToString( privKey.getEncoded() ), true );
// return PEM_PREFIX_PRIVATE_RSA + "\n" + Base64.getEncoder().encodeToString( privKey.getEncoded() ) + "\n" + PEM_POSTFIX_PRIVATE_RSA + "\n";
}
public static String publicKeyToPEMString(PublicKey pubKey) {
return _makePEMString( Base64.getEncoder().encodeToString( pubKey.getEncoded() ), false );
// return PEM_PREFIX_PUBLIC_RSA+ "\n" + Base64.getEncoder().encodeToString( pubKey.getEncoded() )+ "\n" + PEM_POSTFIX_PUBLIC_RSA + "\n";
}
public static PublicKey generatePublicKeyFromPEMFile( String fileName ) throws InvalidKeySpecException {
String fileContent = _readAsString(fileName);
if( fileContent == null ) { return null; } // File Not Found or No Permission Exception
if(!fileContent.startsWith("-----BEGIN")) { return null; } // Wrong File Format Exception (Not PEM File)
byte[] encodedBytes = _PEMStringToByteArray(fileContent, false);
KeyFactory keygen = null;
try { keygen = KeyFactory.getInstance(NAME); } catch(Exception ignore) {}
return keygen.generatePublic(new X509EncodedKeySpec(encodedBytes));
}
public static PrivateKey generatePrivateKeyFromPEMFile( String fileName ) throws InvalidKeySpecException {
String fileContent = _readAsString(fileName);
if( fileContent == null ) { return null; } // File Not Found or No Permission Exception
if(!fileContent.startsWith("-----BEGIN")) { return null; } // Wrong File Format Exception (Not PEM File)
byte[] encodedBytes = _PEMStringToByteArray(fileContent, true);
KeyFactory keygen = null;
try { keygen = KeyFactory.getInstance(NAME); } catch(Exception ignore) {}
if( _isSequenceEncode(encodedBytes, 0) ) {
try {
int offsetToVersion = _getASN1EncodeDataOffset(encodedBytes, 0);
int offsetToModule = offsetToVersion + _getASN1EncodeTotalLength(encodedBytes, offsetToVersion);
if( _isIntegerEncode(encodedBytes, offsetToModule) ) {
int offsetToPublicExp = offsetToModule + _getASN1EncodeTotalLength(encodedBytes, offsetToModule);
int offsetToPrivateExp = offsetToPublicExp + _getASN1EncodeTotalLength(encodedBytes, offsetToPublicExp);
if( !_isIntegerEncode(encodedBytes, offsetToPublicExp) || !_isIntegerEncode(encodedBytes, offsetToPrivateExp) ) {
}
BigInteger modules = _getASN1IntegerData(encodedBytes, offsetToModule);
BigInteger privateExp = _getASN1IntegerData(encodedBytes, offsetToPrivateExp);
return keygen.generatePrivate( new RSAPrivateKeySpec(modules, privateExp) );
}
}
catch(IndexOutOfBoundsException ioobe) {
throw new InvalidKeySpecException("Unexpected Encoded Format");
}
}
return keygen.generatePrivate( new PKCS8EncodedKeySpec(encodedBytes) );
}
private static boolean _isSequenceEncode(byte[] encodedData, int offset) {
return (encodedData[offset] & 0x1F) == 16;
}
private static boolean _isIntegerEncode(byte[] encodedData, int offset) {
return (encodedData[offset] & 0x1F) == 2;
}
private static int _getASN1EncodeDataOffset(byte[] encodedData, int offset) {
return (offset + 2) + ( ( (encodedData[offset + 1] & 0x80) != 0 ) ? (encodedData[offset + 1] & 0x7F) : 0 );
}
private static int _getASN1EncodeTotalLength(byte[] encodedData, int offset) throws InvalidKeySpecException, IndexOutOfBoundsException {
int len = _getASN1EncodeDataLength(encodedData, offset);
if( (encodedData[offset + 1] & 0x80) != 0 ) {
len += ((encodedData[offset + 1] & 0x7F));
}
return len + 2;
}
private static int _getASN1EncodeDataLength(byte[] encodedData, int offset) throws InvalidKeySpecException, IndexOutOfBoundsException {
int len = (encodedData[offset + 1] & 0x7F);
if( (encodedData[offset + 1] & 0x80) != 0 ) {
byte[] buf = { 0, 0, 0, 0 };
if( len > buf.length ) { throw new InvalidKeySpecException("Encoded Length is too Huge"); }
for(int i = 0, j = buf.length - len; i < len ; i++, j++) {
buf[j] = encodedData[ offset + 2 + i ];
}
len = ByteBuffer.wrap(buf).order(ByteOrder.BIG_ENDIAN).getInt();
}
return len;
}
private static BigInteger _getASN1IntegerData(byte[] encodedData, int offset) throws InvalidKeySpecException, IndexOutOfBoundsException {
int newOffset = _getASN1EncodeDataOffset(encodedData, offset);
int len = _getASN1EncodeDataLength(encodedData, offset);
return new BigInteger( encodedData, newOffset, len);
}
private static String _makePEMString( String base64EncodeStr, boolean isPrivate ) {
String prefix = isPrivate ? PEM_PREFIX_PRIVATE : PEM_PREFIX_PUBLIC;
String postfix = isPrivate ? PEM_POSTFIX_PRIVATE : PEM_POSTFIX_PUBLIC;
int baseSplitCount = base64EncodeStr.length() / 64;
int beginIndex = 0;
StringBuilder sb = new StringBuilder( prefix.length() + postfix.length() + base64EncodeStr.length() + baseSplitCount + 3 );
sb.append(prefix).append("\n");
for(int i = 0; i < baseSplitCount; i++) {
sb.append( base64EncodeStr.substring(beginIndex, beginIndex + 64) ).append("\n");
beginIndex += 64;
}
if( base64EncodeStr.length() % 64 > 0 ) {
sb.append( base64EncodeStr.substring(beginIndex) ).append("\n");
}
sb.append(postfix).append("\n");
return sb.toString();
}
private static byte[] _PEMStringToByteArray(String pemContent, boolean isPrivate) {
if( pemContent != null ) {
return Base64.getDecoder().decode(
pemContent.replaceFirst(isPrivate ? PEM_PREFIX_PRIVATE_KEY_REGEX : PEM_PREFIX_PUBLIC_KEY_REGEX, "")
.replaceFirst(isPrivate ? PEM_POSTFIX_PRIVATE_KEY_REGEX : PEM_POSTFIX_PUBLIC_KEY_REGEX, "")
.replaceAll("\\s+", "")
);
}
return null;
}
private static byte[] _readAsBytes(String fileName) {
try { return Files.readAllBytes( Paths.get(fileName) ); } catch(Exception e) { }
return null;
}
private static String _readAsString(String fileName) {
byte[] bytes = _readAsBytes(fileName);
return bytes != null ? new String(bytes) : null;
}
} | 41.366366 | 149 | 0.648857 |
c536aac0e34f0df6e6e1633d1d90ddbd0a0e9e02 | 2,064 | /*
PreviewServer.java
Copyright (c) 2017 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.theta.core.preview;
import javax.net.ssl.SSLContext;
/**
* プレビュー配信用サーバを定義するインターフェース.
*/
public interface PreviewServer {
/**
* サーバが配信するプレビューのマイムタイプを取得します.
*
* @return マイムタイプ
*/
String getMimeType();
/**
* サーバへの URL を取得します.
*
* @return サーバへの URL
*/
String getUri();
/**
* プレビュー配信サーバのポート番号を取得します.
*
* @return ポート番号
*/
int getPort();
/**
* プレビュー配信サーバのポート番号を設定します.
*
* @param port ポート番号
*/
void setPort(int port);
/**
* サーバを開始します.
*
* @param callback 開始結果を通知するコールバック
*/
void startWebServer(OnWebServerStartCallback callback);
/**
* サーバを停止します.
*/
void stopWebServer();
/**
* 画面が回転されたことを通知します.
*/
void onConfigChange();
/**
* Recorder をミュート状態にする.
*/
void mute();
/**
* Recorder のミュート状態を解除する.
*/
void unMute();
/**
* Recorder のミュート状態を返す.
* @return mute状態
*/
boolean isMuted();
/**
* 映像のエンコーダーに対して sync frame の即時生成を要求する.
*
* @return 即時生成を受け付けた場合は<code>true</code>, そうでない場合は<code>false</code>
*/
boolean requestSyncFrame();
/**
* SSLContext を使用するかどうかのフラグを返す.
*
* @return SSLContext を使用する場合は<code>true</code>, そうでない場合は<code>false</code>
*/
boolean usesSSLContext();
void setSSLContext(SSLContext sslContext);
SSLContext getSSLContext();
/**
* Callback interface used to receive the result of starting a web server.
*/
interface OnWebServerStartCallback {
/**
* Called when a web server successfully started.
*
* @param uri An ever-updating, static image URI.
*/
void onStart(String uri);
/**
* Called when a web server failed to start.
*/
void onFail();
}
}
| 18.594595 | 79 | 0.573643 |
13b9749940ef109ee2bb5a355d05988d8d151da1 | 1,934 | package lab4.client;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import lab4.dependency.RMIConstant;
import lab4.dependency.ResourceCollector;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Iterator;
public class Controller {
public TextField filterTextField;
public Button connectButton;
public ImageView resourcesView;
private ResourceCollector h;
public Controller() throws RemoteException, NotBoundException {
Registry registry= LocateRegistry.getRegistry("localhost", RMIConstant.RPORT);
h = (ResourceCollector) registry.lookup(RMIConstant.RID);
}
public void onNextButtonClick(ActionEvent actionEvent) {
resourcesView.setImage(new Image(images.next()));
}
private class ImageIterator implements Iterator<String>{
ImageIterator(String[] urls){
this.urls=urls;
index=0;
}
@Override
public boolean hasNext() {
return true;
}
private String[] urls;
private int index;
@Override
public String next() {
if(urls.length>0){
index++;
index%=urls.length;
return urls[index];
}else{
return "";
}
}
}
private ImageIterator images=new ImageIterator(new String[0]);
public void onConnectButtonClick(ActionEvent actionEvent) {
String filter=filterTextField.getText();
try
{
images=new ImageIterator(h.getUrls(filter));
}
catch (Exception e)
{
System.out.println ("ResourceCollector client exception: " + e);
}
}
}
| 27.628571 | 86 | 0.643226 |
607b6798e4efe97f1e30746e0393435a4deb79d6 | 316 | package org.woo.dubbo;
import org.woo.service.lookup.ServiceLookUp;
/**
* @author Administrator
* @date 2018 07
* org.woo.dubbo.DubboServiceLookUp
*/
public class DubboServiceLookUp extends ServiceLookUp {
@Override
protected <T> T lookupImpl(Class<T> aClass, String s) {
return null;
}
}
| 18.588235 | 59 | 0.699367 |
c3ba71997b723f1f9cfaa25774a98e57f7a60d40 | 5,386 | package com.gank.gankly.ui.main.ios;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.gank.gankly.R;
import com.gank.gankly.bean.ResultsBean;
import com.gank.gankly.config.Constants;
import com.gank.gankly.listener.RecyclerOnClick;
import com.gank.gankly.mvp.source.remote.GankDataSource;
import com.gank.gankly.ui.base.LazyFragment;
import com.gank.gankly.ui.main.MainActivity;
import com.gank.gankly.ui.web.normal.WebActivity;
import com.gank.gankly.utils.theme.RecyclerViewColor;
import com.gank.gankly.utils.theme.ThemeColor;
import com.gank.gankly.widget.LySwipeRefreshLayout;
import com.gank.gankly.widget.MultipleStatusView;
import java.util.List;
import butterknife.BindView;
/**
* ios
* Create by LingYan on 2016-4-26
* Email:137387869@qq.com
*/
public class IosFragment extends LazyFragment implements RecyclerOnClick, IosContract.View {
@BindView(R.id.multiple_status_view)
MultipleStatusView mMultipleStatusView;
@BindView(R.id.swipe_refresh)
LySwipeRefreshLayout mSwipeRefreshLayout;
private MainActivity mActivity;
private IosAdapter mRecyclerAdapter;
private IosContract.Presenter mPresenter;
private RecyclerView mRecyclerView;
@Override
protected int getLayoutId() {
return R.layout.layout_swipe_normal;
}
public static IosFragment newInstance() {
IosFragment fragment = new IosFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
protected void initPresenter() {
mPresenter = new IosPresenter(GankDataSource.getInstance(), this);
}
@Override
protected void initValues() {
}
@Override
protected void initViews() {
setSwipeRefreshLayout(mSwipeRefreshLayout);
mRecyclerAdapter = new IosAdapter(mActivity);
mSwipeRefreshLayout.setAdapter(mRecyclerAdapter);
mRecyclerView = mSwipeRefreshLayout.getRecyclerView();
mRecyclerView.setHasFixedSize(true);
mRecyclerAdapter.setOnItemClickListener(this);
mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(mActivity));
}
@Override
protected void bindListener() {
mMultipleStatusView.setListener(v -> initFetchDate());
mSwipeRefreshLayout.setOnScrollListener(new LySwipeRefreshLayout.OnSwipeRefRecyclerViewListener() {
@Override
public void onRefresh() {
mPresenter.fetchNew();
}
@Override
public void onLoadMore() {
mPresenter.fetchMore();
}
});
}
@Override
protected void initData() {
showLoading();
initFetchDate();
}
private void initFetchDate() {
mPresenter.fetchNew();
}
@Override
public void showLoading() {
mMultipleStatusView.showLoading();
}
@Override
public void showRefreshError(String errorStr) {
Snackbar.make(mSwipeRefreshLayout, errorStr, Snackbar.LENGTH_LONG)
.setAction(R.string.retry, v -> mPresenter.fetchMore());
}
@Override
public void showError() {
mMultipleStatusView.showError();
}
@Override
public void showEmpty() {
mMultipleStatusView.showEmpty();
}
@Override
public void showRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
}
@Override
public void hideRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void hasNoMoreDate() {
}
@Override
public void showContent() {
mMultipleStatusView.showContent();
}
@Override
public void showDisNetWork() {
mMultipleStatusView.showDisNetwork();
}
@Override
public void onClick(View view, ResultsBean bean) {
Bundle bundle = new Bundle();
bundle.putString(WebActivity.TITLE, bean.getDesc());
bundle.putString(WebActivity.URL, bean.getUrl());
bundle.putString(WebActivity.TYPE, Constants.IOS);
bundle.putString(WebActivity.AUTHOR, bean.getWho());
WebActivity.startWebActivity(mActivity, bundle);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mActivity = (MainActivity) context;
}
@Override
protected void callBackRefreshUi() {
ThemeColor themeColor = new ThemeColor(this);
RecyclerViewColor mRecycler = new RecyclerViewColor(mRecyclerView);
mRecycler.setItemColor(R.id.ios_txt_title, R.attr.baseAdapterItemTextColor);
mRecycler.setItemColor(R.id.ios_txt_time, R.attr.textSecondaryColor);
mRecycler.setItemBackgroundColor(R.id.ios_ll, R.attr.lyItemSelectBackground);
themeColor.setBackgroundResource(R.attr.themeBackground, mRecyclerView);
themeColor.swipeRefresh(mSwipeRefreshLayout);
themeColor.recyclerViewColor(mRecycler);
themeColor.start();
}
@Override
public void refillDate(List<ResultsBean> list) {
mRecyclerAdapter.refillItems(list);
}
@Override
public void appendData(List<ResultsBean> list) {
mRecyclerAdapter.appendItems(list);
}
}
| 28.497354 | 107 | 0.692722 |
3343bfb55fd75700be5e8c2f4b7aaece52fb0dda | 7,550 | package net.petafuel.styx.core.persistence.layers;
import net.petafuel.styx.core.persistence.Persistence;
import net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException;
import net.petafuel.styx.core.persistence.PersistenceException;
import net.petafuel.styx.core.xs2a.oauth.entities.OAuthSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.UUID;
public class PersistentOAuthSession {
private static final Logger LOG = LogManager.getLogger(PersistentOAuthSession.class);
private PersistentOAuthSession() {
}
public static OAuthSession create(OAuthSession model) {
Connection connection = Persistence.getInstance().getConnection();
try (PreparedStatement query = connection.prepareStatement("SELECT * FROM create_oauth_session(?, ?, ?, ?, ?, ?, ?)")) {
query.setString(1, model.getAuthorizationEndpoint());
query.setString(2, model.getTokenEndpoint());
query.setString(3, model.getCodeVerifier());
query.setString(4, model.getState());
query.setString(5, model.getScope());
query.setObject(6, model.getId());
query.setObject(7, model.getxRequestId());
try (ResultSet resultSet = query.executeQuery()) {
if (resultSet.next()) {
model = dbToModel(resultSet);
}
}
} catch (SQLException e) {
logSQLError(e);
}
return model;
}
/**
* Retrieve an existing oauth session from the database using the state attribute
*
* @param state state
* @return found oauth session
* @throws PersistenceEmptyResultSetException in case there was no match within the database
* @throws PersistenceException if an unexpected SQL Error occurred
*/
public static OAuthSession getByState(String state) {
Connection connection = Persistence.getInstance().getConnection();
try (PreparedStatement query = connection.prepareStatement("SELECT * FROM get_oauth_session_by_state(?)")) {
query.setString(1, state);
try (ResultSet resultSet = query.executeQuery()) {
if (resultSet.next()) {
return dbToModel(resultSet);
}
}
throw new PersistenceEmptyResultSetException("No OAuth session found for the given state");
} catch (SQLException e) {
logSQLError(e);
throw new PersistenceException(e.getMessage(), e);
}
}
/**
* Retrieve an existing oauth session from the database using the id
*
* @param uuid (used as a preauthId during the pre-step)
* @return found oauth session
* @throws PersistenceEmptyResultSetException in case there was no match within the database
* @throws PersistenceException if an unexpected SQL Error occurred
*/
public static OAuthSession getById(UUID uuid) {
Connection connection = Persistence.getInstance().getConnection();
try (PreparedStatement query = connection.prepareStatement("SELECT * FROM get_oauth_session_by_id(?)")) {
query.setObject(1, uuid);
try (ResultSet resultSet = query.executeQuery()) {
if (resultSet.next()) {
return dbToModel(resultSet);
}
}
throw new PersistenceEmptyResultSetException("No OAuth session found for the given id");
} catch (SQLException e) {
logSQLError(e);
throw new PersistenceException(e.getMessage(), e);
}
}
/**
* Retrieve an existing oauth session from the database using the x_request_id
*
* @param uuid (X-Request-id used during the creation of a consent or payment)
* @return found oauth session
* @throws PersistenceEmptyResultSetException in case there was no match within the database
* @throws PersistenceException if an unexpected SQL Error occurred
*/
public static OAuthSession getByXRequestId(UUID uuid) {
Connection connection = Persistence.getInstance().getConnection();
try (PreparedStatement query = connection.prepareStatement("SELECT * FROM get_oauth_session_by_x_request_id(?)")) {
query.setObject(1, uuid);
try (ResultSet resultSet = query.executeQuery()) {
if (resultSet.next()) {
return dbToModel(resultSet);
}
}
throw new PersistenceEmptyResultSetException("No OAuth session found for the given x_request_id");
} catch (SQLException e) {
logSQLError(e);
throw new PersistenceException(e.getMessage(), e);
}
}
public static OAuthSession update(OAuthSession model) {
Connection connection = Persistence.getInstance().getConnection();
try (PreparedStatement query = connection.prepareStatement("SELECT * FROM update_oauth_session(?, ?, ?, ?, ?, ?)")) {
query.setString(1, model.getAccessToken());
query.setString(2, model.getTokenType());
query.setString(3, model.getRefreshToken());
query.setTimestamp(4, new Timestamp(model.getAccessTokenExpiresAt().getTime()));
query.setTimestamp(5, new Timestamp(model.getRefreshTokenExpiresAt().getTime()));
query.setString(6, model.getState());
try (ResultSet resultSet = query.executeQuery()) {
if (resultSet.next()) {
return dbToModel(resultSet);
}
}
throw new PersistenceException("No OAuthSession found for the given state");
} catch (SQLException e) {
logSQLError(e);
throw new PersistenceException(e.getMessage(), e);
}
}
private static OAuthSession dbToModel(ResultSet resultSet) throws SQLException {
OAuthSession model = new OAuthSession();
model.setId(UUID.fromString(resultSet.getString("id")));
if (resultSet.getString("x_request_id") != null) {
model.setxRequestId(UUID.fromString(resultSet.getString("x_request_id")));
}
model.setAuthorizationEndpoint(resultSet.getString("authorization_endpoint"));
model.setTokenEndpoint(resultSet.getString("token_endpoint"));
model.setCodeVerifier(resultSet.getString("code_verifier"));
model.setState(resultSet.getString("state"));
model.setScope(resultSet.getString("scope"));
model.setAccessToken(resultSet.getString("access_token"));
model.setTokenType(resultSet.getString("token_type"));
model.setRefreshToken(resultSet.getString("refresh_token"));
model.setAccessTokenExpiresAt(resultSet.getTimestamp("access_token_expires_at"));
model.setRefreshTokenExpiresAt(resultSet.getTimestamp("refresh_token_expires_at"));
model.setAuthorizedAt(resultSet.getTimestamp("authorized_at"));
model.setCreatedAt(resultSet.getTimestamp("created_at"));
return model;
}
private static void logSQLError(SQLException e) {
LOG.error("Error executing SQL Query: {} SQL State: {}, StackTrace: {}", e.getMessage(), e.getSQLState(), e.getStackTrace());
throw new PersistenceException(e.getMessage(), e);
}
}
| 46.036585 | 133 | 0.652185 |
d286b5c9e9d5f5b220470a6cea7a6ba6850607a2 | 850 | /*
* Copyright (c) 2016 Yahoo Inc.
* Licensed under the terms of the Apache version 2.0 license.
* See LICENSE file for terms.
*/
package com.yahoo.yqlplus.engine.sources;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.yahoo.yqlplus.api.Source;
import com.yahoo.yqlplus.api.annotations.Query;
import com.yahoo.yqlplus.api.trace.Tracer;
import com.yahoo.yqlplus.engine.java.Person;
import java.util.List;
public class TracingSource implements Source {
private final Tracer tracer;
@Inject
TracingSource(Tracer tracer) {
this.tracer = tracer;
}
@Query
public List<Person> scan() {
try (Tracer trace = tracer.start("MINE", "MINE")) {
trace.fine("Done scanning");
return ImmutableList.of(new Person("1", "joe", 0));
}
}
}
| 24.285714 | 63 | 0.682353 |
65b557c1e361e55e5ae0b38e5a11674c1785b81d | 420 | package com.java.demos.spring.repositories;
import com.java.demos.spring.models.Author;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface AuthorRepository extends JpaRepository<Author, Long> {
Author findAuthorByEmail(String email);
Optional<Author> findAuthorByUsername(String username);
}
| 30 | 71 | 0.82381 |
98dc8f07b7750464ec9ccb415465d5a0c31cdbd2 | 9,733 | package net.minecraft.world;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.enchantment.EnchantmentProtection;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.craftbukkit.event.CraftEventFactory;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.*;
public class Explosion {
public boolean isFlaming;
public boolean isSmoking = true;
private final int field_77289_h = 16;
private final Random explosionRNG = new Random();
private final World worldObj;
public double explosionX;
public double explosionY;
public double explosionZ;
public Entity exploder;
public float explosionSize;
@SuppressWarnings("rawtypes")
public List affectedBlockPositions = new ArrayList();
@SuppressWarnings("rawtypes")
private final Map field_77288_k = new HashMap();
public Explosion(World p_i1948_1_, Entity p_i1948_2_, double p_i1948_3_, double p_i1948_5_, double p_i1948_7_,
float p_i1948_9_) {
worldObj = p_i1948_1_;
exploder = p_i1948_2_;
explosionSize = p_i1948_9_;
explosionX = p_i1948_3_;
explosionY = p_i1948_5_;
explosionZ = p_i1948_7_;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void doExplosionA() {
// CraftBukkit start
if (explosionSize < 0.1F)
return;
// CraftBukkit end
float f = explosionSize;
HashSet hashset = new HashSet();
int i;
int j;
int k;
double d5;
double d6;
double d7;
for (i = 0; i < field_77289_h; ++i) {
for (j = 0; j < field_77289_h; ++j) {
for (k = 0; k < field_77289_h; ++k) {
if (i == 0 || i == field_77289_h - 1 || j == 0 || j == field_77289_h - 1 || k == 0
|| k == field_77289_h - 1) {
double d0 = i / (field_77289_h - 1.0F) * 2.0F - 1.0F;
double d1 = j / (field_77289_h - 1.0F) * 2.0F - 1.0F;
double d2 = k / (field_77289_h - 1.0F) * 2.0F - 1.0F;
double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2);
d0 /= d3;
d1 /= d3;
d2 /= d3;
float f1 = explosionSize * (0.7F + worldObj.rand.nextFloat() * 0.6F);
d5 = explosionX;
d6 = explosionY;
d7 = explosionZ;
for (float f2 = 0.3F; f1 > 0.0F; f1 -= f2 * 0.75F) {
int j1 = MathHelper.floor_double(d5);
int k1 = MathHelper.floor_double(d6);
int l1 = MathHelper.floor_double(d7);
Block block = worldObj.getBlock(j1, k1, l1);
if (block.getMaterial() != Material.air) {
float f3 = exploder != null ? exploder.func_145772_a(this, worldObj, j1, k1, l1, block)
: block.getExplosionResistance(exploder, worldObj, j1, k1, l1, explosionX,
explosionY, explosionZ);
f1 -= (f3 + 0.3F) * f2;
}
if (f1 > 0.0F && (exploder == null
|| exploder.func_145774_a(this, worldObj, j1, k1, l1, block, f1))) {
hashset.add(new ChunkPosition(j1, k1, l1));
}
d5 += d0 * f2;
d6 += d1 * f2;
d7 += d2 * f2;
}
}
}
}
}
affectedBlockPositions.addAll(hashset);
explosionSize *= 2.0F;
i = MathHelper.floor_double(explosionX - explosionSize - 1.0D);
j = MathHelper.floor_double(explosionX + explosionSize + 1.0D);
k = MathHelper.floor_double(explosionY - explosionSize - 1.0D);
int i2 = MathHelper.floor_double(explosionY + explosionSize + 1.0D);
int l = MathHelper.floor_double(explosionZ - explosionSize - 1.0D);
int j2 = MathHelper.floor_double(explosionZ + explosionSize + 1.0D);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(exploder,
AxisAlignedBB.getBoundingBox(i, k, l, j, i2, j2));
net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(worldObj, this, list, explosionSize);
Vec3 vec3 = Vec3.createVectorHelper(explosionX, explosionY, explosionZ);
for (int i1 = 0; i1 < list.size(); ++i1) {
Entity entity = (Entity) list.get(i1);
double d4 = entity.getDistance(explosionX, explosionY, explosionZ) / explosionSize;
if (d4 <= 1.0D) {
d5 = entity.posX - explosionX;
d6 = entity.posY + entity.getEyeHeight() - explosionY;
d7 = entity.posZ - explosionZ;
double d9 = MathHelper.sqrt_double(d5 * d5 + d6 * d6 + d7 * d7);
if (d9 != 0.0D) {
d5 /= d9;
d6 /= d9;
d7 /= d9;
double d10 = worldObj.getBlockDensity(vec3, entity.boundingBox);
double d11 = (1.0D - d4) * d10;
// CraftBukkit start
CraftEventFactory.entityDamage = exploder;
if (!entity.attackEntityFrom(DamageSource.setExplosionSource(this),
(int) ((d11 * d11 + d11) / 2.0D * 8.0D * explosionSize + 1.0D))) {
CraftEventFactory.entityDamage = null;
}
// if (!MinecraftServer.cauldronConfig.allowTntPunishment.getValue()) continue;
// CraftBukkit end
double d8 = EnchantmentProtection.func_92092_a(entity, d11);
entity.motionX += d5 * d8;
entity.motionY += d6 * d8;
entity.motionZ += d7 * d8;
if (entity instanceof EntityPlayer) {
field_77288_k.put(entity, Vec3.createVectorHelper(d5 * d11, d6 * d11, d7 * d11));
}
}
}
}
explosionSize = f;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void doExplosionB(boolean p_77279_1_) {
worldObj.playSoundEffect(explosionX, explosionY, explosionZ, "random.explode", 4.0F,
(1.0F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.2F) * 0.7F);
if (explosionSize >= 2.0F && isSmoking) {
worldObj.spawnParticle("hugeexplosion", explosionX, explosionY, explosionZ, 1.0D, 0.0D, 0.0D);
} else {
worldObj.spawnParticle("largeexplode", explosionX, explosionY, explosionZ, 1.0D, 0.0D, 0.0D);
}
Iterator iterator;
ChunkPosition chunkposition;
int i;
int j;
int k;
Block block;
if (isSmoking) {
// CraftBukkit start
org.bukkit.World bworld = worldObj.getWorld();
org.bukkit.entity.Entity explode = exploder == null ? null : exploder.getBukkitEntity();
Location location = new Location(bworld, explosionX, explosionY, explosionZ);
List<org.bukkit.block.Block> blockList = new ArrayList<>();
for (int i1 = affectedBlockPositions.size() - 1; i1 >= 0; i1--) {
ChunkPosition cpos = (ChunkPosition) affectedBlockPositions.get(i1);
org.bukkit.block.Block bblock = bworld.getBlockAt(cpos.chunkPosX, cpos.chunkPosY, cpos.chunkPosZ);
if (bblock.getType() != org.bukkit.Material.AIR) {
blockList.add(bblock);
}
}
EntityExplodeEvent event = new EntityExplodeEvent(explode, location, blockList, 0.3F);
Bukkit.getServer().getPluginManager().callEvent(event);
affectedBlockPositions.clear();
for (org.bukkit.block.Block bblock : event.blockList()) {
ChunkPosition coords = new ChunkPosition(bblock.getX(), bblock.getY(), bblock.getZ());
affectedBlockPositions.add(coords);
}
if (event.isCancelled()) {
wasCanceled = true;
return;
}
// CraftBukkit end
iterator = affectedBlockPositions.iterator();
while (iterator.hasNext()) {
chunkposition = (ChunkPosition) iterator.next();
i = chunkposition.chunkPosX;
j = chunkposition.chunkPosY;
k = chunkposition.chunkPosZ;
block = worldObj.getBlock(i, j, k);
if (p_77279_1_) {
double d0 = i + worldObj.rand.nextFloat();
double d1 = j + worldObj.rand.nextFloat();
double d2 = k + worldObj.rand.nextFloat();
double d3 = d0 - explosionX;
double d4 = d1 - explosionY;
double d5 = d2 - explosionZ;
double d6 = MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5);
d3 /= d6;
d4 /= d6;
d5 /= d6;
double d7 = 0.5D / (d6 / explosionSize + 0.1D);
d7 *= worldObj.rand.nextFloat() * worldObj.rand.nextFloat() + 0.3F;
d3 *= d7;
d4 *= d7;
d5 *= d7;
worldObj.spawnParticle("explode", (d0 + explosionX * 1.0D) / 2.0D, (d1 + explosionY * 1.0D) / 2.0D,
(d2 + explosionZ * 1.0D) / 2.0D, d3, d4, d5);
worldObj.spawnParticle("smoke", d0, d1, d2, d3, d4, d5);
}
if (block.getMaterial() != Material.air) {
if (block.canDropFromExplosion(this)) {
// CraftBukkit - add yield
block.dropBlockAsItemWithChance(worldObj, i, j, k, worldObj.getBlockMetadata(i, j, k),
event.getYield(), 0);
}
block.onBlockExploded(worldObj, i, j, k, this);
}
}
}
if (isFlaming) {
iterator = affectedBlockPositions.iterator();
while (iterator.hasNext()) {
chunkposition = (ChunkPosition) iterator.next();
i = chunkposition.chunkPosX;
j = chunkposition.chunkPosY;
k = chunkposition.chunkPosZ;
block = worldObj.getBlock(i, j, k);
Block block1 = worldObj.getBlock(i, j - 1, k);
if (block.getMaterial() == Material.air && block1.func_149730_j() && explosionRNG.nextInt(3) == 0) {
// CraftBukkit start - Ignition by explosion
if (!org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(worldObj, i, j, k, this)
.isCancelled()) {
worldObj.setBlock(i, j, k, Blocks.fire);
}
// CraftBukkit end
}
}
}
}
@SuppressWarnings("rawtypes")
public Map func_77277_b() {
return field_77288_k;
}
public EntityLivingBase getExplosivePlacedBy() {
return exploder == null ? null
: exploder instanceof EntityTNTPrimed ? ((EntityTNTPrimed) exploder).getTntPlacedBy()
: exploder instanceof EntityLivingBase ? (EntityLivingBase) exploder : null;
}
public boolean wasCanceled = false; // CraftBukkit
public boolean wasCanceled() {
return wasCanceled;
}
} | 33.912892 | 111 | 0.661666 |
902a8cf854ee24de07e77017ea30c62bdc730e03 | 174 | package org.apache.http.protocol;
import org.apache.http.HttpRequest;
public interface HttpRequestHandlerMapper {
HttpRequestHandler lookup(HttpRequest httpRequest);
}
| 21.75 | 55 | 0.821839 |
c5527cde11d4e6ad0b63723e935a2807716a9294 | 317 | package ru.mail.polis.service;
import javax.annotation.concurrent.ThreadSafe;
import java.nio.ByteBuffer;
import java.util.Set;
@ThreadSafe
public interface Topology<T> {
boolean isMe(T topology);
T me();
Set<T> primaryFor(ByteBuffer key, ReplicationFactor replicationFactor);
Set<T> all();
}
| 15.85 | 75 | 0.728707 |
09c0d9ee8800448588fd9616ff195308b4e80d9c | 1,340 | package CompilerRuntime;
import java.util.concurrent.Callable;
import org.coreasm.engine.absstorage.Element;
import org.coreasm.engine.absstorage.RuleBackgroundElement;
/**
* An interface representing a CoreASM Rule
* @author Markus Brenner
*
*/
public abstract class Rule extends Element implements Callable<RuleResult> {
protected Element agent;
protected java.util.ArrayList<CompilerRuntime.RuleParam> params;
protected CompilerRuntime.LocalStack localStack;
protected CompilerRuntime.EvalStack evalStack;
@Override
public String getBackground(){
return RuleBackgroundElement.RULE_BACKGROUND_NAME;
}
public void clearResults(){
localStack = new CompilerRuntime.LocalStack();
evalStack = new CompilerRuntime.EvalStack();
}
public void setAgent(Element a){
this.agent = a;
}
public Element getAgent(){
return this.agent;
}
public void initRule(java.util.ArrayList<CompilerRuntime.RuleParam> params, CompilerRuntime.LocalStack ls){
this.evalStack = new CompilerRuntime.EvalStack();
this.params = new java.util.ArrayList<CompilerRuntime.RuleParam>(params);
if(ls == null){
this.localStack = new CompilerRuntime.LocalStack();
}
else{
this.localStack = ls;
}
}
public Rule getUpdateResponsible(){
return this;
}
public abstract Rule getCopy();
public abstract int parameterCount();
}
| 26.27451 | 108 | 0.771642 |
3e18f8f9e5e3e9af872172be0b983b5f2ba93779 | 208 | package com.puc.sistemasdevendas.model.entities;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class PatchOrderRequest {
@NotNull
private OrderStatus orderStatus;
}
| 17.333333 | 48 | 0.793269 |
2073980bfcf5f581b0f0445dc4f2f8d8fae5949b | 2,293 | package com.vitco.app.low.engine;
import com.vitco.app.low.CubeIndexer;
import com.vitco.app.util.misc.IntegerTools;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.HashMap;
/**
* Proves fast read/write access to voxel in the world.
*/
public class Engine {
// ------------------------------
// static information for all engines (!!!)
// holds the different known voxel types
private static final HashMap<VoxelType, VoxelType> voxelTypes = new HashMap<VoxelType, VoxelType>();
// generate unique ids for the voxel
private static int uidCount = 1;
private static int generateUID() {
return uidCount++;
}
// -----------------------------
// holds the different known chunks
private final TIntObjectHashMap<Chunk> chunks = new TIntObjectHashMap<Chunk>();
// obtain the appropriate chunk (create a new one if it doesn't exist)
private Chunk getChunk(int[] xyz) {
int chunkId = CubeIndexer.getId(
IntegerTools.ifloordiv2(xyz[0], Chunk.CHUNK_SIZE),
IntegerTools.ifloordiv2(xyz[1], Chunk.CHUNK_SIZE),
IntegerTools.ifloordiv2(xyz[2], Chunk.CHUNK_SIZE));
Chunk result = chunks.get(chunkId);
if (result == null) {
result = new Chunk();
chunks.put(chunkId, result);
}
return result;
}
// delete a voxel
public boolean delete(int[][] xyzs) {
return false;
}
// set a voxel
public void set(int[][] xyzs, VoxelType newType) {
// get the voxel type if it already exists, or create a new one
VoxelType type = voxelTypes.get(newType);
if (type == null) {
voxelTypes.put(newType, newType);
newType.uId = generateUID();
type = newType;
}
for (int[] xyz : xyzs) {
// increase the used count
type.usedCount++;
// get the chunk this voxel lives in
Chunk chunk = getChunk(xyz);
// check if the voxel already exists (and decrease used count of the type if so)
// ...
// update the voxel in the chunk
// ...
}
}
// get a voxel
public VoxelType get(int[][] xyz) {
return null;
}
}
| 29.779221 | 104 | 0.576973 |
096d44644019fe05e584cfb82f986910dd93d889 | 999 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.socialsensor.framework.common.domain.alethiometer;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
*
* @author etzoannos
*/
public class AlexaScore {
@Expose
@SerializedName(value = "local")
private long localAlexaScore = 1000000L;
@Expose
@SerializedName(value = "international")
private long internationalAlexaScore = 1000000L;
public long getInternationalAlexaScore() {
return internationalAlexaScore;
}
public void setInternationalAlexaScore(long internationalAlexaScore) {
this.internationalAlexaScore = internationalAlexaScore;
}
public long getLocalAlexaScore() {
return localAlexaScore;
}
public void setLocalAlexaScore(long localAlexaScore) {
this.localAlexaScore = localAlexaScore;
}
}
| 24.975 | 75 | 0.691692 |
f6540494acd5ff938b604db09a7fbfb9377157fd | 121 | @ParametersAreNonnullByDefault
package org.predicode.predicator;
import javax.annotation.ParametersAreNonnullByDefault;
| 24.2 | 54 | 0.892562 |
b29cceb9916f7869791cc0f8b8975ae957c4667d | 3,731 | package jprelude.csv.base;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
/*
public class CsvFormatTest {
private enum Column {
COLUMN1, COLUMN2, COLUMN3;
}
//@Test
public void testApplyOn() throws IOException {
final Seq<Integer> records = Seq.range(0, 10);
CsvFormat.builder()
.columns(
"COLUMN1",
"COLUMN2",
"COLUMN3"
)
.autoTrim(true)
.escape(null)
.quoteMode(CsvQuoteMode.ALL)
.build()
.map(records.map(n ->
Arrays.asList("==> a" + n, "b" + n, "c" + n)))
.forEach(System.out::println);
}
//@Test
public void testOutputOfSeq() throws Throwable {
final Seq<Integer> records = Seq.range(0, 10);
CsvFormat.builder()
.columns(
"COLUMN1y",
"COLUMN2",
"COLUMN3"
)
.autoTrim(true)
.escape(null)
.recordSeparator(LineSeparator.SYSTEM)
.quoteMode(CsvQuoteMode.ALL)
.build()
.prepareExportTo(TextWriter.fromFile(Paths.get("/home/kenny/test.juhu")))
.apply(records.map(n ->
Arrays.asList(" a" + n, "b" + n, "c" + n)))
.ifErrorFail()
.ifSuccess(result -> System.out.println(String.format(">>>> Exported %d records successfully", result.getSourceRecordCount())));
}
//@Test
public void testInput() throws IOException {
final Seq<Integer> records = Seq.range(0, 10);
final String csvData =
"COLUMN1,COLUMN2,COLUMN3\n"
+ "a1,b1,c1\n"
+ "a2,b2,c2\n"
+ "a3,b3,c3\n";
CsvFormat.builder()
.columns(
"COLUMN2",
"COLUMN1",
"COLUMN3"
)
.autoTrim(true)
.escape(null)
.recordSeparator(LineSeparator.SYSTEM)
.quoteMode(CsvQuoteMode.ALL)
.build()
.parse(TextReader.fromString(csvData))
.forEach(rec -> System.out.println(rec.getIndex() + ": " + rec.get(Column.COLUMN1) + "-" + rec.get(Column.COLUMN2) + "-" + rec.get(Column.COLUMN3)));
}
@Test
public void testInput2() throws IOException {
final Seq<Integer> records = Seq.range(0, 10);
final String csvData =
"ART_NO,PRICE\n"
+ "a123,10.99\n"
+ "b234,2d0.90\n"
+ "c345,30x50\n";
CsvValidator validator = CsvValidator.builder()
.validateColumn(
"ART_NO",
"Must have a length of 4",
artNo -> !artNo.isNull())
.validateColumn(
"PRICE",
"Must be a positive floating number",
price -> price.isFloat())
.build();
CsvFormat.builder()
.columns(
"ART_NO",
"PRICE"
)
.autoTrim(true)
.escape(null)
.recordSeparator(LineSeparator.SYSTEM)
.quoteMode(CsvQuoteMode.ALL)
.build()
.parse(TextReader.fromString(csvData))
//.peek(validator.asConsumer())
.filter(validator.asFilter())
//.forEach(System.out::println);
.forEach(rec -> System.out.println(rec.getIndex() + ": " + rec.get("ART_NO") + "-" + rec.get("PRICE") ));
}
}
*/ | 31.352941 | 161 | 0.468239 |
5667f870ff47b41023ea404d2ea95b215e37836d | 222 | package com.vmware.vcd.domain;
import java.util.List;
@VcdMediaType("application/vnd.vmware.vcloud.query.records")
public class QueryResultVappsType extends ResourceType {
public List<QueryResultVappType> record;
}
| 22.2 | 60 | 0.801802 |
549e5bfb744937ea82b55f26f5a5f513bdb48e3a | 142 | package application;
import spms.Event;
public class Viewer extends Applicant{
public Event event;
public String ticketReceipt;
}
| 15.777778 | 39 | 0.753521 |
9f9a8eeda4a18bdec57f4e8a6d3ae69e35e9e07e | 3,413 | package org.yggdrasil.node.network.peer;
import org.yggdrasil.core.utils.DateTimeUtil;
import org.yggdrasil.node.network.messages.payloads.AddressPayload;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.ZonedDateTime;
import java.util.UUID;
public class PeerRecord implements Serializable {
private final UUID nodeIdentifier;
private ZonedDateTime timeStamp;
private final BigInteger supportedServices;
private final String ipAddress;
private final int port;
private PeerRecord(Builder builder) {
this.nodeIdentifier = builder.nodeIdentifier;
this.timeStamp = builder.timeStamp;
this.supportedServices = builder.supportedServices;
this.ipAddress = builder.ipAddress;
this.port = builder.port;
}
public UUID getNodeIdentifier() {
return nodeIdentifier;
}
public ZonedDateTime getTimeStamp() {
return timeStamp;
}
public BigInteger getSupportedServices() {
return supportedServices;
}
public String getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
public AddressPayload toAddressPayload() {
return AddressPayload.Builder.newBuilder()
.setNodeIdentifier(this.nodeIdentifier.toString().toCharArray())
.setTimestamp((int) this.timeStamp.toEpochSecond())
.setServices(this.supportedServices)
.setIpAddress(this.ipAddress.toCharArray())
.setPort(this.port)
.build();
}
public static class Builder {
private UUID nodeIdentifier;
private ZonedDateTime timeStamp;
private BigInteger supportedServices;
private String ipAddress;
private int port;
private Builder(){}
public static Builder newBuilder(){
return new Builder();
}
public Builder setNodeIdentifier(UUID nodeIdentifier) {
this.nodeIdentifier = nodeIdentifier;
return this;
}
public Builder setNodeIdentifier(String nodeIdentifier) {
this.nodeIdentifier = UUID.fromString(nodeIdentifier);
return this;
}
public Builder setTimeStamp(ZonedDateTime timeStamp) {
this.timeStamp = timeStamp;
return this;
}
public Builder setSupportedServices(BigInteger supportedServices) {
this.supportedServices = supportedServices;
return this;
}
public Builder setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public PeerRecord build() {
return new PeerRecord(this);
}
public PeerRecord buildFromAddressPayload(AddressPayload addressPayload) {
this.nodeIdentifier = UUID.fromString(String.valueOf(addressPayload.getNodeIdentifier()));
this.timeStamp = DateTimeUtil.fromMessageTimestamp(addressPayload.getTimestamp());
this.supportedServices = addressPayload.getServices();
this.ipAddress = String.valueOf(addressPayload.getIpAddress());
this.port = addressPayload.getPort();
return new PeerRecord(this);
}
}
}
| 29.678261 | 102 | 0.643422 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.