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
|
---|---|---|---|---|---|
0c24f67ee7001fce834ba6c607070ce783901da3 | 1,861 | package zhinan.liang.entitys;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import zhinan.liang.daos.OrderDao;
import java.util.List;
/**
* Created by liang on 2016/6/16.
* hibernate jpa 测试
*/
public class OrderHibernateTest {
private static Logger logger= LogManager.getLogger(OrderHibernateTest.class);
@Test
public void runtest() {
/**
* jpa hibernamte test
*/
try {
//通过Configuration获得一个SessionFactory对象
SessionFactory sf
= new Configuration().configure().buildSessionFactory();
//打开一个Session
Session session = sf.openSession();
//开始一个事务
Transaction tx = session.beginTransaction();
//创建一个Student对象
Orders order = new Orders();
order.setOrderId("0001");
order.setType(1);
order.setUnit(1);
//通过session的save()方法将Student对象保存到数据库中
session.save(order);
//提交事务
tx.commit();
//关闭会话
session.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private OrderDao orderDao;
@Test
public void jpaDaoTest() {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:application-context.xml");
orderDao = (OrderDao)ac.getBean("orderDao");
List<Orders> l=orderDao.orderList();
for(Orders o:l){
logger.info("logger-test"+o.getOrderId());
}
}
} | 29.539683 | 104 | 0.626008 |
e91c96a8ba17c792d537a382e17cbddeac095032 | 2,908 | /*
* 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
*
* 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.lodsve.boot.autoconfigure.swagger;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.util.List;
/**
* swagger配置.
*
* @author <a href="mailto:[email protected]">sunhao([email protected])</a>
*/
@ConfigurationProperties(prefix = "lodsve.swagger")
@Data
public class SwaggerProperties {
/**
* 接口版本号
*/
private String version;
/**
* 接口文档标题
*/
private String title;
/**
* 接口文档描述
*/
private String description;
/**
* 项目团队地址
*/
private String termsOfServiceUrl;
/**
* 项目使用的许可证
*/
private String license;
/**
* 许可证描述地址
*/
private String licenseUrl;
/**
* 项目联系人
*/
@NestedConfigurationProperty
private Contact contact;
/**
* 全局变量
*/
@NestedConfigurationProperty
private List<GlobalParameter> globalParameters;
/**
* 认证配置,目前仅支持header传参
*/
@NestedConfigurationProperty
private AuthConfig auth;
@Data
public static class Contact {
/**
* 项目联系人
*/
private String name;
/**
* 项目联系人主页
*/
private String url;
/**
* 项目联系人邮箱
*/
private String email;
}
@Data
public static class GlobalParameter {
/**
* 参数名称
*/
private String name;
/**
* 参数描述
*/
private String description;
/**
* 参数类型<p/>
* integer/string/boolean/number/object
*/
private String type;
/**
* 参数位置[query/header/path/cookie/form/formData/body]
*/
private String scope;
/**
* 是否必填
*/
private boolean required;
}
@Data
public static class AuthConfig {
/**
* 是否启用认证
*/
private boolean enabled;
/**
* 认证的key名称
*/
private String key;
}
}
| 23.079365 | 83 | 0.595942 |
587ad737033e228eb49c24a4eef281a448611553 | 4,017 | /*
* Copyright 2019 Pivotal, 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.spinnaker.kork.configserver;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.cloud.config.server.resource.NoSuchResourceException;
import org.springframework.cloud.config.server.resource.ResourceRepository;
import org.springframework.cloud.config.server.support.EnvironmentPropertySource;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
public class CloudConfigResourceService implements EnvironmentAware {
private static final String CONFIG_SERVER_RESOURCE_PREFIX = "configserver:";
private final ResourceRepository resourceRepository;
private final EnvironmentRepository environmentRepository;
@Value("${spring.application.name:application}")
private String applicationName = "application";
private String profiles;
public CloudConfigResourceService() {
this.resourceRepository = null;
this.environmentRepository = null;
}
public CloudConfigResourceService(
ResourceRepository resourceRepository, EnvironmentRepository environmentRepository) {
this.resourceRepository = resourceRepository;
this.environmentRepository = environmentRepository;
}
public String getLocalPath(String path) {
String contents = retrieveFromConfigServer(path);
return ConfigFileUtils.writeToTempFile(contents, getResourceName(path));
}
private String retrieveFromConfigServer(String path) {
if (resourceRepository == null || environmentRepository == null) {
throw new ConfigFileLoadingException(
"Config Server repository not configured for resource \"" + path + "\"");
}
try {
String fileName = getResourceName(path);
Resource resource =
this.resourceRepository.findOne(applicationName, profiles, null, fileName);
try (InputStream inputStream = resource.getInputStream()) {
Environment environment =
this.environmentRepository.findOne(applicationName, profiles, null);
String text = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
StandardEnvironment preparedEnvironment =
EnvironmentPropertySource.prepareEnvironment(environment);
return EnvironmentPropertySource.resolvePlaceholders(preparedEnvironment, text);
}
} catch (NoSuchResourceException e) {
throw new ConfigFileLoadingException(
"The resource \"" + path + "\" was not found in config server", e);
} catch (IOException e) {
throw new ConfigFileLoadingException(
"Exception reading config server resource \"" + path + "\"", e);
}
}
private String getResourceName(String path) {
return path.substring(CONFIG_SERVER_RESOURCE_PREFIX.length());
}
@Override
public void setEnvironment(org.springframework.core.env.Environment environment) {
profiles = StringUtils.join(environment.getActiveProfiles(), ",");
}
public static boolean isCloudConfigResource(String path) {
return path.startsWith(CONFIG_SERVER_RESOURCE_PREFIX);
}
}
| 39.382353 | 91 | 0.76475 |
2b3786d3ec7be59b7097abd896db01e5923491f3 | 9,946 | /*
* Copyright (C) 2020 Reincarnation Development Team
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*/
package reincarnation.decompiler.method;
import org.junit.jupiter.api.Test;
import reincarnation.TestCode;
import reincarnation.CodeVerifier;
/**
* @version 2018/10/23 15:31:37
*/
class MethodTest extends CodeVerifier {
@Test
void Basic() {
verify(new Basic());
}
/**
* @version 2018/10/23 15:32:19
*/
private static class Basic implements TestCode.Int {
@Override
public int run() {
return compute();
}
private int compute() {
return -10;
}
}
@Test
void Param() {
verify(new Param());
}
/**
* @version 2018/10/23 15:32:31
*/
private static class Param implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value);
}
private int compute(int value) {
return 100 + value;
}
}
@Test
void MultipleParams() {
verify(new MultipleParams());
}
/**
* @version 2018/10/23 15:32:40
*/
private static class MultipleParams implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value, value + 1);
}
private int compute(int first, int second) {
return first * second;
}
}
@Test
void ArrayParam() {
verify(new ArrayParam());
}
/**
* @version 2018/10/23 15:32:50
*/
private static class ArrayParam implements TestCode.IntParam {
@Override
public int run(int value) {
int[] ints = {value, value + 1, value + 2};
return compute(ints);
}
private int compute(int[] values) {
int i = 0;
for (int j = 0; j < values.length; j++) {
i += values[j];
}
return i;
}
}
@Test
void AssignLocalParam() {
verify(new AssignLocalParam());
}
/**
* @version 2018/10/23 15:32:58
*/
private static class AssignLocalParam implements TestCode.IntParam {
@Override
public int run(int value) {
int local = 0;
int result = compute(local = value);
return local + result;
}
private int compute(int value) {
return 100 + value;
}
}
@Test
void AssignFieldParam() {
verify(new AssignFieldParam());
}
/**
* @version 2018/10/23 15:33:05
*/
private static class AssignFieldParam implements TestCode.IntParam {
private int local;
@Override
public int run(int value) {
int result = compute(local = value);
return local + result;
}
private int compute(int value) {
return 100 + value;
}
}
@Test
void VariableParam() {
verify(new VariableParam());
}
/**
* @version 2018/10/23 15:33:10
*/
private static class VariableParam implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value, value + 1, value + 2);
}
private int compute(int... values) {
int i = 0;
for (int j = 0; j < values.length; j++) {
i += values[j];
}
return i;
}
}
@Test
void VariableParamWithBase() {
verify(new VariableParamWithBase());
}
/**
* @version 2018/10/23 15:33:14
*/
private static class VariableParamWithBase implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value, value + 1, value + 2);
}
private int compute(int base, int... values) {
int i = base * base;
for (int j = 0; j < values.length; j++) {
i += values[j];
}
return i;
}
}
@Test
void VariableParamWithBaseOnly() {
verify(new VariableParamWithBaseOnly());
}
/**
* @version 2018/10/23 15:33:19
*/
private static class VariableParamWithBaseOnly implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value);
}
private int compute(int base, int... values) {
int i = base * base;
for (int j = 0; j < values.length; j++) {
i += values[j];
}
return i;
}
}
@Test
void Nest() {
verify(new Nest());
}
/**
* @version 2018/10/23 15:33:24
*/
private static class Nest implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value, nest(value));
}
private int compute(int first, int second) {
return first * second;
}
private int nest(int value) {
return value + value;
}
}
@Test
void Overload() {
verify(new Overload());
}
/**
* @version 2018/10/23 15:33:29
*/
private static class Overload implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value);
}
private int compute(int value) {
return value * value;
}
private String compute(String value) {
return value.substring(1);
}
}
@Test
void ExtendPublic() {
verify(new ExtendPublic());
}
/**
* @version 2018/10/23 15:33:39
*/
private static class BasePublic {
public int compute() {
return 10;
}
}
/**
* @version 2018/10/23 15:33:36
*/
private static class ExtendPublic extends BasePublic implements TestCode.IntParam {
@Override
public int run(int value) {
return value + compute();
}
}
@Test
void ExtendProtected() {
verify(new ExtendProtected());
}
/**
* @version 2018/10/23 15:33:47
*/
private static class BaseProtected {
protected int compute() {
return 10;
}
}
/**
* @version 2018/10/23 15:33:50
*/
private static class ExtendProtected extends BaseProtected implements TestCode.IntParam {
@Override
public int run(int value) {
return value + compute();
}
}
@Test
void ExtendPackage() {
verify(new ExtendPackage());
}
/**
* @version 2018/10/23 15:33:54
*/
private static class BasePackage {
int compute() {
return 10;
}
}
/**
* @version 2018/10/23 15:35:06
*/
private static class ExtendPackage extends BasePackage implements TestCode.IntParam {
@Override
public int run(int value) {
return value + compute();
}
}
@Test
void Override() {
verify(new OverrideChild());
}
/**
* @version 2018/10/23 15:35:11
*/
private static class OverrideBase {
public int compute(int value) {
return value + 1;
}
}
/**
* @version 2018/10/23 15:35:14
*/
private static class OverrideChild extends OverrideBase implements TestCode.IntParam {
@Override
public int run(int value) {
return compute(value);
}
@Override
public int compute(int value) {
return value - 1;
}
}
@Test
void callOverriddenMethod() {
verify(new Child());
}
@Test
void callOverriddenMethodFromInstance() {
verify(new TestCode.IntParam() {
@Override
public int run(int param) {
Child child = new Child();
return child.compute(param) + ((Parent) child).compute(param) + ((Ancestor) child).compute(param);
}
});
}
/**
* @version 2018/10/26 15:44:41
*/
static class Ancestor {
public int compute(int value) {
return value + 1;
}
}
/**
* @version 2018/10/26 15:44:41
*/
static class Parent extends Ancestor {
@Override
public int compute(int value) {
return value + 10;
}
}
/**
* @version 2018/10/26 15:44:41
*/
static class Child extends Parent implements TestCode.IntParam {
@Override
public int compute(int value) {
return value + 100;
}
/**
* {@inheritDoc}
*/
@Override
public int run(int param) {
return compute(param) + super.compute(param) + ((Ancestor) this).compute(param);
}
}
/**
* @version 2018/10/23 15:35:40
*/
static class SuperChild extends Ancestor implements TestCode.IntParam {
@Override
public int run(int value) {
return this.compute(value) + super.compute(value);
}
@Override
public int compute(int value) {
return value - 1;
}
}
} | 21.389247 | 115 | 0.49075 |
314526c8695ef8c8238a622644f27627d3c048ec | 3,181 | package com.fshtank.sanbox.controller;
import com.fshtank.sanbox.exception.SanboxException;
import com.fshtank.sanbox.model.SanboxWebRequest;
import com.fshtank.sanbox.model.SanboxWebResponse;
import com.fshtank.sanbox.service.SbxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* Example REST resource controller.
*
* @author Rick Fisher ([email protected])
*/
@RestController
@RequestMapping("/sandbox")
public class SanboxController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(SanboxController.class);
@Autowired
SbxService sbxService;
@Autowired
private SanboxWebRequest sanboxWebRequest;
/**
* @return Collection of Collection<PbcOfertaVeiculo>
*/
@RequestMapping(value = "/demo/{locale}/{language}",
method = RequestMethod.GET,
produces = {"application/vnd.status.v1+json;version=1.0",
"application/vnd.status.v1+xml;version=1.0"}
)
public SanboxWebResponse getDemo(@PathVariable("locale") String locale,
@PathVariable("language") String language,
@RequestParam(value = "sampleId", required = false) Integer sampleId) {
sanboxWebRequest.setLocale(locale);
sanboxWebRequest.setLanguage(language);
sanboxWebRequest.setSampleId(sampleId);
SanboxWebResponse sanboxWebResponse = sbxService.doSomething(sanboxWebRequest);
return sanboxWebResponse;
}
/**
* @return Collection of Collection<PbcOfertaVeiculo>
*/
@RequestMapping(value = "/bitwise/{digit}",
method = RequestMethod.GET,
produces = {"application/vnd.status.v1+json;version=1.0",
"application/vnd.status.v1+xml;version=1.0"}
)
public SanboxWebResponse getShiftDemo(@PathVariable("digit") int digitInt,
@RequestParam(value = "direction", required = true) String shiftDirection,
@RequestParam(value = "shift", required = true) Integer shiftInt) {
sanboxWebRequest.setDigitToShift(digitInt);
sanboxWebRequest.setShiftOperator(shiftInt);
sanboxWebRequest.setShiftDirection(shiftDirection);
SanboxWebResponse sanboxWebResponse = sbxService.doShiftThing(sanboxWebRequest);
return sanboxWebResponse;
}
@RequestMapping(value = "alive",
method = RequestMethod.GET,
produces = {"application/vnd.currentoffers.v2+json;version=2.0",
"application/vnd.currentoffers.v2+xml;version=2.0"}
)
public String imAlive () { return "Pearl Jam: 'Im Alive!'";
}
}
| 35.344444 | 116 | 0.684376 |
b3519e1978a3f91f5e9195bd34985a3821db11b6 | 8,167 | /*
* Copyright © 2017 Mathieu Carbou ([email protected])
*
* 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.mycila.megatron.ehcache;
import com.mycila.megatron.ConfigurationException;
import com.mycila.megatron.DisoveringMegatronPlugins;
import com.mycila.megatron.MegatronApi;
import com.mycila.megatron.MegatronConfiguration;
import com.mycila.megatron.Utils;
import org.ehcache.Cache;
import org.ehcache.Status;
import org.ehcache.core.events.CacheManagerListener;
import org.ehcache.core.spi.service.CacheManagerProviderService;
import org.ehcache.core.spi.service.ExecutionService;
import org.ehcache.core.spi.store.InternalCacheManager;
import org.ehcache.core.spi.time.TimeSourceService;
import org.ehcache.impl.internal.util.ThreadFactoryUtil;
import org.ehcache.management.CollectorService;
import org.ehcache.management.ManagementRegistryService;
import org.ehcache.management.registry.DefaultCollectorService;
import org.ehcache.spi.service.Service;
import org.ehcache.spi.service.ServiceDependencies;
import org.ehcache.spi.service.ServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terracotta.management.model.call.Parameter;
import org.terracotta.management.model.cluster.Client;
import org.terracotta.management.model.cluster.ClientIdentifier;
import org.terracotta.management.model.context.Context;
import org.terracotta.management.model.notification.ContextualNotification;
import org.terracotta.management.model.stats.ContextualStatistics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
@ServiceDependencies({CacheManagerProviderService.class, ExecutionService.class, TimeSourceService.class, ManagementRegistryService.class})
public class DefaultMegatronService implements MegatronService, CacheManagerListener, CollectorService.Collector {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMegatronService.class);
private final MegatronServiceConfiguration configuration;
private volatile DisoveringMegatronPlugins plugins;
private volatile ManagementRegistryService managementRegistryService;
private volatile CollectorService collectorService;
private volatile InternalCacheManager cacheManager;
private volatile MegatronApi megatronApi;
private volatile String cacheManagerAlias;
private volatile Context context;
public DefaultMegatronService(MegatronServiceConfiguration configuration) {
this.configuration = configuration;
}
@Override
public MegatronConfiguration getConfiguration() {
return configuration;
}
@Override
public void start(ServiceProvider<Service> serviceProvider) {
this.managementRegistryService = serviceProvider.getService(ManagementRegistryService.class);
this.cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager();
this.collectorService = new DefaultCollectorService(this);
this.collectorService.start(serviceProvider);
context = managementRegistryService.getConfiguration().getContext()
.with(Client.KEY, ClientIdentifier.create("Ehcache:" + cacheManagerAlias, Utils.generateShortUUID()).getClientId());
cacheManagerAlias = context.get("cacheManagerName");
ExecutorService executorService = serviceProvider.getService(ExecutionService.class).getUnorderedExecutor("megatron-scheduler", new SynchronousQueue<>());
ScheduledExecutorService scheduledExecutorService = serviceProvider.getService(ExecutionService.class).getScheduledExecutor("megatron-task");
ThreadFactory threadFactory = ThreadFactoryUtil.threadFactory("megatron");
megatronApi = new EhcacheMegatronApi(cacheManagerAlias, executorService, scheduledExecutorService, threadFactory, configuration);
this.cacheManager.registerListener(this);
}
@Override
public void stop() {
if(collectorService != null) {
collectorService.stop();
}
if (plugins != null) {
plugins.close();
plugins = null;
managementRegistryService = null;
}
}
@Override
public void cacheAdded(String alias, Cache<?, ?> cache) {
}
@Override
public void cacheRemoved(String alias, Cache<?, ?> cache) {
}
@Override
public void stateTransition(Status from, Status to) {
// we are only interested when cache manager is initializing (but at the end of the initialization)
switch (to) {
case AVAILABLE: {
DisoveringMegatronPlugins megatronPlugins = createMegatronPlugins();
LOGGER.info("[{}] Initializing Megatron with config: {}", cacheManagerAlias, configuration);
try {
megatronPlugins.init(configuration);
} catch (ConfigurationException e) {
LOGGER.warn(e.getMessage(), e);
} finally {
this.plugins = megatronPlugins;
}
LOGGER.info("[{}] Collecting statistics each {}ms", cacheManagerAlias, configuration.getStatisticCollectorInterval());
try {
managementRegistryService.withCapability("StatisticCollectorCapability")
.call(
"startStatisticCollector",
Void.TYPE,
new Parameter(configuration.getStatisticCollectorInterval(), long.class.getName()),
new Parameter(TimeUnit.MILLISECONDS, TimeUnit.class.getName()))
.on(context)
.build()
.execute()
.getResult(context)
.getValue();
} catch (NoSuchElementException e) {
LOGGER.warn("[{}] Unable to start statistic collector: no statistic collector found in management registry.", cacheManagerAlias);
} catch (ExecutionException e) {
LOGGER.warn("[{}] Unable to start statistic collector: {}", cacheManagerAlias, e.getCause().getMessage(), e.getCause());
}
break;
}
case UNINITIALIZED: {
this.cacheManager.deregisterListener(this);
break;
}
case MAINTENANCE:
// in case we need management capabilities in maintenance mode
break;
default:
throw new AssertionError("Unsupported state: " + to);
}
}
private DisoveringMegatronPlugins createMegatronPlugins() {
DisoveringMegatronPlugins plugins = new DisoveringMegatronPlugins();
plugins.setApi(megatronApi);
return plugins;
}
@Override
public void onNotification(ContextualNotification notification) {
DisoveringMegatronPlugins plugins = this.plugins;
if (plugins != null && notification != null) {
LOGGER.trace("[{}] onNotification({})", cacheManagerAlias, notification.getType());
notification.setContext(context.with(notification.getContext()));
plugins.onNotifications(Collections.singletonList(notification));
}
}
@Override
public void onStatistics(Collection<ContextualStatistics> statistics) {
DisoveringMegatronPlugins plugins = this.plugins;
if (plugins != null && !statistics.isEmpty()) {
LOGGER.trace("[{}] onStatistics({})", cacheManagerAlias, statistics.size());
for (ContextualStatistics statistic : statistics) {
statistic.setContext(context.with(statistic.getContext()));
}
plugins.onStatistics(statistics instanceof List ? (List<ContextualStatistics>) statistics : new ArrayList<>(statistics));
}
}
}
| 40.231527 | 158 | 0.750092 |
2c91eb8c79031c097e9e76bc836c5b8e93a2fbfe | 2,331 | package com.fix.remote;
import com.fix.common.domain.configs.Platform;
import com.fix.common.utils.RemoteUrlUtils;
import com.fix.exceptions.PlatformNotFoundException;
import com.fix.exceptions.PlatformRegistryNotFoundException;
import com.fix.model.mappers.PlatformMapper;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class PlatformsRegistry {
private static final String APPLICATION_NAME = "FIX-AGENT";
@Autowired
private PlatformMapper platformMapper;
public List<Platform> getAllPlatforms() throws PlatformRegistryNotFoundException {
return this.getAllInstances().stream()
.map(instance -> this.platformMapper.mapToPlatform(instance))
.collect(Collectors.toList());
}
public InstanceInfo getPlatformInstanceInfo(Platform platform) throws PlatformRegistryNotFoundException {
String instanceId = platformMapper.mapToInstanceIntoId(platform);
Optional<InstanceInfo> instanceInfo = this.getAllInstances().stream()
.filter(instance -> instance.getInstanceId().equals(instanceId))
.findFirst();
if(!instanceInfo.isPresent()) throw new PlatformNotFoundException(platform.getName());
return instanceInfo.get();
}
public String getPlatformInstanceUrl(Platform platform) {
InstanceInfo instanceInfo = this.getPlatformInstanceInfo(platform);
return RemoteUrlUtils.createHttpUrl(instanceInfo.getIPAddr(), instanceInfo.getPort());
}
private List<InstanceInfo> getAllInstances() throws PlatformRegistryNotFoundException {
Optional<Application> application = EurekaServerContextHolder
.getInstance().getServerContext().getRegistry().getApplications().getRegisteredApplications().stream()
.filter(app -> app.getName().equals(APPLICATION_NAME)).findFirst();
if(!application.isPresent()) throw new PlatformRegistryNotFoundException(APPLICATION_NAME);
return application.get().getInstances();
}
}
| 36.421875 | 118 | 0.750322 |
af76c0c9c164b06e2869a10aff065fc30efba8e7 | 3,064 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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 com.atinternet.tracker;
import java.util.TreeMap;
/**
* Wrapper class to manage MediaPlayer instances
*/
public class MediaPlayers extends Helper {
final TreeMap<Integer, MediaPlayer> players;
MediaPlayers(Tracker tracker) {
super(tracker);
players = new TreeMap<>();
}
/**
* Add a player
*
* @return a new MediaPlayer instance
*/
public MediaPlayer add() {
int id = 0;
do {
id++;
} while (players.get(id) != null);
return add(id);
}
/**
* Add a player
*
* @param playerId player identifier
* @return a new MediaPlayer instance
*/
public MediaPlayer add(int playerId) {
if (players.get(playerId) == null) {
MediaPlayer player = new MediaPlayer(tracker).setPlayerId(playerId);
players.put(player.getPlayerId(), player);
return player;
} else {
Tool.executeCallback(tracker.getListener(), Tool.CallbackType.WARNING, "Player with the same id already exists");
return players.get(playerId);
}
}
/**
* Remove a MediaPlayer with all media attached
*
* @param playerId player identifier
*/
public void remove(int playerId) {
MediaPlayer player = players.remove(playerId);
if (player != null) {
player.Videos().removeAll();
player.LiveVideos().removeAll();
player.Audios().removeAll();
player.LiveAudios().removeAll();
player.Media().removeAll();
player.LiveMedia().removeAll();
}
}
/**
* Remove all players
*/
public void removeAll() {
while (!players.isEmpty()) {
remove(players.firstEntry().getValue().getPlayerId());
}
}
}
| 31.587629 | 141 | 0.657637 |
0b9b4061f8fc13ea7c741df888edd993d8608db8 | 11,501 | /*
* 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 oslp;
/**
*
* @author Artpicks
*/
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.awt.event.*;
import java.text.NumberFormat;
public class MonsterWindow extends javax.swing.JFrame {
/** Creates new form MonsterWindow */
private static final int MAX_X = 8; //Max buttons in a row
private JTextArea log_display;
private JRadioButton remove_mode;
private MonsterLog monster_log;
public MonsterWindow() {
initComponents();
}
public void makeDynamicWindow(MonsterLog monster){
this.setTitle("OSLP - "+monster.getName());
this.setLocationRelativeTo(null);
ImageIcon img = new ImageIcon(getClass().getResource("/oslp/images/Beer tankard.png"));
this.setIconImage(img.getImage());
monster_log = monster;
GridBagConstraints gbc = new GridBagConstraints();
int x = 0;
int y = 0;
log_display = new JTextArea();
log_display.setPreferredSize(new Dimension(400,400));
log_display.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
gbc.gridx = 50;
gbc.gridy = 0;
gbc.gridheight = 999;
gbc.fill = GridBagConstraints.VERTICAL;
getContentPane().add(log_display, gbc);
gbc = new GridBagConstraints();
JButton back_button = new JButton();
back_button.setText("Back");
back_button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
StartMenu menu = new StartMenu();
MonsterWindow.this.setVisible(false);
monster_log.saveMonsterXML();
menu.setVisible(rootPaneCheckingEnabled);
MonsterWindow.this.dispose();
}
});
gbc.gridx = MAX_X-1;
gbc.gridy = 99;
gbc.fill = GridBagConstraints.HORIZONTAL;
getContentPane().add(back_button, gbc);
JPanel remove_panel = new JPanel();
remove_panel.setLayout(new java.awt.GridBagLayout());
remove_panel.setPreferredSize(new Dimension(95, 50));
remove_mode = new JRadioButton();
remove_mode.setText("Remove");
remove_panel.add(remove_mode, new GridBagConstraints());
gbc.gridy = 98;
getContentPane().add(remove_panel, gbc);
JButton inc_killcount = new JButton();
inc_killcount.setText("Add Kill Count");
inc_killcount.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(!remove_mode.isSelected()){
monster_log.addKillcount(1);
}
else{
monster_log.subKillcount(1);
}
displayLog();
}
});
gbc.gridy = 97;
gbc.fill = GridBagConstraints.HORIZONTAL;
getContentPane().add(inc_killcount, gbc);
ArrayList<ItemDrop> local_drops = monster.getDrops();
for (ItemDrop local_drop : local_drops) {
addButton(local_drop, x, y);
x++;
if(x >= MAX_X){
x = 0;
y++;
}
}
displayLog();
pack();
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int xi = (int) ((dimension.getWidth() - this.getWidth()) / 2);
int yi = (int) ((dimension.getHeight() - this.getHeight()) / 2);
this.setLocation(xi, yi);
}
//Adds button with the item Icon, name and quantity with rairty color code
//at GridbagLayout(x,y).
private void addButton(ItemDrop itemdrop, int x, int y){
Font myFont = new Font("Helvetica", Font.BOLD, 8);
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel = new JPanel();
panel.setLayout(new java.awt.GridBagLayout());
panel.setPreferredSize(new Dimension(95,75));
JLabel itemname = new JLabel(itemdrop.getItem().getName());
itemname.setFont(myFont);
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(itemname, gbc);
JLabel quantity;
JButton button = new JButton();
System.out.println(itemdrop.getItem().getName());
button.setIcon(new ImageIcon(getClass().getResource(itemdrop.getItem().getIconPath())));
button.setPreferredSize(new Dimension(50,50));
if(itemdrop.getMinDrop() == itemdrop.getMaxDrop()){
quantity = new JLabel("Quantity: "+Integer.toString(itemdrop.getMinDrop()));
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(!remove_mode.isSelected()){
monster_log.getDrops().get(monster_log.getDrops().indexOf(itemdrop)).addQuantity(itemdrop.getMinDrop());
}
else{
monster_log.getDrops().get(monster_log.getDrops().indexOf(itemdrop)).subQuantity(itemdrop.getMinDrop());
}
displayLog();
}
});
}
else{
quantity = new JLabel("Quantity: Varies");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
try{
int quan = Integer.parseInt((String)JOptionPane.showInputDialog("Enter a Quantity: "));
if(!remove_mode.isSelected()){
monster_log.getDrops().get(monster_log.getDrops().indexOf(itemdrop)).addQuantity(quan);
}
else{
monster_log.getDrops().get(monster_log.getDrops().indexOf(itemdrop)).subQuantity(quan);
}
displayLog();
}
catch(NumberFormatException w){
}
}
});
}
quantity.setOpaque(true);
quantity.setBackground(getRarityColour(itemdrop.getRarity()));
quantity.setFont(myFont);
gbc.gridx = 0;
gbc.gridy = 2;
panel.add(quantity, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(button, gbc);
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.NONE;
getContentPane().add(panel, gbc);
}
private Color getRarityColour(String rarity){
String clean_rarity = rarity.replace(" ", "");
switch (clean_rarity) {
case "Always":
return new Color(175, 238, 238);
case "Common":
return new Color(86, 225, 86);
case "Uncommon":
return new Color(255, 237, 76);
case "Rare":
return new Color(255, 134, 60);
case "Veryrare":
return new Color(255, 98, 98);
default:
return new Color(200, 200, 200);
}
}
private void displayLog(){
log_display.setText("");
String newline = System.getProperty("line.separator");
log_display.append(monster_log.getName()+" Loot Log"+newline);
log_display.append(newline);
if(monster_log.getKillcount() > 0){
log_display.append("Kill Count: "+monster_log.getKillcount());
log_display.append(newline);
}
Map<String, ItemDrop> monsterLog = monster_log.getMap();
long running_total = 0;
for(String key : monsterLog.keySet()){
ItemDrop monsterItem = monsterLog.get(key);
if (monsterItem.getQuantity() > 0) {
long quantity = monsterItem.getQuantity();
long price = monsterItem.getItem().getPrice();
long total = quantity * price;
running_total = total+running_total;
String squantity = NumberFormat.getIntegerInstance().format(quantity);
String stotal = NumberFormat.getIntegerInstance().format(total);
log_display.append(squantity+" "+key+" = "+stotal+" gp"+newline);
}
}
String srt = NumberFormat.getIntegerInstance().format(running_total);
log_display.append(newline);
log_display.append("Total gp value of drops: "+srt);
}
/** 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
getContentPane().setLayout(new java.awt.GridBagLayout());
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
monster_log.saveMonsterXML();
System.exit(0);
}//GEN-LAST:event_formWindowClosing
/**
* @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(MonsterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MonsterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MonsterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MonsterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MonsterWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| 40.073171 | 124 | 0.590296 |
08b20921156ce94bcff52380ca5c32ece3607182 | 1,658 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.client;
/**
* The value for the durability of a BatchWriter or ConditionalWriter.
*
* @since 1.7.0
*/
public enum Durability {
// Note, the order of these is important; the "highest" Durability is used in group commits.
/**
* Use the durability as specified by the table or system configuration.
*/
DEFAULT,
/**
* Don't bother writing mutations to the write-ahead log.
*/
NONE,
/**
* Write mutations the the write-ahead log. Data may be sitting the the servers output buffers, and not replicated anywhere.
*/
LOG,
/**
* Write mutations to the write-ahead log, and ensure the data is stored on remote servers, but perhaps not on persistent storage.
*/
FLUSH,
/**
* Write mutations to the write-ahead log, and ensure the data is saved to persistent storage.
*/
SYNC
}
| 35.276596 | 132 | 0.721954 |
8f9d9d8631d4e9221c6494dd42e22acf9e7242b1 | 4,116 | /* Copyright (c) 2014 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Johnathan Garrett (LMN Solutions) - initial implementation
*/
package org.locationtech.geogig.api.plumbing.diff;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.common.base.Optional;
/**
*
*/
public class AttributeDiffTest extends Assert {
@Before
public void setUp() {
}
@Test
public void testAttributeDiffRemoved() {
Optional<Integer> oldValue = Optional.of(1);
Optional<Integer> newValue = null;
AttributeDiff diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.REMOVED);
assertTrue(diff.getOldValue().equals(oldValue));
assertFalse(diff.getNewValue().isPresent());
newValue = Optional.absent();
diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.REMOVED);
assertTrue(diff.getOldValue().equals(oldValue));
assertFalse(diff.getNewValue().isPresent());
}
@Test
public void testAttributeDiffAdded() {
Optional<Integer> oldValue = null;
Optional<Integer> newValue = Optional.of(1);
AttributeDiff diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.ADDED);
assertFalse(diff.getOldValue().isPresent());
assertTrue(diff.getNewValue().equals(newValue));
oldValue = Optional.absent();
diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.ADDED);
assertFalse(diff.getOldValue().isPresent());
assertTrue(diff.getNewValue().equals(newValue));
}
@Test
public void testAttributeDiffModified() {
Optional<Integer> oldValue = Optional.of(1);
Optional<Integer> newValue = Optional.of(2);
AttributeDiff diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.MODIFIED);
assertTrue(diff.getOldValue().equals(oldValue));
assertTrue(diff.getNewValue().equals(newValue));
}
@Test
public void testAttributeDiffNoChange() {
Optional<Integer> oldValue = Optional.of(1);
Optional<Integer> newValue = Optional.of(1);
AttributeDiff diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.NO_CHANGE);
assertTrue(diff.getOldValue().equals(oldValue));
assertTrue(diff.getNewValue().equals(newValue));
oldValue = Optional.absent();
newValue = Optional.absent();
diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.NO_CHANGE);
assertFalse(diff.getOldValue().isPresent());
assertFalse(diff.getNewValue().isPresent());
oldValue = null;
newValue = null;
diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.NO_CHANGE);
assertFalse(diff.getOldValue().isPresent());
assertFalse(diff.getNewValue().isPresent());
oldValue = null;
newValue = Optional.absent();
diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.NO_CHANGE);
assertFalse(diff.getOldValue().isPresent());
assertFalse(diff.getNewValue().isPresent());
oldValue = Optional.absent();
newValue = null;
diff = new GenericAttributeDiffImpl(oldValue, newValue);
assertTrue(diff.getType() == AttributeDiff.TYPE.NO_CHANGE);
assertFalse(diff.getOldValue().isPresent());
assertFalse(diff.getNewValue().isPresent());
}
}
| 38.111111 | 78 | 0.6793 |
d87aff940d6e09af7e4ed2b780e819d947d7cc94 | 1,743 | package com.ssp.ding;
import com.ssp.ding.message.ActionCardMessage;
import com.ssp.ding.message.DingMessage;
import com.ssp.ding.message.LinkMessage;
import com.ssp.ding.message.OAMessage;
import java.time.Duration;
/**
* 消息发送根据类型
* 接口文档:https://ding-doc.dingtalk.com/doc#/serverapi2/ye8tup
*
* @author: sunshaoping
* @date: Create by in 6:41 下午 2020/6/15
* @see DingMessageService
*/
public interface DingMessageSender<T> {
DingMediaService mediaService();
/**
* 发送消息
*
* @param message 消息对象
*/
T sendMessage(DingMessage message);
/**
* 文本消息
*
* @param content 消息内容,建议500字符以内
*/
T sendTextMessage(String content);
/**
* 图片消息
*
* @param mediaId 媒体文件id。可以通过媒体文件接口上传图片获取。建议宽600像素 x 400像素,宽高比3 : 2
* @see DingMediaService 上传媒体文件
*/
T sendImageMessage(String mediaId);
/**
* 语音消息
*
* @param mediaId 媒体文件id。2MB,播放长度不超过60s,AMR格式。
* <p>
* 可以通过媒体文件接口上传图片获取。
* @param duration 正整数,小于60,表示音频时长
* @see DingMediaService 上传媒体文件
*/
T sendVoiceMessage(String mediaId, Duration duration);
/**
* 文件消息
*
* @param mediaId 媒体文件id。引用的媒体文件最大10MB。可以通过媒体文件接口上传图片获取。
* @see DingMediaService 上传媒体文件
*/
T sendFileMessage(String mediaId);
/**
* 链接消息
*/
T sendLinkMessage(LinkMessage linkMessage);
/**
* OA消息
*/
T sendOAMessage(OAMessage message);
/**
* markdown消息
*
* @param title 首屏会话透出的展示内容
* @param text markdown格式的消息,建议500字符以内
*/
T sendMarkdownMessage(String title, String text);
/**
* 卡片消息
*/
T sendActionCardMessage(ActionCardMessage message);
}
| 19.58427 | 71 | 0.611589 |
117d6754f29fcee0a9229111b84ca1388d9bb810 | 5,011 | /*
* 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.facebook.presto.type;
import com.facebook.presto.annotation.UsedByGeneratedCode;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.SqlScalarFunction;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import io.airlift.slice.Slice;
import java.math.BigDecimal;
import java.math.BigInteger;
import static com.facebook.presto.metadata.FunctionKind.SCALAR;
import static com.facebook.presto.metadata.OperatorType.SATURATED_FLOOR_CAST;
import static com.facebook.presto.spi.type.Decimals.bigIntegerTenToNth;
import static com.facebook.presto.spi.type.Decimals.decodeUnscaledValue;
import static com.facebook.presto.spi.type.Decimals.encodeUnscaledValue;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static java.math.BigInteger.ONE;
import static java.math.RoundingMode.FLOOR;
public final class DecimalSaturatedFloorCasts
{
private DecimalSaturatedFloorCasts() {}
public static final SqlScalarFunction DECIMAL_TO_DECIMAL_SATURATED_FLOOR_CAST = SqlScalarFunction.builder(DecimalSaturatedFloorCasts.class)
.signature(Signature.builder()
.kind(SCALAR)
.operatorType(SATURATED_FLOOR_CAST)
.argumentTypes(parseTypeSignature("decimal(source_precision,source_scale)", ImmutableSet.of("source_precision", "source_scale")))
.returnType(parseTypeSignature("decimal(result_precision,result_scale)", ImmutableSet.of("result_precision", "result_scale")))
.build()
)
.implementation(b -> b
.methods("shortDecimalToShortDecimal", "shortDecimalToLongDecimal", "longDecimalToShortDecimal", "longDecimalToLongDecimal")
.withExtraParameters((context) -> {
int sourcePrecision = Ints.checkedCast(context.getLiteral("source_precision"));
int sourceScale = Ints.checkedCast(context.getLiteral("source_scale"));
int resultPrecision = Ints.checkedCast(context.getLiteral("result_precision"));
int resultScale = Ints.checkedCast(context.getLiteral("result_scale"));
return ImmutableList.of(sourcePrecision, sourceScale, resultPrecision, resultScale);
})
).build();
@UsedByGeneratedCode
public static long shortDecimalToShortDecimal(long value, int sourcePrecision, int sourceScale, int resultPrecision, int resultScale)
{
return bigintToBigintFloorSaturatedCast(BigInteger.valueOf(value), sourceScale, resultPrecision, resultScale).longValueExact();
}
@UsedByGeneratedCode
public static Slice shortDecimalToLongDecimal(long value, int sourcePrecision, int sourceScale, int resultPrecision, int resultScale)
{
return encodeUnscaledValue(bigintToBigintFloorSaturatedCast(BigInteger.valueOf(value), sourceScale, resultPrecision, resultScale));
}
@UsedByGeneratedCode
public static long longDecimalToShortDecimal(Slice value, int sourcePrecision, int sourceScale, int resultPrecision, int resultScale)
{
return bigintToBigintFloorSaturatedCast(decodeUnscaledValue(value), sourceScale, resultPrecision, resultScale).longValueExact();
}
@UsedByGeneratedCode
public static Slice longDecimalToLongDecimal(Slice value, int sourcePrecision, int sourceScale, int resultPrecision, int resultScale)
{
return encodeUnscaledValue(bigintToBigintFloorSaturatedCast(decodeUnscaledValue(value), sourceScale, resultPrecision, resultScale));
}
private static BigInteger bigintToBigintFloorSaturatedCast(BigInteger value, int sourceScale, int resultPrecision, int resultScale)
{
BigDecimal bigDecimal = new BigDecimal(value, sourceScale);
bigDecimal = bigDecimal.setScale(resultScale, FLOOR);
BigInteger unscaledValue = bigDecimal.unscaledValue();
BigInteger maxUnscaledValue = bigIntegerTenToNth(resultPrecision).subtract(ONE);
if (unscaledValue.compareTo(maxUnscaledValue) > 0) {
return maxUnscaledValue;
}
BigInteger minUnscaledValue = maxUnscaledValue.negate();
if (unscaledValue.compareTo(minUnscaledValue) < 0) {
return minUnscaledValue;
}
return unscaledValue;
}
}
| 50.616162 | 149 | 0.737777 |
20d82a9fc3b09089204279d9bfcd87fa626240a3 | 17,823 | package com.wecook.yelinaung.database.local;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.wecook.yelinaung.database.DrinkDbModel;
import com.wecook.yelinaung.database.DrinksContract;
import com.wecook.yelinaung.database.DrinksDatasource;
import com.wecook.yelinaung.models.Action;
import com.wecook.yelinaung.models.Ingredient;
import com.wecook.yelinaung.models.Occasion;
import com.wecook.yelinaung.models.ServedIn;
import com.wecook.yelinaung.models.Skill;
import com.wecook.yelinaung.models.Taste;
import com.wecook.yelinaung.models.Tool;
import com.wecook.yelinaung.util.Convertor;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.wecook.yelinaung.database.DrinksContract.DrinksEntry;
/**
* Created by user on 5/21/16.
*/
public class DrinkLocalDataSource implements DrinksDatasource {
private static DrinkLocalDataSource INSTANCE;
private Context context;
private final String[] PROJECTIONS = {
DrinksEntry.ID, DrinksEntry.NAME, DrinksEntry.VIDEO, DrinksEntry.COLOR, DrinksEntry.RATING,
DrinksEntry.BOOKMARK, DrinksEntry.DESCRIPTION, DrinksEntry.IS_HOT, DrinksEntry.IS_CARBONATED,
DrinksEntry.ISALCOHOLIC, DrinksEntry.TOOLS, DrinksEntry.INGREDIANTS, DrinksEntry.ACTIONS,
DrinksEntry.TASTES, DrinksEntry.SKILLS, DrinksEntry.SERVEIN, DrinksEntry.OCCASIONS
};
private DrinkLocalDataSource(@NonNull Context context) {
checkNotNull(context);
this.context = context;
}
public int convertBoolean(boolean condition) {
if (condition) {
return 1;
} else {
return 0;
}
}
public boolean convertInt(int i) {
if (i == 1) {
return true;
} else {
return false;
}
}
@Override public void saveBookmark(@NonNull DrinkDbModel drinkDbModel) {
checkNotNull(drinkDbModel);
ContentValues contentValues = new ContentValues();
if (drinkDbModel != null) {
contentValues.put(DrinksContract.DrinksEntry.ID, drinkDbModel.getId());
contentValues.put(DrinksContract.DrinksEntry.COLOR, drinkDbModel.getColor());
contentValues.put(DrinksContract.DrinksEntry.NAME, drinkDbModel.getName());
contentValues.put(DrinksContract.DrinksEntry.DESCRIPTION, drinkDbModel.getDescription());
contentValues.put(DrinksContract.DrinksEntry.VIDEO, drinkDbModel.getVideo());
contentValues.put(DrinksContract.DrinksEntry.RATING, drinkDbModel.getRating());
contentValues.put(DrinksEntry.IS_HOT, convertBoolean(drinkDbModel.getIsHot()));
contentValues.put(DrinksEntry.ISALCOHOLIC, convertBoolean(drinkDbModel.getIsAlcohol()));
contentValues.put(DrinksEntry.IS_CARBONATED, convertBoolean(drinkDbModel.getIsCarbon()));
contentValues.put(DrinksEntry.BOOKMARK, drinkDbModel.getBookmark());
context.getContentResolver()
.update(DrinksEntry.DRINKS_URI, contentValues,
DrinksEntry.ID + " = '" + drinkDbModel.getId() + "'", null);
}
//} else {
//context.getContentResolver()
// .insert(DrinksEntry.DRINKS_URI, contentValues, DrinksEntry.ID + "=" + drinkDbModel.getId(),
// null);
// }
}
public static DrinkLocalDataSource getInstance(@NonNull Context context) {
if (INSTANCE == null) {
INSTANCE = new DrinkLocalDataSource(context);
}
return INSTANCE;
}
@Override public void deleteAllDrinks() {
context.getContentResolver().delete(DrinksContract.DrinksEntry.DRINKS_URI, null, null);
}
@Override public void deleteDrink(@NonNull String drinkId) {
context.getContentResolver()
.delete(DrinksEntry.DRINKS_URI, DrinksEntry.ID + " == " + drinkId, PROJECTIONS);
}
@Override public List<DrinkDbModel> getBookmarks() {
List<DrinkDbModel> drinks = new ArrayList<DrinkDbModel>();
Cursor cursor = context.getContentResolver()
.query(DrinksEntry.DRINKS_URI, PROJECTIONS, DrinksEntry.BOOKMARK + " == 1", null, "");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
DrinkDbModel drinkDbModel = null;
String id = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.NAME));
String description =
cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.DESCRIPTION));
String video = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.VIDEO));
int rating = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.RATING));
int bookmark = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.BOOKMARK));
String color = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.COLOR));
boolean hot = convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_HOT)));
boolean alcohol =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.ISALCOHOLIC)));
boolean carbon =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_CARBONATED)));
String tools = cursor.getString(cursor.getColumnIndex(DrinksEntry.TOOLS));
List<Tool> list = Convertor.jsonToTools(tools);
String ingrediants = cursor.getString(cursor.getColumnIndex(DrinksEntry.INGREDIANTS));
List<Ingredient> ingredientList = Convertor.jsonToIngredients(ingrediants);
String actions = cursor.getString(cursor.getColumnIndex(DrinksEntry.ACTIONS));
List<Action> actionList = Convertor.jsonToActions(actions);
String tastes = cursor.getString(cursor.getColumnIndex(DrinksEntry.TASTES));
List<Taste> tasteList = Convertor.jsonToTastes(tastes);
String skills = cursor.getString(cursor.getColumnIndex(DrinksEntry.SKILLS));
Skill skill = Convertor.jsonToSkill(skills);
String serveIn = cursor.getString(cursor.getColumnIndex(DrinksEntry.SERVEIN));
ServedIn servedIn = Convertor.jsonToServeIn(serveIn);
String occasions = cursor.getString(cursor.getColumnIndex(DrinksEntry.OCCASIONS));
List<Occasion> occasionList = Convertor.jsonToOccasions(occasions);
drinkDbModel =
new DrinkDbModel(bookmark, color, description, id, name, rating, video, hot, alcohol,
carbon, list, ingredientList, actionList, tasteList, skill, servedIn, occasionList);
drinks.add(drinkDbModel);
}
if (cursor != null) {
cursor.close();
}
}
return drinks;
}
@Nullable @Override public DrinkDbModel getDrink(@NonNull String drinkId) {
Cursor cursor = context.getContentResolver()
.query(DrinksEntry.DRINKS_URI, PROJECTIONS, drinkId + " == " + DrinksEntry.ID,
new String[] {}, "asc");
DrinkDbModel drinkDbModel = null;
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
String id = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.NAME));
String description = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.DESCRIPTION));
String video = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.VIDEO));
int rating = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.RATING));
int bookmark = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.BOOKMARK));
String color = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.COLOR));
boolean hot = convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_HOT)));
boolean alcohol =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.ISALCOHOLIC)));
boolean carbon =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_CARBONATED)));
String tools = cursor.getString(cursor.getColumnIndex(DrinksEntry.TOOLS));
List<Tool> list = Convertor.jsonToTools(tools);
String ingrediants = cursor.getString(cursor.getColumnIndex(DrinksEntry.INGREDIANTS));
List<Ingredient> ingredientList = Convertor.jsonToIngredients(ingrediants);
String actions = cursor.getString(cursor.getColumnIndex(DrinksEntry.ACTIONS));
List<Action> actionList = Convertor.jsonToActions(actions);
String tastes = cursor.getString(cursor.getColumnIndex(DrinksEntry.TASTES));
List<Taste> tasteList = Convertor.jsonToTastes(tastes);
String skills = cursor.getString(cursor.getColumnIndex(DrinksEntry.SKILLS));
Skill skill = Convertor.jsonToSkill(skills);
String serveIn = cursor.getString(cursor.getColumnIndex(DrinksEntry.SERVEIN));
ServedIn servedIn = Convertor.jsonToServeIn(serveIn);
String occasions = cursor.getString(cursor.getColumnIndex(DrinksEntry.OCCASIONS));
List<Occasion> occasionList = Convertor.jsonToOccasions(occasions);
drinkDbModel =
new DrinkDbModel(bookmark, color, description, id, name, rating, video, hot, alcohol,
carbon, list, ingredientList, actionList, tasteList, skill, servedIn, occasionList);
}
if (cursor != null) {
cursor.close();
}
return drinkDbModel;
}
@Override public List<DrinkDbModel> getDrinks() {
List<DrinkDbModel> drinks = new ArrayList<DrinkDbModel>();
Cursor cursor =
context.getContentResolver().query(DrinksEntry.DRINKS_URI, PROJECTIONS, null, null, "");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
DrinkDbModel drinkDbModel = null;
String id = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.NAME));
String description =
cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.DESCRIPTION));
String video = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.VIDEO));
int rating = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.RATING));
int bookmark = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.BOOKMARK));
String color = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.COLOR));
boolean hot = convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_HOT)));
boolean alcohol =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.ISALCOHOLIC)));
boolean carbon =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_CARBONATED)));
String tools = cursor.getString(cursor.getColumnIndex(DrinksEntry.TOOLS));
List<Tool> list = Convertor.jsonToTools(tools);
String ingrediants = cursor.getString(cursor.getColumnIndex(DrinksEntry.INGREDIANTS));
List<Ingredient> ingredientList = Convertor.jsonToIngredients(ingrediants);
String actions = cursor.getString(cursor.getColumnIndex(DrinksEntry.ACTIONS));
List<Action> actionList = Convertor.jsonToActions(actions);
String tastes = cursor.getString(cursor.getColumnIndex(DrinksEntry.TASTES));
List<Taste> tasteList = Convertor.jsonToTastes(tastes);
String skills = cursor.getString(cursor.getColumnIndex(DrinksEntry.SKILLS));
Skill skill = Convertor.jsonToSkill(skills);
String serveIn = cursor.getString(cursor.getColumnIndex(DrinksEntry.SERVEIN));
ServedIn servedIn = Convertor.jsonToServeIn(serveIn);
String occasions = cursor.getString(cursor.getColumnIndex(DrinksEntry.OCCASIONS));
List<Occasion> occasionList = Convertor.jsonToOccasions(occasions);
drinkDbModel =
new DrinkDbModel(bookmark, color, description, id, name, rating, video, hot, alcohol,
carbon, list, ingredientList, actionList, tasteList, skill, servedIn, occasionList);
drinks.add(drinkDbModel);
}
if (cursor != null) {
cursor.close();
}
}
return drinks;
}
@Override public void refreshDrinks() {
}
@Override public List<DrinkDbModel> searchDrinks(String query) {
List<DrinkDbModel> drinks = new ArrayList<DrinkDbModel>();
Cursor cursor = context.getContentResolver()
.query(DrinksEntry.DRINKS_URI, PROJECTIONS, DrinksEntry.NAME + " like '%" + query + "%'",
new String[] {}, "");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
DrinkDbModel drinkDbModel = null;
String id = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.NAME));
String description =
cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.DESCRIPTION));
String video = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.VIDEO));
int rating = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.RATING));
int bookmark = cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.BOOKMARK));
String color = cursor.getString(cursor.getColumnIndexOrThrow(DrinksEntry.COLOR));
boolean hot = convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_HOT)));
boolean alcohol =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.ISALCOHOLIC)));
boolean carbon =
convertInt(cursor.getInt(cursor.getColumnIndexOrThrow(DrinksEntry.IS_CARBONATED)));
String tools = cursor.getString(cursor.getColumnIndex(DrinksEntry.TOOLS));
List<Tool> list = Convertor.jsonToTools(tools);
String ingrediants = cursor.getString(cursor.getColumnIndex(DrinksEntry.INGREDIANTS));
List<Ingredient> ingredientList = Convertor.jsonToIngredients(ingrediants);
String actions = cursor.getString(cursor.getColumnIndex(DrinksEntry.ACTIONS));
List<Action> actionList = Convertor.jsonToActions(actions);
String tastes = cursor.getString(cursor.getColumnIndex(DrinksEntry.TASTES));
List<Taste> tasteList = Convertor.jsonToTastes(tastes);
String skills = cursor.getString(cursor.getColumnIndex(DrinksEntry.SKILLS));
Skill skill = Convertor.jsonToSkill(skills);
String serveIn = cursor.getString(cursor.getColumnIndex(DrinksEntry.SERVEIN));
ServedIn servedIn = Convertor.jsonToServeIn(serveIn);
String occasions = cursor.getString(cursor.getColumnIndex(DrinksEntry.OCCASIONS));
List<Occasion> occasionList = Convertor.jsonToOccasions(occasions);
drinkDbModel =
new DrinkDbModel(bookmark, color, description, id, name, rating, video, hot, alcohol,
carbon, list, ingredientList, actionList, tasteList, skill, servedIn, occasionList);
drinks.add(drinkDbModel);
}
if (cursor != null) {
cursor.close();
}
}
return drinks;
}
//public static final String TOOLS = "tools";
//public static final String INGREDIANTS = "ingrediants";
//public static final String ACTIONS = "actions";
//public static final String TASTES = "tastes";
//public static final String SKILLS = "skills";
//public static final String SERVEIN = "serve_in";
//public static final String OCCASIONS = "occasions";
@Override public void saveDrinks(@NonNull DrinkDbModel drinkDbModel) {
checkNotNull(drinkDbModel);
ContentValues contentValues = new ContentValues();
if (drinkDbModel != null) {
contentValues.put(DrinksContract.DrinksEntry.ID, drinkDbModel.getId());
contentValues.put(DrinksContract.DrinksEntry.COLOR, drinkDbModel.getColor());
contentValues.put(DrinksContract.DrinksEntry.NAME, drinkDbModel.getName());
contentValues.put(DrinksContract.DrinksEntry.DESCRIPTION, drinkDbModel.getDescription());
contentValues.put(DrinksContract.DrinksEntry.VIDEO, drinkDbModel.getVideo());
contentValues.put(DrinksContract.DrinksEntry.RATING, drinkDbModel.getRating());
contentValues.put(DrinksEntry.IS_HOT, convertBoolean(drinkDbModel.getIsHot()));
contentValues.put(DrinksEntry.ISALCOHOLIC, convertBoolean(drinkDbModel.getIsAlcohol()));
contentValues.put(DrinksEntry.IS_CARBONATED, convertBoolean(drinkDbModel.getIsCarbon()));
String tools = Convertor.toolsToJson(drinkDbModel.getTools());
String ingrediants = Convertor.ingrediantsToJson(drinkDbModel.getIngredients());
String actions = Convertor.actionsToJson(drinkDbModel.getActions());
String tastes = Convertor.tastesToJson(drinkDbModel.getTastes());
String skills = Convertor.skillToJson(drinkDbModel.getSkills());
String serveIn = Convertor.serveInToJson(drinkDbModel.getServedIns());
String occasions = Convertor.occasionsToJson(drinkDbModel.getOccasions());
contentValues.put(DrinksEntry.TOOLS, tools);
contentValues.put(DrinksEntry.INGREDIANTS, ingrediants);
contentValues.put(DrinksEntry.ACTIONS, actions);
contentValues.put(DrinksEntry.TASTES, tastes);
contentValues.put(DrinksEntry.SKILLS, skills);
contentValues.put(DrinksEntry.SERVEIN, serveIn);
contentValues.put(DrinksEntry.OCCASIONS, occasions);
contentValues.put(DrinksEntry.BOOKMARK, 0);
if (context.getContentResolver()
.update(DrinksEntry.DRINKS_URI, contentValues,
DrinksEntry.ID + " = '" + drinkDbModel.getId() + "'", null) <= 0) {
context.getContentResolver().insert(DrinksContract.DrinksEntry.DRINKS_URI, contentValues);
}
}
//} else {
//context.getContentResolver()
// .insert(DrinksEntry.DRINKS_URI, contentValues, DrinksEntry.ID + "=" + drinkDbModel.getId(),
// null);
// }
}
}
| 47.528 | 101 | 0.723223 |
bdc1b182ddbfa613983c3ed11384cfd7caa1a7d8 | 456 | package katas.kyu6;
public class FactorsOfTriangleNumbers {
public static int calculate(int n) {
int i = 1;
for (; ; i++) {
int number = (i * (i + 1)) / 2;
int count = 0;
for (int j = 1; j <= Math.sqrt(number); j++) {
if (number % j == 0) if (number / j == j) count++;
else count = count + 2;
}
if (count > n) return number;
}
}
}
| 26.823529 | 66 | 0.425439 |
b1e8c62501a3bdce682b483471813f371e60727d | 12,029 | // The MIT License (MIT)
//
// Copyright (c) 2015 Kristian Stangeland
//
// 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.
////
// Please note that this is NOT an original copy, but has
// been unceremoniously butchered for use in HydraCore.
// - Justin
package com.lesserhydra.bukkitutil;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.lesserhydra.bukkitutil.nbt.NbtCompound;
import com.lesserhydra.bukkitutil.nbt.NbtFactory;
import com.lesserhydra.bukkitutil.nbt.NbtList;
import com.lesserhydra.bukkitutil.nbt.NbtType;
import com.lesserhydra.bukkitutil.volatilecode.MirrorItemStack;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
@SuppressWarnings({"WeakerAccess", "unused"})
public class Attributes {
public enum Slot {
ALL(""),
MAIN_HAND("mainhand"),
OFF_HAND("offhand"),
HEAD("head"),
CHEST("chest"),
LEGS("legs"),
FEET("feet");
private final String id;
Slot(String id) {
this.id = id;
}
public String getId() {
return id;
}
public static Slot fromId(String id) {
for (Slot slot : values()) {
if (slot.id.equals(id)) return slot;
}
throw new IllegalArgumentException("Unknown slot ID \"" + id + "\" detected.");
}
}
public enum Operation {
ADD_NUMBER(0),
MULTIPLY_PERCENTAGE(1),
ADD_PERCENTAGE(2);
private int id;
Operation(int id) {
this.id = id;
}
public int getId() {
return id;
}
public static Operation fromId(int id) {
// Linear scan is very fast for small N
for (Operation op : values()) {
if (op.getId() == id) {
return op;
}
}
throw new IllegalArgumentException("Corrupt operation ID " + id + " detected.");
}
}
public static class AttributeType {
private static ConcurrentMap<String, AttributeType> LOOKUP = Maps.newConcurrentMap();
public static final AttributeType GENERIC_MAX_HEALTH = new AttributeType("generic.maxHealth").register();
public static final AttributeType GENERIC_FOLLOW_RANGE = new AttributeType("generic.followRange").register();
public static final AttributeType GENERIC_ATTACK_DAMAGE = new AttributeType("generic.attackDamage").register();
public static final AttributeType GENERIC_MOVEMENT_SPEED = new AttributeType("generic.movementSpeed").register();
public static final AttributeType GENERIC_KNOCKBACK_RESISTANCE = new AttributeType("generic.knockbackResistance").register();
public static final AttributeType GENERIC_ARMOR = new AttributeType("generic.armor").register();
public static final AttributeType GENERIC_ARMOR_TOUGHNESS = new AttributeType("generic.armorToughness").register();
public static final AttributeType GENERIC_ATTACK_SPEED = new AttributeType("generic.attackSpeed").register();
public static final AttributeType GENERIC_LUCK = new AttributeType("generic.luck").register();
private final String minecraftId;
/**
* Construct a new attribute type.
* <p>
* Remember to {@link #register()} the type.
*
* @param minecraftId - the ID of the type.
*/
public AttributeType(String minecraftId) {
this.minecraftId = minecraftId;
}
/**
* Retrieve the associated minecraft ID.
*
* @return The associated ID.
*/
public String getMinecraftId() {
return minecraftId;
}
/**
* Register the type in the central registry.
*
* @return The registered type.
*/
// Constructors should have no side-effects!
public AttributeType register() {
AttributeType old = LOOKUP.putIfAbsent(minecraftId, this);
return old != null ? old : this;
}
/**
* Retrieve the attribute type associated with a given ID.
*
* @param minecraftId The ID to search for.
* @return The attribute type, or NULL if not found.
*/
public static AttributeType fromId(String minecraftId) {
return LOOKUP.get(minecraftId);
}
/**
* Retrieve every registered attribute type.
*
* @return Every type.
*/
public static Iterable<AttributeType> values() {
return LOOKUP.values();
}
}
public static class Attribute {
private NbtCompound data;
private Attribute(Builder builder) {
data = NbtFactory.makeCompound();
setAmount(builder.amount);
setOperation(builder.operation);
setSlot(builder.slot);
setAttributeType(builder.type);
setName(builder.name);
setUUID(builder.uuid);
}
private Attribute(NbtCompound data) {
this.data = data;
}
public double getAmount() {
return data.getDouble("Amount");
}
public void setAmount(double amount) {
data.set("Amount", amount);
}
public Operation getOperation() {
return Operation.fromId(data.getInteger("Operation"));
}
public void setOperation(@NotNull Operation operation) {
Preconditions.checkNotNull(operation, "operation cannot be NULL.");
data.set("Operation", operation.getId());
}
public Slot getSlot() {
return Slot.fromId(data.getString("Slot"));
}
public void setSlot(@NotNull Slot slot) {
Preconditions.checkNotNull(slot, "slot cannot be NULL.");
if (slot == Slot.ALL) data.remove("Slot");
else data.set("Slot", slot.getId());
}
public AttributeType getAttributeType() {
return AttributeType.fromId(data.getString("AttributeName"));
}
public void setAttributeType(@NotNull AttributeType type) {
Preconditions.checkNotNull(type, "type cannot be NULL.");
data.set("AttributeName", type.getMinecraftId());
}
public String getName() {
return data.getString("Name");
}
public void setName(@NotNull String name) {
Preconditions.checkNotNull(name, "name cannot be NULL.");
data.set("Name", name);
}
public UUID getUUID() {
return data.getUUID("UUID");
}
public void setUUID(@NotNull UUID id) {
Preconditions.checkNotNull(id, "id cannot be NULL.");
data.setUUID("UUID", id);
}
/**
* Construct a new attribute builder with a random UUID and default operation of adding numbers.
*
* @return The attribute builder.
*/
public static Builder newBuilder() {
return new Builder().uuid(UUID.randomUUID()).operation(Operation.ADD_NUMBER);
}
// Makes it easier to construct an attribute
public static class Builder {
private double amount;
private Operation operation = Operation.ADD_NUMBER;
private Slot slot = Slot.ALL;
private AttributeType type;
private String name;
private UUID uuid;
private Builder() {
// Don't make this accessible
}
public Builder amount(double amount) {
this.amount = amount;
return this;
}
public Builder operation(Operation operation) {
this.operation = operation;
return this;
}
public Builder slot(Slot slot) {
this.slot = slot;
return this;
}
public Builder type(AttributeType type) {
this.type = type;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder uuid(UUID uuid) {
this.uuid = uuid;
return this;
}
public Attribute build() {
return new Attribute(this);
}
}
}
// This may be modified
public MirrorItemStack stack;
private NbtList attributes;
public Attributes(ItemStack stack) {
// Create a CraftItemStack (under the hood)
this.stack = InventoryUtil.getMirrorItemStack(stack);
loadAttributes(false);
}
/**
* Load the NBT list from the TAG compound.
*
* @param createIfMissing - create the list if its missing.
*/
private void loadAttributes(boolean createIfMissing) {
if (this.attributes == null) {
NbtCompound nbt = InventoryUtil.getItemTag(this.stack, createIfMissing);
if (nbt != null) {
this.attributes = nbt.getList("AttributeModifiers", NbtType.COMPOUND, createIfMissing);
}
}
}
/**
* Remove the NBT list from the TAG compound.
*/
private void removeAttributes() {
NbtCompound nbt = InventoryUtil.getItemTag(this.stack, false);
if (nbt != null) nbt.remove("AttributeModifiers");
this.attributes = null;
}
/**
* Retrieve the modified item stack.
*
* @return The modified item stack.
*/
public MirrorItemStack getStack() {
return stack;
}
/**
* Retrieve the number of attributes.
*
* @return Number of attributes.
*/
public int size() {
return attributes != null ? attributes.size() : 0;
}
/**
* Add a new attribute to the list.
*
* @param attribute - the new attribute.
*/
public void add(Attribute attribute) {
Preconditions.checkNotNull(attribute.getName(), "must specify an attribute name.");
loadAttributes(true);
attributes.add(attribute.data);
}
/**
* Remove the first instance of the given attribute.
* <p>
* The attribute will be removed using its UUID.
*
* @param attribute - the attribute to remove.
* @return TRUE if the attribute was removed, FALSE otherwise.
*/
public boolean remove(Attribute attribute) {
if (attributes == null)
return false;
UUID uuid = attribute.getUUID();
for (Iterator<Attribute> it = values().iterator(); it.hasNext(); ) {
if (Objects.equal(it.next().getUUID(), uuid)) {
it.remove();
// Last removed attribute?
if (size() == 0) {
removeAttributes();
}
return true;
}
}
return false;
}
/**
* Remove every attribute.
*/
public void clear() {
removeAttributes();
}
/**
* Retrieve the attribute at a given index.
*
* @param index - the index to look up.
* @return The attribute at that index.
*/
public Attribute get(int index) {
if (size() == 0) throw new IllegalStateException("Attribute list is empty.");
return new Attribute(attributes.getCompound(index));
}
// We can't make Attributes itself iterable without splitting it up into separate classes
public Iterable<Attribute> values() {
return () -> {
// Handle the empty case
if (size() == 0) return Collections.<Attribute>emptyList().iterator();
return Iterators.transform(attributes.iterator(),
element -> new Attribute((NbtCompound) element));
};
}
}
| 29.482843 | 129 | 0.650012 |
8bd61ac07d135acbb4fd0f4b732c9ff167c16934 | 95,718 | package com.google.mu.util;
import static com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static com.google.mu.util.Substring.BEGINNING;
import static com.google.mu.util.Substring.END;
import static com.google.mu.util.Substring.after;
import static com.google.mu.util.Substring.before;
import static com.google.mu.util.Substring.first;
import static com.google.mu.util.Substring.last;
import static com.google.mu.util.Substring.prefix;
import static com.google.mu.util.Substring.spanningInOrder;
import static com.google.mu.util.Substring.suffix;
import static com.google.mu.util.Substring.upToIncluding;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Function;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import com.google.mu.util.Substring.Match;
import com.google.mu.util.stream.Joiner;
@RunWith(JUnit4.class)
public class SubstringTest {
@Test public void none() {
assertThat(Substring.NONE.in("foo")).isEmpty();
assertThat(Substring.NONE.removeFrom("foo")).isEqualTo("foo");
assertThat(Substring.NONE.replaceFrom("foo", "xyz")).isEqualTo("foo");
}
@Test public void none_toString() {
assertThat(Substring.NONE.toString()).isEqualTo("NONE");
}
@Test
public void beginning() {
assertThat(BEGINNING.from("foo")).hasValue("");
assertThat(BEGINNING.removeFrom("foo")).isEqualTo("foo");
assertThat(BEGINNING.replaceFrom("foo", "begin ")).isEqualTo("begin foo");
assertThat(BEGINNING.in("foo").get().before()).isEmpty();
assertThat(BEGINNING.in("foo").get().after()).isEqualTo("foo");
assertThat(BEGINNING.repeatedly().from("foo")).containsExactly("");
assertThat(BEGINNING.repeatedly().from("")).containsExactly("");
}
@Test
public void beginning_toString() {
assertThat(BEGINNING.toString()).isEqualTo("BEGINNING");
}
@Test
public void end() {
assertThat(END.from("foo")).hasValue("");
assertThat(END.removeFrom("foo")).isEqualTo("foo");
assertThat(END.replaceFrom("foo", " end")).isEqualTo("foo end");
assertThat(END.in("foo").get().before()).isEqualTo("foo");
assertThat(END.in("foo").get().after()).isEmpty();
assertThat(END.repeatedly().from("foo")).containsExactly("");
assertThat(END.repeatedly().from("")).containsExactly("");
}
@Test
public void end_toString() {
assertThat(END.toString()).isEqualTo("END");
}
@Test
public void prefix_toString() {
assertThat(prefix("foo").toString()).isEqualTo("foo");
}
@Test
public void prefix_length() {
assertThat(prefix("foo").length()).isEqualTo(3);
}
@Test
public void prefix_charAt() {
assertThat(prefix("foo").charAt(1)).isEqualTo('o');
}
@Test
public void prefix_subSequence() {
assertThat(prefix("foo").subSequence(1, 3)).isEqualTo("oo");
}
@Test
public void prefix_equals() {
new EqualsTester()
.addEqualityGroup(prefix("foo"), prefix("foo"))
.addEqualityGroup(prefix("bar"))
.addEqualityGroup(suffix("foo"))
.testEquals();
}
@Test
public void prefix_noMatch() {
assertThat(prefix("foo").in("notfoo")).isEmpty();
assertThat(prefix("foo").in("")).isEmpty();
assertThat(prefix("foo").repeatedly().match("notfoo")).isEmpty();
assertThat(prefix("foo").repeatedly().match("")).isEmpty();
}
@Test
public void prefix_matchesFullString() {
Optional<Substring.Match> match = prefix("foo").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(prefix("foo").repeatedly().from("foo")).containsExactly("foo");
}
@Test
public void prefix_matchesPrefix() {
Optional<Substring.Match> match = prefix("foo").in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("a")).isEqualTo("abar");
assertThat(match.get().replaceWith("at")).isEqualTo("atbar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(prefix("foo").repeatedly().from("foobar")).containsExactly("foo");
}
@Test
public void prefix_matchesPrefixFollowedByIdentialSubstring() {
Optional<Substring.Match> match = prefix("foo").in("foofoobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("foobar");
assertThat(match.get().remove()).isEqualTo("foobar");
assertThat(match.get().replaceWith("")).isEqualTo("foobar");
assertThat(match.get().replaceWith("a")).isEqualTo("afoobar");
assertThat(match.get().replaceWith("at")).isEqualTo("atfoobar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(prefix("foo").repeatedly().from("foofoobar"))
.containsExactly("foo", "foo");
assertThat(prefix("foo").repeatedly().from("foofoo"))
.containsExactly("foo", "foo");
}
@Test
public void prefix_emptyPrefix() {
Optional<Substring.Match> match = prefix("").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("foo");
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("b")).isEqualTo("bfoo");
assertThat(match.get().replaceWith("bar")).isEqualTo("barfoo");
assertThat(match.get().length()).isEqualTo(0);
assertThat(match.get().toString()).isEmpty();
assertThat(prefix("").repeatedly().from("foo")).containsExactly("");
}
@Test
public void charPrefix_toString() {
assertThat(prefix('a').toString()).isEqualTo("a");
}
@Test
public void charPrefix_noMatch() {
assertThat(prefix('f').in("notfoo")).isEmpty();
assertThat(prefix('f').in("")).isEmpty();
assertThat(prefix('f').repeatedly().match("")).isEmpty();
}
@Test
public void charPrefix_matchesFullString() {
Optional<Substring.Match> match = prefix('f').in("f");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(prefix('f').repeatedly().from("f")).containsExactly("f");
}
@Test
public void charPrefix_matchesPrefix() {
Optional<Substring.Match> match = prefix("f").in("fbar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("a")).isEqualTo("abar");
assertThat(match.get().replaceWith("at")).isEqualTo("atbar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(prefix('f').repeatedly().from("fbar")).containsExactly("f");
}
@Test
public void charPrefix_matchesPrefixFollowedByIdenticalChar() {
Optional<Substring.Match> match = prefix("f").in("ffar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("far");
assertThat(match.get().remove()).isEqualTo("far");
assertThat(match.get().replaceWith("")).isEqualTo("far");
assertThat(match.get().replaceWith("a")).isEqualTo("afar");
assertThat(match.get().replaceWith("at")).isEqualTo("atfar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(prefix('f').repeatedly().from("ffar")).containsExactly("f", "f");
}
@Test
public void prefix_addToIfAbsent_absent() {
assertThat(prefix("google3/").addToIfAbsent("java/com")).isEqualTo("google3/java/com");
}
@Test
public void prefix_addToIfAbsent_present() {
assertThat(prefix("google3/").addToIfAbsent("google3/java/com")).isEqualTo("google3/java/com");
}
@Test
public void prefix_addToIfAbsent_builderIsEmpty() {
StringBuilder builder = new StringBuilder();
assertThat(prefix("foo").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void prefix_addToIfAbsent_builderHasFewerChars() {
StringBuilder builder = new StringBuilder("oo");
assertThat(prefix("foo").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("foooo");
}
@Test
public void prefix_addToIfAbsent_builderHasSameNumberOfChars_absent() {
StringBuilder builder = new StringBuilder("ofo");
assertThat(prefix("obo").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("oboofo");
}
@Test
public void prefix_addToIfAbsent_builderHasSameNumberOfChars_present() {
StringBuilder builder = new StringBuilder("foo");
assertThat(prefix("foo").addToIfAbsent(builder)).isFalse();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void prefix_addToIfAbsent_builderHasMoreChars_absent() {
StringBuilder builder = new StringBuilder("booo");
assertThat(prefix("bob").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("bobbooo");
}
@Test
public void prefix_addToIfAbsent_builderHasMoreChars_present() {
StringBuilder builder = new StringBuilder("booo");
assertThat(prefix("boo").addToIfAbsent(builder)).isFalse();
assertThat(builder.toString()).isEqualTo("booo");
}
@Test
public void prefix_removeFrom_emptyIsRemovedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(prefix("").removeFrom(builder)).isTrue();
assertThat(builder.toString()).isEmpty();
}
@Test
public void prefix_removeFrom_emptyIsRemovedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(prefix("").removeFrom(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void prefix_removeFrom_nonEmptyIsNotRemovedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(prefix("foo").removeFrom(builder)).isFalse();
assertThat(builder.toString()).isEmpty();
}
@Test
public void prefix_removeFrom_nonEmptyIsNotRemovedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(prefix("fob").removeFrom(builder)).isFalse();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void prefix_removeFrom_nonEmptyIsRemovedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("food");
assertThat(prefix("foo").removeFrom(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("d");
}
@Test
public void prefix_replaceFrom_emptyIsReplacedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(prefix("").replaceFrom(builder, "head")).isTrue();
assertThat(builder.toString()).isEqualTo("head");
}
@Test
public void prefix_replaceFrom_emptyIsReplacedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(prefix("").replaceFrom(builder, "/")).isTrue();
assertThat(builder.toString()).isEqualTo("/foo");
}
@Test
public void prefix_replaceFrom_nonEmptyIsNotReplacedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(prefix("foo").replaceFrom(builder, "/")).isFalse();
assertThat(builder.toString()).isEmpty();
}
@Test
public void prefix_replaceFrom_nonEmptyIsNotReplacedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(prefix("fob").replaceFrom(builder, "bar")).isFalse();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void prefix_replaceFrom_nonEmptyIsReplacedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("food");
assertThat(prefix("foo").replaceFrom(builder, "$")).isTrue();
assertThat(builder.toString()).isEqualTo("$d");
}
@Test
public void prefix_emptyIsInEmptySource() {
assertThat(prefix("").isIn("")).isTrue();
assertThat(prefix("").isIn(new StringBuilder())).isTrue();
}
@Test
public void prefix_emptyIsInNonEmptySource() {
assertThat(prefix("").isIn("foo")).isTrue();
assertThat(prefix("").isIn(new StringBuilder().append("foo"))).isTrue();
}
@Test
public void prefix_nonEmptyNotInEmptySource() {
assertThat(prefix("foo").isIn("")).isFalse();
assertThat(prefix("foo").isIn(new StringBuilder())).isFalse();
}
@Test
public void prefix_sourceHasFewerCharacters() {
assertThat(prefix("foo").isIn("fo")).isFalse();
assertThat(prefix("foo").isIn(new StringBuilder().append("fo"))).isFalse();
}
@Test
public void prefix_sourceHasSameNumberOfCharacters_present() {
assertThat(prefix("foo").isIn("foo")).isTrue();
assertThat(prefix("foo").isIn(new StringBuilder().append("foo"))).isTrue();
}
@Test
public void prefix_sourceHasSameNumberOfCharacters_absent() {
assertThat(prefix("foo").isIn("fob")).isFalse();
assertThat(prefix("foo").isIn(new StringBuilder().append("fob"))).isFalse();
}
@Test
public void prefix_sourceHasMoreCharacters_present() {
assertThat(prefix("foo").isIn("food")).isTrue();
assertThat(prefix("foo").isIn(new StringBuilder().append("food"))).isTrue();
}
@Test
public void prefix_sourceHasMoreCharacters_absent() {
assertThat(prefix("foo").isIn("fit")).isFalse();
assertThat(prefix("foo").isIn(new StringBuilder().append("fit"))).isFalse();
}
@Test
public void suffix_toString() {
assertThat(suffix("foo").toString()).isEqualTo("foo");
}
@Test
public void suffix_length() {
assertThat(suffix("foo").length()).isEqualTo(3);
}
@Test
public void suffix_charAt() {
assertThat(suffix("foo").charAt(1)).isEqualTo('o');
}
@Test
public void suffix_subSequence() {
assertThat(suffix("foo").subSequence(1, 3)).isEqualTo("oo");
}
@Test
public void suffix_equals() {
new EqualsTester()
.addEqualityGroup(suffix("foo"), suffix("foo"))
.addEqualityGroup(suffix("bar"))
.addEqualityGroup(prefix("foo"))
.testEquals();
}
@Test
public void suffix_noMatch() {
assertThat(suffix("foo").in("foonot")).isEmpty();
assertThat(suffix("foo").in("")).isEmpty();
assertThat(suffix("foo").repeatedly().match("")).isEmpty();
}
@Test
public void suffix_matchesFullString() {
Optional<Substring.Match> match = suffix("foo").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(suffix("foo").repeatedly().from("foo")).containsExactly("foo");
}
@Test
public void suffix_matchesSuffix() {
Optional<Substring.Match> match = suffix("bar").in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("c")).isEqualTo("fooc");
assertThat(match.get().replaceWith("car")).isEqualTo("foocar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(suffix("bar").repeatedly().from("foobar")).containsExactly("bar");
}
@Test
public void suffix_matchesSuffixPrecededByIdenticalString() {
Optional<Substring.Match> match = suffix("bar").in("foobarbar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foobar");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foobar");
assertThat(match.get().replaceWith("")).isEqualTo("foobar");
assertThat(match.get().replaceWith("c")).isEqualTo("foobarc");
assertThat(match.get().replaceWith("car")).isEqualTo("foobarcar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(suffix("bar").repeatedly().from("foobarbar")).containsExactly("bar");
}
@Test
public void suffix_emptySuffix() {
Optional<Substring.Match> match = suffix("").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("b")).isEqualTo("foob");
assertThat(match.get().replaceWith("bar")).isEqualTo("foobar");
assertThat(match.get().length()).isEqualTo(0);
assertThat(match.get().toString()).isEmpty();
assertThat(suffix("").repeatedly().from("foo")).containsExactly("");
}
@Test
public void suffix_addToIfAbsent_absent() {
assertThat(suffix(".").addToIfAbsent("a")).isEqualTo("a.");
assertThat(suffix('.').addToIfAbsent("foo")).isEqualTo("foo.");
}
@Test
public void suffix_addToIfAbsent_present() {
assertThat(suffix(".").addToIfAbsent("a.")).isEqualTo("a.");
assertThat(suffix('.').addToIfAbsent("foo.")).isEqualTo("foo.");
}
@Test
public void suffix_addToIfAbsent_emptyIsNotAddedToEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(suffix("").addToIfAbsent(builder)).isFalse();
assertThat(builder.toString()).isEmpty();
}
@Test
public void suffix_addToIfAbsent_builderEmpty() {
StringBuilder builder = new StringBuilder();
assertThat(suffix(".").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo(".");
}
@Test
public void suffix_addToIfAbsent_builderHasFewerCharacters() {
StringBuilder builder = new StringBuilder("oo");
assertThat(suffix("foo").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("oofoo");
}
@Test
public void suffix_addToIfAbsent_builderHasSameNumberOfCharacters_absent() {
StringBuilder builder = new StringBuilder("foo");
assertThat(suffix("boo").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("fooboo");
}
@Test
public void suffix_addToIfAbsent_builderHasSameNumberOfCharacters_present() {
StringBuilder builder = new StringBuilder("foo");
assertThat(suffix("foo").addToIfAbsent(builder)).isFalse();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void suffix_addToIfAbsent_builderHasMoreCharacters_absent() {
StringBuilder builder = new StringBuilder("booo");
assertThat(suffix("foo").addToIfAbsent(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("booofoo");
}
@Test
public void suffix_addToIfAbsent_builderHasMoreCharacters_present() {
StringBuilder builder = new StringBuilder("booo");
assertThat(suffix("oo").addToIfAbsent(builder)).isFalse();
assertThat(builder.toString()).isEqualTo("booo");
}
@Test
public void suffix_removeFrom_emptyIsRemovedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(suffix("").removeFrom(builder)).isTrue();
assertThat(builder.toString()).isEmpty();
}
@Test
public void suffix_removeFrom_emptyIsRemovedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(suffix("").removeFrom(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void suffix_removeFrom_nonEmptyIsNotRemovedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(suffix("foo").removeFrom(builder)).isFalse();
assertThat(builder.toString()).isEmpty();
}
@Test
public void suffix_removeFrom_nonEmptyIsNotRemovedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(suffix("zoo").removeFrom(builder)).isFalse();
assertThat(builder.toString()).isEqualTo("foo");
}
@Test
public void suffix_removeFrom_nonEmptyIsRemovedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("boofoo");
assertThat(suffix("foo").removeFrom(builder)).isTrue();
assertThat(builder.toString()).isEqualTo("boo");
}
@Test
public void suffix_replaceFrom_emptyIsReplacedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(suffix("").replaceFrom(builder, ".")).isTrue();
assertThat(builder.toString()).isEqualTo(".");
}
@Test
public void suffix_replaceFrom_emptyIsReplacedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("foo");
assertThat(suffix("").replaceFrom(builder, ".")).isTrue();
assertThat(builder.toString()).isEqualTo("foo.");
}
@Test
public void suffix_replaceFrom_nonEmptyIsNotReplacedFromEmptyBuilder() {
StringBuilder builder = new StringBuilder();
assertThat(suffix("foo").replaceFrom(builder, ".")).isFalse();
assertThat(builder.toString()).isEmpty();
}
@Test
public void suffix_replaceFrom_nonEmptyIsReplacedFromNonEmptyBuilder() {
StringBuilder builder = new StringBuilder("boofoo");
assertThat(suffix("foo").replaceFrom(builder, "lala")).isTrue();
assertThat(builder.toString()).isEqualTo("boolala");
}
@Test
public void suffix_emptyIsInEmptySource() {
assertThat(suffix("").isIn("")).isTrue();
assertThat(suffix("").isIn(new StringBuilder())).isTrue();
}
@Test
public void suffix_emptyIsInNonEmptySource() {
assertThat(suffix("").isIn("foo")).isTrue();
assertThat(suffix("").isIn(new StringBuilder().append("foo"))).isTrue();
}
@Test
public void suffix_nonEmptyNotInEmptySource() {
assertThat(suffix("foo").isIn("")).isFalse();
assertThat(suffix("foo").isIn(new StringBuilder())).isFalse();
}
@Test
public void suffix_sourceHasFewerCharacters() {
assertThat(suffix("foo").isIn("fo")).isFalse();
assertThat(suffix("foo").isIn(new StringBuilder().append("fo"))).isFalse();
}
@Test
public void suffix_sourceHasSameNumberOfCharacters_present() {
assertThat(suffix("foo").isIn("foo")).isTrue();
assertThat(suffix("foo").isIn(new StringBuilder().append("foo"))).isTrue();
}
@Test
public void suffix_sourceHasSameNumberOfCharacters_absent() {
assertThat(suffix("foo").isIn("boo")).isFalse();
assertThat(suffix("foo").isIn(new StringBuilder().append("boo"))).isFalse();
}
@Test
public void suffix_sourceHasMoreCharacters_present() {
assertThat(suffix("foo").isIn("ffoo")).isTrue();
assertThat(suffix("foo").isIn(new StringBuilder().append("ffoo"))).isTrue();
}
@Test
public void suffix_sourceHasMoreCharacters_absent() {
assertThat(suffix("foo").isIn("zoo")).isFalse();
assertThat(suffix("foo").isIn(new StringBuilder().append("zoo"))).isFalse();
}
@Test
public void charSuffix_toString() {
assertThat(suffix('f').toString()).isEqualTo("f");
}
@Test
public void charSuffix_noMatch() {
assertThat(suffix('f').in("foo")).isEmpty();
assertThat(suffix('f').in("")).isEmpty();
assertThat(suffix('f').repeatedly().match("foo")).isEmpty();
assertThat(suffix('f').repeatedly().match("")).isEmpty();
}
@Test
public void charSuffix_matchesFullString() {
Optional<Substring.Match> match = suffix('f').in("f");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(suffix('f').repeatedly().from("f")).containsExactly("f");
}
@Test
public void charSuffix_matchesSuffix() {
Optional<Substring.Match> match = suffix('r').in("bar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("ba");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("ba");
assertThat(match.get().replaceWith("")).isEqualTo("ba");
assertThat(match.get().replaceWith("c")).isEqualTo("bac");
assertThat(match.get().replaceWith("car")).isEqualTo("bacar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("r");
assertThat(suffix('r').repeatedly().from("bar")).containsExactly("r");
}
@Test
public void charSuffix_matchesSuffixPrecededByIdenticalString() {
Optional<Substring.Match> match = suffix('r').in("barr");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("bar");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("c")).isEqualTo("barc");
assertThat(match.get().replaceWith("car")).isEqualTo("barcar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("r");
assertThat(suffix('r').repeatedly().from("barr")).containsExactly("r");
}
@Test
public void firstSnippet_toString() {
assertThat(first("foo").toString()).isEqualTo("first('foo')");
}
@Test
public void firstSnippet_noMatch() {
assertThat(first("foo").in("bar")).isEmpty();
assertThat(first("foo").in("")).isEmpty();
assertThat(first("foo").repeatedly().match("")).isEmpty();
}
@Test
public void firstSnippet_matchesFullString() {
Optional<Substring.Match> match = first("foo").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first("foo").repeatedly().from("foo")).containsExactly("foo");
}
@Test
public void firstSnippet_matchesPrefix() {
Optional<Substring.Match> match = first("foo").in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("c")).isEqualTo("cbar");
assertThat(match.get().replaceWith("car")).isEqualTo("carbar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first("foo").repeatedly().from("foobar")).containsExactly("foo");
}
@Test
public void firstSnippet_matchesPrefixFollowedByIdenticalString() {
Optional<Substring.Match> match = first("foo").in("foofoobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("foobar");
assertThat(match.get().remove()).isEqualTo("foobar");
assertThat(match.get().replaceWith("")).isEqualTo("foobar");
assertThat(match.get().replaceWith("c")).isEqualTo("cfoobar");
assertThat(match.get().replaceWith("car")).isEqualTo("carfoobar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first("foo").repeatedly().from("foofoobar"))
.containsExactly("foo", "foo");
assertThat(first("foo").repeatedly().from("foobarfoo"))
.containsExactly("foo", "foo");
}
@Test
public void firstSnippet_matchesSuffix() {
Optional<Substring.Match> match = first("bar").in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("c")).isEqualTo("fooc");
assertThat(match.get().replaceWith("car")).isEqualTo("foocar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first("bar").repeatedly().from("foobar")).containsExactly("bar");
}
@Test
public void firstSnippet_matchesInTheMiddle() {
Optional<Substring.Match> match = first("bar").in("foobarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEqualTo("baz");
assertThat(match.get().remove()).isEqualTo("foobaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foocarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first("bar").repeatedly().from("foobarbaz")).containsExactly("bar");
assertThat(first("bar").repeatedly().from("foobarbarbazbar"))
.containsExactly("bar", "bar", "bar");
}
@Test
public void firstSnippet_emptySnippet() {
Optional<Substring.Match> match = first("").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("foo");
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("b")).isEqualTo("bfoo");
assertThat(match.get().replaceWith("bar")).isEqualTo("barfoo");
assertThat(match.get().length()).isEqualTo(0);
assertThat(match.get().toString()).isEmpty();
assertThat(first("").repeatedly().from("foo")).containsExactly("");
}
@Test
public void firstSnippet_matchesFirstOccurrence() {
Optional<Substring.Match> match = first("bar").in("foobarbarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEqualTo("barbaz");
assertThat(match.get().remove()).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocbarbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foocarbarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first("bar").repeatedly().from("foobarbarbaz"))
.containsExactly("bar", "bar");
assertThat(first("bar").repeatedly().from("foobarcarbarbaz"))
.containsExactly("bar", "bar");
}
@Test
public void regex_toString() {
assertThat(first(Pattern.compile(".*x")).toString()).isEqualTo("first(\".*x\", 0)");
}
@Test
public void regex_noMatch() {
assertThat(first(Pattern.compile(".*x")).in("bar")).isEmpty();
assertThat(first(Pattern.compile(".*x")).in("")).isEmpty();
assertThat(first(Pattern.compile(".*x")).repeatedly().match("")).isEmpty();
}
@Test
public void regex_matchesFullString() {
Optional<Substring.Match> match = first(Pattern.compile(".*oo")).in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first(Pattern.compile(".*oo")).repeatedly().from("foo"))
.containsExactly("foo");
}
@Test
public void regex_matchesPrefix() {
Optional<Substring.Match> match = first(Pattern.compile(".*oo")).in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("c")).isEqualTo("cbar");
assertThat(match.get().replaceWith("car")).isEqualTo("carbar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first(Pattern.compile(".*oo")).repeatedly().from("foobar"))
.containsExactly("foo");
}
@Test
public void regex_matchesPrefixFollowedBySamePattern() {
Optional<Substring.Match> match = first(Pattern.compile(".oo")).in("foodoobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("doobar");
assertThat(match.get().remove()).isEqualTo("doobar");
assertThat(match.get().replaceWith("")).isEqualTo("doobar");
assertThat(match.get().replaceWith("c")).isEqualTo("cdoobar");
assertThat(match.get().replaceWith("car")).isEqualTo("cardoobar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first(Pattern.compile(".oo")).repeatedly().from("foodoobar"))
.containsExactly("foo", "doo");
}
@Test
public void regex_matchesPrefixWithStartingAnchor() {
Optional<Substring.Match> match = first(Pattern.compile("^.oo")).in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("c")).isEqualTo("cbar");
assertThat(match.get().replaceWith("car")).isEqualTo("carbar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first(Pattern.compile("^.oo")).repeatedly().from("foobar"))
.containsExactly("foo");
}
@Test
public void regex_matchesPrefixFollowedBySamePattern_withStartingAnchor() {
Optional<Substring.Match> match = first(Pattern.compile("^.oo")).in("foodoobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("doobar");
assertThat(match.get().remove()).isEqualTo("doobar");
assertThat(match.get().replaceWith("")).isEqualTo("doobar");
assertThat(match.get().replaceWith("c")).isEqualTo("cdoobar");
assertThat(match.get().replaceWith("car")).isEqualTo("cardoobar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(first(Pattern.compile("^.oo")).repeatedly().from("foodoobar"))
.containsExactly("foo", "doo");
}
@Test
public void regex_doesNotMatchPrefixDueToStartingAnchor() {
assertThat(first(Pattern.compile("^oob.")).in("foobar")).isEmpty();
assertThat(first(Pattern.compile("^oob")).repeatedly().match("foobar")).isEmpty();
}
@Test
public void regex_matchesSuffix() {
Optional<Substring.Match> match = first(Pattern.compile("b.*")).in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("c")).isEqualTo("fooc");
assertThat(match.get().replaceWith("car")).isEqualTo("foocar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first(Pattern.compile("b.*")).repeatedly().from("foobar"))
.containsExactly("bar");
}
@Test
public void regex_matchesSuffixWithEndingAnchor() {
Optional<Substring.Match> match = first(Pattern.compile("b.*$")).in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("c")).isEqualTo("fooc");
assertThat(match.get().replaceWith("car")).isEqualTo("foocar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first(Pattern.compile("b.*$")).repeatedly().from("foobar"))
.containsExactly("bar");
}
@Test
public void regex_doesNotMatchPostfixDueToEndingAnchor() {
assertThat(first(Pattern.compile("b.$")).in("foobar")).isEmpty();
assertThat(first(Pattern.compile("b.$")).repeatedly().match("foobar")).isEmpty();
}
@Test
public void regex_matchesInTheMiddle() {
Optional<Substring.Match> match = first(Pattern.compile(".ar")).in("foobarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEqualTo("baz");
assertThat(match.get().remove()).isEqualTo("foobaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foocarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first(Pattern.compile(".ar")).repeatedly().from("foobarbaz"))
.containsExactly("bar");
assertThat(first(Pattern.compile(".ar")).repeatedly().from("foobarzbarbaz"))
.containsExactly("bar", "bar");
assertThat(first(Pattern.compile(".ar")).repeatedly().from("foobarbazbar"))
.containsExactly("bar", "bar");
}
@Test
public void regex_emptySnippet() {
Optional<Substring.Match> match = first(Pattern.compile("")).in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("foo");
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("b")).isEqualTo("bfoo");
assertThat(match.get().replaceWith("bar")).isEqualTo("barfoo");
assertThat(match.get().length()).isEqualTo(0);
assertThat(match.get().toString()).isEmpty();
assertThat(first(Pattern.compile("")).repeatedly().from("foo"))
.containsExactly("");
assertThat(first(Pattern.compile("^")).repeatedly().from("foo"))
.containsExactly("");
assertThat(first(Pattern.compile("$")).repeatedly().from("foo"))
.containsExactly("");
}
@Test
public void regex_matchesFirstOccurrence() {
Optional<Substring.Match> match = first(Pattern.compile(".ar")).in("foobarbarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEqualTo("barbaz");
assertThat(match.get().remove()).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocbarbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foocarbarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first(Pattern.compile(".ar")).repeatedly().from("foobarbarbaz"))
.containsExactly("bar", "bar");
assertThat(first(Pattern.compile(".ar")).repeatedly().from("foobarbazbar"))
.containsExactly("bar", "bar");
}
@Test
public void regexGroup_noMatch() {
assertThat(first(Pattern.compile("(.*)x"), 1).in("bar")).isEmpty();
assertThat(first(Pattern.compile("(.*x)"), 1).in("bar")).isEmpty();
assertThat(first(Pattern.compile(".*(x)"), 1).in("bar")).isEmpty();
assertThat(first(Pattern.compile("(.*x)"), 1).in("")).isEmpty();
assertThat(first(Pattern.compile("(.*x)"), 1).repeatedly().match("")).isEmpty();
}
@Test
public void regexGroup_matchesFirstGroup() {
Optional<Substring.Match> match = first(Pattern.compile("(f.)b.*"), 1).in("fobar");
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("c")).isEqualTo("cbar");
assertThat(match.get().replaceWith("car")).isEqualTo("carbar");
assertThat(match.get().length()).isEqualTo(2);
assertThat(match.get().toString()).isEqualTo("fo");
assertThat(first(Pattern.compile("(f.)b.*"), 1).repeatedly().from("fobar"))
.containsExactly("fo");
assertThat(first(Pattern.compile("(f.)b.."), 1).repeatedly().from("fobar"))
.containsExactly("fo");
assertThat(first(Pattern.compile("(f.)b.."), 1).repeatedly().from("fobarfubaz"))
.containsExactly("fo", "fu");
}
@Test
public void regexGroup_matchesSecondGroup() {
Optional<Substring.Match> match = first(Pattern.compile("f(o.)(ba.)"), 2).in("foobarbaz");
assertThat(match.get().after()).isEqualTo("baz");
assertThat(match.get().remove()).isEqualTo("foobaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foocarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(first(Pattern.compile("f(o.)(ba.)"), 1).repeatedly().from("foobarbaz"))
.containsExactly("oo");
assertThat(
first(Pattern.compile("f(o.)(ba.);"), 1).repeatedly().match("foobar; foibaz;")
.map(Object::toString))
.containsExactly("oo", "oi");
}
@Test
public void regexGroup_group0() {
Optional<Substring.Match> match = first(Pattern.compile("f(o.)(ba.).*"), 0).in("foobarbaz");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("c")).isEqualTo("c");
assertThat(match.get().replaceWith("car")).isEqualTo("car");
assertThat(match.get().length()).isEqualTo(9);
assertThat(match.get().toString()).isEqualTo("foobarbaz");
assertThat(
first(Pattern.compile("f(o.)(ba.).*"), 0).repeatedly().from("foobarbaz"))
.containsExactly("foobarbaz");
}
@Test
public void regexGroup_negativeGroup() {
assertThrows(IndexOutOfBoundsException.class, () -> first(Pattern.compile("."), -1));
}
@Test
public void regexGroup_invalidGroupIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> first(Pattern.compile("f(o.)(ba.)"), 3));
}
@Test
public void lastSnippet_toString() {
assertThat(last("foo").toString()).isEqualTo("last('foo')");
}
@Test
public void lastSnippet_noMatch() {
assertThat(last("foo").in("bar")).isEmpty();
assertThat(last("foo").in("")).isEmpty();
assertThat(last("foo").repeatedly().match("bar")).isEmpty();
assertThat(last("f").repeatedly().match("")).isEmpty();
}
@Test
public void lastSnippet_matchesFullString() {
Optional<Substring.Match> match = last("foo").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(last("foo").repeatedly().from("foo")).containsExactly("foo");
}
@Test
public void lastSnippet_matchesPrefix() {
Optional<Substring.Match> match = last("foo").in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("bar");
assertThat(match.get().remove()).isEqualTo("bar");
assertThat(match.get().replaceWith("")).isEqualTo("bar");
assertThat(match.get().replaceWith("c")).isEqualTo("cbar");
assertThat(match.get().replaceWith("car")).isEqualTo("carbar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(last("foo").repeatedly().from("foobar")).containsExactly("foo");
}
@Test
public void lastSnippet_matchesPrefixPrecededBySamePattern() {
Optional<Substring.Match> match = last("foo").in("foobarfoobaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foobar");
assertThat(match.get().after()).isEqualTo("baz");
assertThat(match.get().remove()).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foobarcbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foobarcarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(last("foo").repeatedly().from("foobarfoobaz")).containsExactly("foo");
}
@Test
public void lastSnippet_matchesSuffix() {
Optional<Substring.Match> match = last("bar").in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("c")).isEqualTo("fooc");
assertThat(match.get().replaceWith("car")).isEqualTo("foocar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(last("bar").repeatedly().from("foobar")).containsExactly("bar");
}
@Test
public void lastSnippet_matchesInTheMiddle() {
Optional<Substring.Match> match = last("bar").in("foobarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEqualTo("baz");
assertThat(match.get().remove()).isEqualTo("foobaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foocarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(last("bar").repeatedly().from("foobarbaz")).containsExactly("bar");
}
@Test
public void lastSnippet_matchesLastOccurrence() {
Optional<Substring.Match> match = last("bar").in("foobarbarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foobar");
assertThat(match.get().after()).isEqualTo("baz");
assertThat(match.get().remove()).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("")).isEqualTo("foobarbaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foobarcbaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foobarcarbaz");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("bar");
assertThat(last("bar").repeatedly().from("barfoobarbaz")).containsExactly("bar");
}
@Test
public void lastSnippet_emptySnippet() {
Optional<Substring.Match> match = last("").in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("foo");
assertThat(match.get().replaceWith("")).isEqualTo("foo");
assertThat(match.get().replaceWith("b")).isEqualTo("foob");
assertThat(match.get().replaceWith("bar")).isEqualTo("foobar");
assertThat(match.get().length()).isEqualTo(0);
assertThat(match.get().toString()).isEmpty();
assertThat(last("").repeatedly().from("foo")).containsExactly("");
}
@Test
public void firstChar_toString() {
assertThat(first('f').toString()).isEqualTo("first('f')");
}
@Test
public void firstChar_noMatch() {
assertThat(first('f').in("bar")).isEmpty();
assertThat(first('f').in("")).isEmpty();
assertThat(first('f').repeatedly().match("bar")).isEmpty();
assertThat(first('f').repeatedly().match("")).isEmpty();
}
@Test
public void firstChar_matchesFullString() {
Optional<Substring.Match> match = first('f').in("f");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(first('f').repeatedly().from("f")).containsExactly("f");
}
@Test
public void firstChar_matchesPrefix() {
Optional<Substring.Match> match = first('f').in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("oobar");
assertThat(match.get().remove()).isEqualTo("oobar");
assertThat(match.get().replaceWith("")).isEqualTo("oobar");
assertThat(match.get().replaceWith("c")).isEqualTo("coobar");
assertThat(match.get().replaceWith("car")).isEqualTo("caroobar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(first('f').repeatedly().from("foobar")).containsExactly("f");
}
@Test
public void firstChar_matchesPrefixFollowedBySameChar() {
Optional<Substring.Match> match = first('f').in("foofar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("oofar");
assertThat(match.get().remove()).isEqualTo("oofar");
assertThat(match.get().replaceWith("")).isEqualTo("oofar");
assertThat(match.get().replaceWith("c")).isEqualTo("coofar");
assertThat(match.get().replaceWith("car")).isEqualTo("caroofar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(first('f').repeatedly().from("foofar")).containsExactly("f", "f");
}
@Test
public void firstChar_matchesSuffix() {
Optional<Substring.Match> match = first('r').in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("fooba");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("fooba");
assertThat(match.get().replaceWith("")).isEqualTo("fooba");
assertThat(match.get().replaceWith("c")).isEqualTo("foobac");
assertThat(match.get().replaceWith("car")).isEqualTo("foobacar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("r");
assertThat(first('r').repeatedly().from("foofar")).containsExactly("r");
}
@Test
public void firstChar_matchesFirstOccurrence() {
Optional<Substring.Match> match = first('b').in("foobarbarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foo");
assertThat(match.get().after()).isEqualTo("arbarbaz");
assertThat(match.get().remove()).isEqualTo("fooarbarbaz");
assertThat(match.get().replaceWith("")).isEqualTo("fooarbarbaz");
assertThat(match.get().replaceWith("c")).isEqualTo("foocarbarbaz");
assertThat(match.get().replaceWith("coo")).isEqualTo("foocooarbarbaz");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("b");
assertThat(first('b').repeatedly().from("foobarbarbaz"))
.containsExactly("b", "b", "b");
}
@Test
public void lastChar_noMatch() {
assertThat(last('f').in("bar")).isEmpty();
assertThat(last('f').in("")).isEmpty();
assertThat(last('f').repeatedly().match("bar")).isEmpty();
assertThat(last('f').repeatedly().match("")).isEmpty();
assertThat(last("f").in("bar")).isEmpty();
assertThat(last("f").in("")).isEmpty();
assertThat(last("f").repeatedly().match("bar")).isEmpty();
assertThat(last("f").repeatedly().match("")).isEmpty();
}
@Test
public void lastChar_matchesFullString() {
Optional<Substring.Match> match = last('f').in("f");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(last('f').repeatedly().from("f")).containsExactly("f");
assertThat(last("f").repeatedly().from("f")).containsExactly("f");
}
@Test
public void lastChar_matchesPrefix() {
Optional<Substring.Match> match = last('f').in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("oobar");
assertThat(match.get().remove()).isEqualTo("oobar");
assertThat(match.get().replaceWith("")).isEqualTo("oobar");
assertThat(match.get().replaceWith("c")).isEqualTo("coobar");
assertThat(match.get().replaceWith("car")).isEqualTo("caroobar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("f");
assertThat(last('f').repeatedly().from("foobar")).containsExactly("f");
assertThat(last("f").repeatedly().from("foobar")).containsExactly("f");
}
@Test
public void lastChar_matchesSuffix() {
Optional<Substring.Match> match = last('r').in("foobar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("fooba");
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEqualTo("fooba");
assertThat(match.get().replaceWith("")).isEqualTo("fooba");
assertThat(match.get().replaceWith("c")).isEqualTo("foobac");
assertThat(match.get().replaceWith("car")).isEqualTo("foobacar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("r");
assertThat(last('r').repeatedly().from("farbar")).containsExactly("r");
assertThat(last("r").repeatedly().from("farbar")).containsExactly("r");
}
@Test
public void lastChar_matchesLastOccurrence() {
Optional<Substring.Match> match = last('b').in("foobarbaz");
assertThat(match).isPresent();
assertThat(match.get().before()).isEqualTo("foobar");
assertThat(match.get().after()).isEqualTo("az");
assertThat(match.get().remove()).isEqualTo("foobaraz");
assertThat(match.get().replaceWith("")).isEqualTo("foobaraz");
assertThat(match.get().replaceWith("c")).isEqualTo("foobarcaz");
assertThat(match.get().replaceWith("car")).isEqualTo("foobarcaraz");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("b");
assertThat(last('b').repeatedly().from("farbarbaz")).containsExactly("b");
assertThat(last("b").repeatedly().from("farbarbaz")).containsExactly("b");
}
@Test
public void removeFrom_noMatch() {
assertThat(first('f').removeFrom("bar")).isEqualTo("bar");
}
@Test
public void removeFrom_match() {
assertThat(first('f').removeFrom("foo")).isEqualTo("oo");
}
@Test
public void removeAllFrom_noMatch() {
assertThat(first('f').repeatedly().removeAllFrom("bar")).isEqualTo("bar");
}
@Test
public void removeAllFrom_oneMatch() {
assertThat(first('f').repeatedly().removeAllFrom("foo")).isEqualTo("oo");
assertThat(first('f').repeatedly().removeAllFrom("afoo")).isEqualTo("aoo");
assertThat(first('f').repeatedly().removeAllFrom("oof")).isEqualTo("oo");
}
@Test
public void removeAllFrom_twoMatches() {
assertThat(first('o').repeatedly().removeAllFrom("foo")).isEqualTo("f");
assertThat(first('o').repeatedly().removeAllFrom("ofo")).isEqualTo("f");
assertThat(first('o').repeatedly().removeAllFrom("oof")).isEqualTo("f");
}
@Test
public void removeAllFrom_threeMatches() {
assertThat(first("x").repeatedly().removeAllFrom("fox x bxr")).isEqualTo("fo br");
assertThat(first("x").repeatedly().removeAllFrom("xaxbxxxcxx")).isEqualTo("abc");
}
@Test
public void replaceFrom_noMatch() {
assertThat(first('f').replaceFrom("bar", "")).isEqualTo("bar");
assertThat(first('f').replaceFrom("bar", "x")).isEqualTo("bar");
assertThat(first('f').replaceFrom("bar", "xyz")).isEqualTo("bar");
}
@Test
public void replaceFrom_match() {
assertThat(first('f').replaceFrom("foo", "")).isEqualTo("oo");
assertThat(first('f').replaceFrom("foo", "b")).isEqualTo("boo");
assertThat(first('f').replaceFrom("foo", "bar")).isEqualTo("baroo");
}
@Test
public void replaceAllFrom_noMatch() {
assertThat(first('f').repeatedly().replaceAllFrom("bar", (Function<? super Match, ? extends CharSequence>) m -> "x")).isEqualTo("bar");
assertThat(first('f').repeatedly().replaceAllFrom("bar", (Function<? super Match, ? extends CharSequence>) m -> "xyz")).isEqualTo("bar");
}
@Test
public void replaceAllFrom_oneMatch() {
assertThat(first('f').repeatedly().replaceAllFrom("foo", (Function<? super Match, ? extends CharSequence>) m -> "xx")).isEqualTo("xxoo");
assertThat(first('f').repeatedly().replaceAllFrom("afoo", (Function<? super Match, ? extends CharSequence>) m -> "xx")).isEqualTo("axxoo");
assertThat(first('f').repeatedly().replaceAllFrom("oof", (Function<? super Match, ? extends CharSequence>) m -> "xx")).isEqualTo("ooxx");
}
@Test
public void replaceAllFrom_twoMatches() {
assertThat(first('o').repeatedly().replaceAllFrom("foo", (Function<? super Match, ? extends CharSequence>) m -> "xx")).isEqualTo("fxxxx");
assertThat(first('o').repeatedly().replaceAllFrom("ofo", (Function<? super Match, ? extends CharSequence>) m -> "xx")).isEqualTo("xxfxx");
assertThat(first('o').repeatedly().replaceAllFrom("oof", (Function<? super Match, ? extends CharSequence>) m -> "xx")).isEqualTo("xxxxf");
}
@Test
public void replaceAllFrom_threeMatches() {
assertThat(first("x").repeatedly().replaceAllFrom("fox x bxr", (Function<? super Match, ? extends CharSequence>) m -> "yy")).isEqualTo("foyy yy byyr");
assertThat(first("x").repeatedly().replaceAllFrom("xaxbxxcx", (Function<? super Match, ? extends CharSequence>) m -> "yy")).isEqualTo("yyayybyyyycyy");
}
@Test
public void replaceAllFrom_placeholderSubstitution() {
Substring.Pattern placeholder = Substring.between(before(first('{')), after(first('}')));
ImmutableMap<String, String> dictionary = ImmutableMap.of("{key}", "foo", "{value}", "bar");
assertThat(
placeholder.repeatedly().replaceAllFrom("/{key}:{value}/", (Function<? super Match, ? extends CharSequence>) match -> dictionary.get(match.toString())))
.isEqualTo("/foo:bar/");
}
@Test
public void replaceAllFrom_replacementFunctionReturnsNull() {
Substring.Pattern placeholder = Substring.between(before(first('{')), after(first('}')));
NullPointerException thrown =
assertThrows(
NullPointerException.class,
() -> placeholder.repeatedly().replaceAllFrom("{unknown}", (Function<? super Match, ? extends CharSequence>) match -> null));
assertThat(thrown).hasMessageThat().contains("{unknown}");
}
@Test
public void replaceAllFrom_replacementFunctionReturnsNonEmpty() {
assertThat(Substring.first("var").repeatedly().replaceAllFrom("var=x", (Function<? super Match, ? extends CharSequence>) m -> "v")).isEqualTo("v=x");
}
@Test
public void delimit() {
assertThat(first(',').repeatedly().split("foo").map(Match::toString))
.containsExactly("foo");
assertThat(first(',').repeatedly().split("foo, bar").map(Match::toString))
.containsExactly("foo", " bar");
assertThat(first(',').repeatedly().split("foo,").map(Match::toString))
.containsExactly("foo", "");
assertThat(first(',').repeatedly().split("foo,bar, ").map(Match::toString))
.containsExactly("foo", "bar", " ");
}
@Test
public void repeatedly_split_beginning() {
assertThrows(IllegalStateException.class, () -> BEGINNING.repeatedly().split("foo"));
}
@Test
public void repeatedly_split_end() {
assertThrows(IllegalStateException.class, () -> END.repeatedly().split("foo"));
}
@Test
public void repeatedly_split_empty() {
assertThrows(IllegalStateException.class, () -> first("").repeatedly().split("foo"));
}
@Test
public void split_cannotSplit() {
assertThat(first('=').split("foo:bar")).isEqualTo(BiOptional.empty());
}
@Test
public void repeatedly_splitThenTrim_noMatch() {
assertThat(first("://").repeatedly().splitThenTrim("abc").map(Match::toString))
.containsExactly("abc");
}
@Test
public void repeatedly_splitThenTrim_match() {
assertThat(first("//").repeatedly().splitThenTrim("// foo").map(Match::toString))
.containsExactly("", "foo");
assertThat(first("/").repeatedly().splitThenTrim("foo / bar").map(Match::toString))
.containsExactly("foo", "bar");
assertThat(first("/").repeatedly().splitThenTrim(" foo/bar/").map(Match::toString))
.containsExactly("foo", "bar", "");
}
@Test
public void split_canSplit() {
assertThat(first('=').split(" foo=bar").map((String k, String v) -> k)).hasValue(" foo");
assertThat(first('=').split("foo=bar ").map((String k, String v) -> v)).hasValue("bar ");
assertThat(first('=').split(" foo=bar").map((String k, String v) -> k)).hasValue(" foo");
}
@Test
public void splitThenTrim_intoTwoParts_cannotSplit() {
assertThat(first('=').splitThenTrim("foo:bar")).isEqualTo(BiOptional.empty());
}
@Test
public void splitThenTrim_intoTwoParts_canSplit() {
assertThat(first('=').splitThenTrim(" foo =bar").map((String k, String v) -> k)).hasValue("foo");
assertThat(first('=').splitThenTrim("foo = bar ").map((String k, String v) -> v)).hasValue("bar");
}
@Test
public void matchAsCharSequence() {
CharSequence match = first(" >= ").in("foo >= bar").get();
assertThat(match.length()).isEqualTo(4);
assertThat(match.charAt(0)).isEqualTo(' ');
assertThat(match.charAt(1)).isEqualTo('>');
assertThat(match.charAt(2)).isEqualTo('=');
assertThat(match.charAt(3)).isEqualTo(' ');
assertThat(match.toString()).isEqualTo(" >= ");
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(4));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(5, 5));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 5));
}
@Test
public void matchAsCharSequence_subSequence() {
CharSequence match = first(" >= ").in("foo >= bar").get().subSequence(1, 3);
assertThat(match.length()).isEqualTo(2);
assertThat(match.charAt(0)).isEqualTo('>');
assertThat(match.charAt(1)).isEqualTo('=');
assertThat(match.toString()).isEqualTo(">=");
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(2));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(3, 3));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 3));
}
@Test
public void matchAsCharSequence_subSequence_emptyAtHead() {
CharSequence match = first(" >= ").in("foo >= bar").get().subSequence(0, 0);
assertThat(match.length()).isEqualTo(0);
assertThat(match.toString()).isEmpty();
assertThat(match.subSequence(0, 0).toString()).isEmpty();
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(0));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 1));
}
@Test
public void matchAsCharSequence_subSequence_emptyInTheMiddle() {
CharSequence match = first(">=").in("foo >= bar").get().subSequence(1, 1);
assertThat(match.length()).isEqualTo(0);
assertThat(match.toString()).isEmpty();
assertThat(match.subSequence(0, 0).toString()).isEmpty();
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(0));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 1));
}
@Test
public void matchAsCharSequence_subSequence_emptyAtEnd() {
CharSequence match = first(">=").in("foo >= bar").get().subSequence(2, 2);
assertThat(match.length()).isEqualTo(0);
assertThat(match.toString()).isEmpty();
assertThat(match.subSequence(0, 0).toString()).isEmpty();
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(0));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 1));
}
@Test
public void matchAsCharSequence_subSequence_full() {
CharSequence match = first(">=").in("foo >= bar").get().subSequence(0, 2);
assertThat(match.length()).isEqualTo(2);
assertThat(match.charAt(0)).isEqualTo('>');
assertThat(match.charAt(1)).isEqualTo('=');
assertThat(match.toString()).isEqualTo(">=");
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(2));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(3, 3));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 3));
}
@Test
public void matchAsCharSequence_subSequence_partial() {
CharSequence match = first(" >= ").in("foo >= bar").get().subSequence(1, 3);
assertThat(match.length()).isEqualTo(2);
assertThat(match.charAt(0)).isEqualTo('>');
assertThat(match.charAt(1)).isEqualTo('=');
assertThat(match.toString()).isEqualTo(">=");
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(2));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MAX_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.charAt(Integer.MIN_VALUE));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(3, 3));
assertThrows(IndexOutOfBoundsException.class, () -> match.subSequence(0, 3));
}
@Test
public void or_toString() {
assertThat(first("foo").or(last("bar")).toString()).isEqualTo("first('foo').or(last('bar'))");
}
@Test
public void or_firstMatcherMatches() {
Optional<Substring.Match> match = first('b').or(first("foo")).in("bar");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEqualTo("ar");
assertThat(match.get().remove()).isEqualTo("ar");
assertThat(match.get().replaceWith("")).isEqualTo("ar");
assertThat(match.get().replaceWith("c")).isEqualTo("car");
assertThat(match.get().replaceWith("coo")).isEqualTo("cooar");
assertThat(match.get().length()).isEqualTo(1);
assertThat(match.get().toString()).isEqualTo("b");
assertThat(first('b').or(first("foo")).repeatedly().from("barfoo"))
.containsExactly("b", "foo");
}
@Test
public void or_secondMatcherMatches() {
Optional<Substring.Match> match = first('b').or(first("foo")).in("foo");
assertThat(match).isPresent();
assertThat(match.get().before()).isEmpty();
assertThat(match.get().after()).isEmpty();
assertThat(match.get().remove()).isEmpty();
assertThat(match.get().replaceWith("")).isEmpty();
assertThat(match.get().replaceWith("b")).isEqualTo("b");
assertThat(match.get().replaceWith("bar")).isEqualTo("bar");
assertThat(match.get().length()).isEqualTo(3);
assertThat(match.get().toString()).isEqualTo("foo");
assertThat(prefix("bar").or(first("foo")).repeatedly().from("foobar"))
.containsExactly("foo", "bar");
}
@Test
public void or_neitherMatches() {
assertThat(first("bar").or(first("foo")).in("baz")).isEmpty();
assertThat(prefix("bar").or(first("foo")).repeatedly().match("baz")).isEmpty();
}
@Test
public void uptoIncluding_toString() {
assertThat(upToIncluding(last("bar")).toString()).isEqualTo("upToIncluding(last('bar'))");
}
@Test
public void upToIncluding_noMatch() {
assertThat(Substring.upToIncluding(first("://")).in("abc")).isEmpty();
assertThat(Substring.upToIncluding(first("://")).repeatedly().match("abc")).isEmpty();
}
@Test
public void upToIncluding_matchAtPrefix() {
assertThat(Substring.upToIncluding(first("://")).removeFrom("://foo")).isEqualTo("foo");
assertThat(Substring.upToIncluding(first("://")).repeatedly().from("://foo"))
.containsExactly("://");
}
@Test
public void upToIncluding_matchInTheMiddle() {
assertThat(Substring.upToIncluding(first("://")).removeFrom("http://foo")).isEqualTo("foo");
assertThat(Substring.upToIncluding(first("://")).repeatedly().from("http://foo"))
.containsExactly("http://");
}
@Test
public void upToIncluding_delimitedByRegexGroup() {
assertThat(
Substring.upToIncluding(first(Pattern.compile("(/.)/"))).repeatedly().match("foo/1/bar/2/")
.map(Object::toString))
.containsExactly("foo/1/", "bar/2/");
}
@Test
public void toEnd_toString() {
assertThat(first("//").toEnd().toString()).isEqualTo("first('//').toEnd()");
}
@Test
public void toEnd_noMatch() {
assertThat(first("//").toEnd().in("abc")).isEmpty();
assertThat(first("//").toEnd().repeatedly().match("abc")).isEmpty();
}
@Test
public void toEnd_matchAtSuffix() {
assertThat(first("//").toEnd().removeFrom("foo//")).isEqualTo("foo");
assertThat(first("//").toEnd().repeatedly().from("foo//")).containsExactly("//");
}
@Test
public void toEnd_matchInTheMiddle() {
assertThat(first("//").toEnd().removeFrom("foo // bar")).isEqualTo("foo ");
assertThat(first("//").toEnd().repeatedly().from("foo // bar //"))
.containsExactly("// bar //");
}
@Test
public void before_toString() {
assertThat(Substring.before(first("://")).toString()).isEqualTo("before(first('://'))");
}
@Test
public void before_noMatch() {
assertThat(Substring.before(first("://")).in("abc")).isEmpty();
assertThat(Substring.before(first("://")).repeatedly().match("abc")).isEmpty();
}
@Test
public void before_matchAtPrefix() {
assertThat(Substring.before(first("//")).removeFrom("//foo")).isEqualTo("//foo");
assertThat(Substring.before(first("//")).repeatedly().from("//foo"))
.containsExactly("");
assertThat(Substring.before(first("//")).repeatedly().from("//foo//"))
.containsExactly("", "foo");
}
@Test
public void before_matchInTheMiddle() {
assertThat(Substring.before(first("//")).removeFrom("http://foo")).isEqualTo("//foo");
assertThat(Substring.before(first("//")).repeatedly().from("http://foo"))
.containsExactly("http:");
}
@Test
public void delimite_noMatch() {
assertThat(first("://").repeatedly().split("abc").map(Match::toString))
.containsExactly("abc");
}
@Test
public void repeatedly_split_match() {
assertThat(first("//").repeatedly().split("//foo").map(Match::toString))
.containsExactly("", "foo");
assertThat(first("/").repeatedly().split("foo/bar").map(Match::toString))
.containsExactly("foo", "bar");
assertThat(first("/").repeatedly().split("foo/bar/").map(Match::toString))
.containsExactly("foo", "bar", "");
}
@Test
public void repeatedly_split_byBetweenPattern() {
Substring.Pattern comment = Substring.between(before(first("/*")), after(first("*/")));
assertThat(comment.repeatedly().split("a").map(Match::toString))
.containsExactly("a")
.inOrder();
assertThat(comment.repeatedly().split("a/*comment*/").map(Match::toString))
.containsExactly("a", "")
.inOrder();
assertThat(comment.repeatedly().split("a/*comment*/b").map(Match::toString))
.containsExactly("a", "b")
.inOrder();
assertThat(comment.repeatedly().split("a/*c1*/b/*c2*/").map(Match::toString))
.containsExactly("a", "b", "")
.inOrder();
assertThat(comment.repeatedly().split("a/*c1*/b/*c2*/c").map(Match::toString))
.containsExactly("a", "b", "c")
.inOrder();
}
@Test
public void after_toString() {
assertThat(Substring.after(first("//")).toString()).isEqualTo("after(first('//'))");
}
@Test
public void after_noMatch() {
assertThat(Substring.after(first("//")).in("abc")).isEmpty();
assertThat(Substring.after(first("//")).repeatedly().match("abc")).isEmpty();
}
@Test
public void after_matchAtSuffix() {
assertThat(Substring.after(last('.')).removeFrom("foo.")).isEqualTo("foo.");
assertThat(Substring.after(last('.')).repeatedly().from("foo."))
.containsExactly("");
}
@Test
public void after_matchInTheMiddle() {
assertThat(Substring.after(last('.')).removeFrom("foo. bar")).isEqualTo("foo.");
assertThat(Substring.after(last('.')).repeatedly().from("foo. bar"))
.containsExactly(" bar");
}
@Test
public void between_toString() {
assertThat(Substring.between(last("<"), last(">")).toString())
.isEqualTo("between(last('<'), last('>'))");
}
@Test
public void between_matchedInTheMiddle() {
Substring.Match match = Substring.between(last('<'), last('>')).in("foo<bar>baz").get();
assertThat(match.toString()).isEqualTo("bar");
assertThat(match.before()).isEqualTo("foo<");
assertThat(match.after()).isEqualTo(">baz");
assertThat(match.length()).isEqualTo(3);
assertThat(
Substring.between(last('<'), last('>')).repeatedly().from("foo<bar>baz"))
.containsExactly("bar");
assertThat(
Substring.between(first('/'), first('/')).repeatedly().from("/foo/bar/"))
.containsExactly("foo", "bar");
}
@Test
public void between_emptyMatch() {
Substring.Match match = Substring.between(last('<'), last('>')).in("foo<>baz").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEqualTo("foo<");
assertThat(match.after()).isEqualTo(">baz");
assertThat(match.length()).isEqualTo(0);
assertThat(Substring.between(last('<'), last('>')).repeatedly().from("foo<>baz"))
.containsExactly("");
}
@Test
public void between_consecutiveFirstChar() {
Substring.Pattern delimiter = first('-');
Substring.Match match = Substring.between(delimiter, delimiter).in("foo-bar-baz").get();
assertThat(match.toString()).isEqualTo("bar");
assertThat(match.before()).isEqualTo("foo-");
assertThat(match.after()).isEqualTo("-baz");
assertThat(match.length()).isEqualTo(3);
assertThat(
Substring.between(delimiter, delimiter).repeatedly().match("-foo-bar-baz-")
.map(Object::toString))
.containsExactly("foo", "bar", "baz");
}
@Test
public void between_matchedFully() {
Substring.Match match = Substring.between(last('<'), last('>')).in("<foo>").get();
assertThat(match.toString()).isEqualTo("foo");
assertThat(match.before()).isEqualTo("<");
assertThat(match.after()).isEqualTo(">");
assertThat(match.length()).isEqualTo(3);
assertThat(Substring.between(last('<'), last('>')).repeatedly().from("<foo>"))
.containsExactly("foo");
}
@Test
public void between_outerMatchesEmpty() {
Substring.Match match = Substring.between(first(""), last('.')).in("foo.").get();
assertThat(match.toString()).isEqualTo("foo");
assertThat(match.before()).isEmpty();
assertThat(match.after()).isEqualTo(".");
assertThat(match.length()).isEqualTo(3);
assertThat(Substring.between(first(""), last('.')).repeatedly().from("foo."))
.contains("foo");
}
@Test
public void between_innerMatchesEmpty() {
Substring.Match match = Substring.between(first(":"), last("")).in("hello:world").get();
assertThat(match.toString()).isEqualTo("world");
assertThat(match.before()).isEqualTo("hello:");
assertThat(match.after()).isEmpty();
assertThat(match.length()).isEqualTo(5);
assertThat(Substring.between(first(":"), last("")).repeatedly().from("foo:bar"))
.containsExactly("bar");
}
@Test
public void between_matchedLastOccurrence() {
Substring.Match match = Substring.between(last('<'), last('>')).in("<foo><bar> <baz>").get();
assertThat(match.toString()).isEqualTo("baz");
assertThat(match.before()).isEqualTo("<foo><bar> <");
assertThat(match.after()).isEqualTo(">");
assertThat(match.length()).isEqualTo(3);
assertThat(
Substring.between(last('<'), last('>')).repeatedly().match("<foo><bar> <baz>")
.map(Object::toString))
.containsExactly("baz");
}
@Test
public void between_matchedIncludingDelimiters() {
Substring.Match match =
Substring.between(before(last('<')), after(last('>'))).in("begin<foo>end").get();
assertThat(match.toString()).isEqualTo("<foo>");
assertThat(match.before()).isEqualTo("begin");
assertThat(match.after()).isEqualTo("end");
assertThat(match.length()).isEqualTo(5);
assertThat(
Substring.between(before(last('<')), after(last('>'))).repeatedly().match("begin<foo>end")
.map(Object::toString))
.containsExactly("<foo>");
}
@Test
public void between_nothingBetweenSameChar() {
assertThat(Substring.between(first('.'), first('.')).in(".")).isEmpty();
assertThat(Substring.between(first('.'), first('.')).repeatedly().match(".")).isEmpty();
}
@Test
public void between_matchesOpenButNotClose() {
assertThat(Substring.between(first('<'), first('>')).in("<foo")).isEmpty();
assertThat(Substring.between(first('<'), first('>')).repeatedly().match("<foo")).isEmpty();
}
@Test
public void between_matchesCloseButNotOpen() {
assertThat(Substring.between(first('<'), first('>')).in("foo>")).isEmpty();
assertThat(Substring.between(first('<'), first('>')).repeatedly().match("foo>")).isEmpty();
}
@Test
public void between_closeIsBeforeOpen() {
assertThat(Substring.between(first('<'), first('>')).in(">foo<")).isEmpty();
assertThat(Substring.between(first('<'), first('>')).repeatedly().match(">foo<")).isEmpty();
}
@Test
public void between_closeBeforeOpenDoesNotCount() {
Substring.Match match = Substring.between(first('<'), first('>')).in("><foo>").get();
assertThat(match.toString()).isEqualTo("foo");
assertThat(match.before()).isEqualTo("><");
assertThat(match.after()).isEqualTo(">");
assertThat(match.length()).isEqualTo(3);
assertThat(Substring.between(first('<'), first('>')).repeatedly().from("><foo>"))
.containsExactly("foo");
}
@Test
public void between_matchesNone() {
assertThat(Substring.between(first('<'), first('>')).in("foo")).isEmpty();
assertThat(Substring.between(first('<'), first('>')).repeatedly().match("foo")).isEmpty();
}
@Test
public void between_closeUsesBefore() {
Substring.Pattern open = first("-");
Substring.Pattern close = Substring.before(first("-"));
Substring.Match match = Substring.between(open, close).in("-foo-").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEqualTo("-");
assertThat(match.after()).isEqualTo("foo-");
assertThat(match.length()).isEqualTo(0);
assertThat(
Substring.between(first("-"), before(first("-"))).repeatedly().match("-foo-")
.map(Object::toString))
.containsExactly("");
}
@Test
public void between_closeUsesUpToIncluding() {
Substring.Match match =
Substring.between(first("-"), Substring.upToIncluding(first("-"))).in("-foo-").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEqualTo("-");
assertThat(match.after()).isEqualTo("foo-");
assertThat(match.length()).isEqualTo(0);
assertThat(
Substring.between(first("-"), upToIncluding(first("-"))).repeatedly().match("-foo-")
.map(Object::toString))
.containsExactly("");
}
@Test
public void between_closeUsesRegex() {
Substring.Match match =
Substring.between(first("-"), first(Pattern.compile(".*-"))).in("-foo-").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEqualTo("-");
assertThat(match.after()).isEqualTo("foo-");
assertThat(match.length()).isEqualTo(0);
assertThat(
Substring.between(first("-"), first(Pattern.compile(".*-")))
.repeatedly().from("-foo-"))
.containsExactly("");
}
@Test
public void between_closeOverlapsWithOpen() {
assertThat(Substring.between(first("abc"), last("cde")).in("abcde")).isEmpty();
assertThat(Substring.between(first("abc"), last("cde")).repeatedly().match("abcde")).isEmpty();
assertThat(Substring.between(first("abc"), last('c')).in("abc")).isEmpty();
assertThat(Substring.between(first("abc"), last('c')).repeatedly().match("abc")).isEmpty();
assertThat(Substring.between(first("abc"), suffix("cde")).in("abcde")).isEmpty();
assertThat(Substring.between(first("abc"), suffix("cde")).repeatedly().match("abcde")).isEmpty();
assertThat(Substring.between(first("abc"), suffix('c')).in("abc")).isEmpty();
assertThat(Substring.between(first("abc"), suffix('c')).repeatedly().match("abc")).isEmpty();
assertThat(Substring.between(first("abc"), prefix("a")).in("abc")).isEmpty();
assertThat(Substring.between(first("abc"), prefix("a")).repeatedly().match("abc")).isEmpty();
assertThat(Substring.between(first("abc"), prefix('a')).in("abc")).isEmpty();
assertThat(Substring.between(first("abc"), prefix('a')).repeatedly().match("abc")).isEmpty();
assertThat(Substring.between(first("abc"), first("a")).in("abc")).isEmpty();
assertThat(Substring.between(first("abc"), first("a")).repeatedly().match("abc")).isEmpty();
assertThat(Substring.between(first("abc"), first('a')).in("abc")).isEmpty();
assertThat(Substring.between(first("abc"), first('a')).repeatedly().match("abc")).isEmpty();
}
@Test
public void between_betweenInsideBetween() {
Substring.Match match =
Substring.between(first("-"), Substring.between(first(""), first('-'))).in("-foo-").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEqualTo("-");
assertThat(match.after()).isEqualTo("foo-");
assertThat(match.length()).isEqualTo(0);
assertThat(
Substring.between(first("-"), Substring.between(first(""), first('-'))).repeatedly().match("-foo-")
.map(Object::toString))
.containsExactly("");
}
@Test
public void between_emptyOpen() {
Substring.Match match = Substring.between(first(""), first(", ")).in("foo, bar").get();
assertThat(match.toString()).isEqualTo("foo");
assertThat(match.before()).isEmpty();
assertThat(match.after()).isEqualTo(", bar");
assertThat(match.length()).isEqualTo(3);
assertThat(
Substring.between(first(""), first(", ")).repeatedly().from("foo, bar"))
.contains("foo");
}
@Test
public void between_emptyClose() {
Substring.Match match = Substring.between(first(":"), first("")).in("foo:bar").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEqualTo("foo:");
assertThat(match.after()).isEqualTo("bar");
assertThat(match.length()).isEqualTo(0);
assertThat(Substring.between(first(":"), first("")).repeatedly().from("foo:bar"))
.containsExactly("");
}
@Test
public void between_emptyOpenAndClose() {
Substring.Match match = Substring.between(first(""), first("")).in("foo").get();
assertThat(match.toString()).isEmpty();
assertThat(match.before()).isEmpty();
assertThat(match.after()).isEqualTo("foo");
assertThat(match.length()).isEqualTo(0);
assertThat(Substring.between(first(""), first("")).repeatedly().from("foo"))
.containsExactly("");
}
@Test
public void between_openAndCloseAreEqual() {
Substring.Match match = Substring.between(first("-"), first("-")).in("foo-bar-baz-duh").get();
assertThat(match.toString()).isEqualTo("bar");
assertThat(match.before()).isEqualTo("foo-");
assertThat(match.after()).isEqualTo("-baz-duh");
assertThat(match.length()).isEqualTo(3);
assertThat(
Substring.between(first("-"), first("-")).repeatedly().match("foo-bar-baz-duh")
.map(Object::toString))
.containsExactly("bar", "baz");
}
@Test
public void between_closeBeforeOpenIgnored() {
Substring.Match match = Substring.between(first("<"), first(">")).in(">foo<bar>").get();
assertThat(match.toString()).isEqualTo("bar");
assertThat(match.before()).isEqualTo(">foo<");
assertThat(match.after()).isEqualTo(">");
assertThat(match.length()).isEqualTo(3);
assertThat(
Substring.between(first("<"), first(">")).repeatedly().match(">foo<bar>h<baz>")
.map(Object::toString))
.containsExactly("bar", "baz");
}
@Test
public void then_toString() {
assertThat(first("(").then(first("<")).toString())
.isEqualTo("first('(').then(first('<'))");
}
@Test
public void then_match() {
assertThat(first("GET").then(prefix(" ")).split("GET http").map(Joiner.on(':')::join))
.hasValue("GET:http");
}
@Test
public void then_firstPatternDoesNotMatch() {
assertThat(first("GET").then(prefix(" ")).split("GE http").map(Joiner.on(':')::join))
.isEmpty();
}
@Test
public void then_secondPatternDoesNotMatch() {
assertThat(first("GET").then(prefix(" ")).split("GET: http").map(Joiner.on('-')::join))
.isEmpty();
}
@Test
public void patternFrom_noMatch() {
assertThat(prefix("foo").from("")).isEmpty();
}
@Test
public void patternFrom_match() {
assertThat(Substring.first("bar").from("foo bar")).hasValue("bar");
}
@Test
public void matcher_index() {
assertThat(Substring.first("foo").in("foobar").get().index()).isEqualTo(0);
assertThat(Substring.first("bar").in("foobar").get().index()).isEqualTo(3);
assertThat(END.in("foobar").get().index()).isEqualTo(6);
}
@Test
public void matcher_fullString() {
assertThat(Substring.first("bar").in("foobar").get().fullString()).isEqualTo("foobar");
}
@Test
public void iterateIn_example() {
String text = "{x:1}, {y:2}, {z:3}";
ImmutableListMultimap<String, String> dictionary =
Substring.between(first('{'), first('}')).repeatedly().match(text)
.map(Object::toString)
.map(Substring.first(':')::in)
.map(Optional::get)
.collect(toImmutableListMultimap(Substring.Match::before, Substring.Match::after));
assertThat(dictionary).containsExactly("x", "1", "y", "2", "z", "3").inOrder();
}
@Test
public void iterateIn_getLinesPreservingNewLineChar() {
String text = "line1\nline2\nline3";
assertThat(Substring.upToIncluding(first('\n').or(END)).repeatedly().from(text))
.containsExactly("line1\n", "line2\n", "line3")
.inOrder();
}
@Test
public void iterateIn_characteristics() {
Spliterator<?> spliterator = BEGINNING.repeatedly().match("test").spliterator();
assertThat(spliterator.characteristics() & Spliterator.NONNULL).isEqualTo(Spliterator.NONNULL);
}
@Test
public void spanningInOrder_toString() {
assertThat(spanningInOrder("o", "bar").toString()).isEqualTo("spanningInOrder('o', 'bar')");
}
@Test
public void spanningInOrder_twoStops_matches() {
Substring.Match match = spanningInOrder("o", "bar").in("foo bar car").get();
assertThat(match.index()).isEqualTo(1);
assertThat(match.length()).isEqualTo(6);
}
@Test
public void spanningInOrder_twoStops_firstPatternDoesNotMatch() {
assertThat(spanningInOrder("o", "bar").in("far bar car")).isEmpty();
}
@Test
public void spanningInOrder_twoStops_secondPatternDoesNotMatch() {
assertThat(spanningInOrder("o", "bar").in("foo car")).isEmpty();
}
@Test
public void spanningInOrder_twoStops_firstStopIsEmpty() {
Substring.Match match = spanningInOrder("", "foo").in("foo bar car").get();
assertThat(match.index()).isEqualTo(0);
assertThat(match.length()).isEqualTo(3);
}
@Test
public void spanningInOrder_twoStops_secondStopIsEmpty() {
Substring.Match match = spanningInOrder("foo", "").in("foo bar car").get();
assertThat(match.index()).isEqualTo(0);
assertThat(match.length()).isEqualTo(3);
}
@Test
public void spanningInOrder_twoStops_bothStopsAreEmpty() {
Substring.Match match = spanningInOrder("", "").in("foo bar car").get();
assertThat(match.index()).isEqualTo(0);
assertThat(match.length()).isEqualTo(0);
}
@Test
public void spanningInOrder_threeStops_matches() {
Substring.Match match = spanningInOrder("o", "bar", "bar").in("foo barcarbar").get();
assertThat(match.toString()).isEqualTo("oo barcarbar");
assertThat(match.index()).isEqualTo(1);
assertThat(match.length()).isEqualTo(12);
}
@Test
public void spanningInOrder_threeStops_firstPatternDoesNotMatch() {
assertThat(spanningInOrder("o", "bar", "car").in("far bar car")).isEmpty();
}
@Test
public void spanningInOrder_threeStops_secondPatternDoesNotMatch() {
assertThat(spanningInOrder("o", "bar", "car").in("foo boo car")).isEmpty();
}
@Test
public void spanningInOrder_threeStops_thirdPatternDoesNotMatch() {
assertThat(spanningInOrder("o", "bar", "car").in("foo bar cat")).isEmpty();
}
@Test public void testRegexTopLevelGroups_noGroup() {
assertThat(Substring.topLevelGroups(java.util.regex.Pattern.compile("f+")).from("fff"))
.containsExactly("fff");
}
@Test public void testRegexTopLevelGroups_singleGroup() {
assertThat(Substring.topLevelGroups(java.util.regex.Pattern.compile("(f+)")).from("fffdef"))
.containsExactly("fff");
}
@Test public void testRegexTopLevelGroups_twoGroups() {
assertThat(Substring.topLevelGroups(java.util.regex.Pattern.compile("(f+)(cde)")).from("fffcde"))
.containsExactly("fff", "cde");
}
@Test public void testRegexTopLevelGroups_repeatingGroup() {
assertThat(Substring.topLevelGroups(java.util.regex.Pattern.compile("((f){2,3})")).from("fffcde"))
.containsExactly("fff");
}
@Test public void testRegexTopLevelGroups_nestedGroup() {
assertThat(Substring.topLevelGroups(java.util.regex.Pattern.compile("((ab)(cd)+)ef")).from("abcdcdef"))
.containsExactly("abcdcd");
}
@Test public void testRegexTopLevelGroups_noMatch() {
assertThat(Substring.topLevelGroups(java.util.regex.Pattern.compile("((ab)(cd)+)ef")).from("cdef"))
.isEmpty();
}
@Test
public void testNulls() throws Exception {
new NullPointerTester().testAllPublicInstanceMethods(prefix("foo").in("foobar").get());
newClassSanityTester().testNulls(Substring.class);
newClassSanityTester().forAllPublicStaticMethods(Substring.class).testNulls();
}
private static ClassSanityTester newClassSanityTester() {
return new ClassSanityTester()
.setDefault(int.class, 0)
.setDefault(String.class, "sub")
.setDefault(Pattern.class, Pattern.compile("testpattern"))
.setDefault(Substring.Pattern.class, prefix("foo"));
}
}
| 41.098325 | 164 | 0.668098 |
770cd73d6bafe373091dba200f714c0ed662c40a | 1,347 | import javax.swing.JFrame;
import javax.swing.JLabel;
// Creating JFrame object inside main()
public class P1 {
public static void main(String[] args) {
var myFrame = new JFrame();
var myMsg = new JLabel("Inside Main!");
myFrame.add(myMsg);
myFrame.setSize(500, 400);
myFrame.getContentPane().setBackground(new java.awt.Color(0, 202, 202));
myFrame.setLayout(new java.awt.GridBagLayout());
myFrame.setVisible(true);
new Message2();
new Message3();
}
}
// Creating JFrame object inside constructor
class Message2 {
Message2() {
var myFrame = new JFrame();
var myMsg = new JLabel("Inside constructor");
myFrame.add(myMsg);
myFrame.setSize(500, 400);
myFrame.getContentPane().setBackground(new java.awt.Color(0, 202, 202));
myFrame.setLayout(new java.awt.GridBagLayout());
myFrame.setVisible(true);
}
}
// Inheriting JFrame class
class Message3 extends JFrame {
Message3() {
var myMsg = new JLabel("Inheriting JFrame Class!");
add(myMsg);
setSize(500, 400);
getContentPane().setBackground(new java.awt.Color(0, 202, 202));
setLayout(new java.awt.GridBagLayout());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} | 27.489796 | 80 | 0.631032 |
192090001fbac9d801033941b0035035042359a4 | 102,124 |
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20160615 (GIT 4ac7450)
//----------------------------------------------------
package parser;
import java_cup.runtime.*;
import java_cup.runtime.ComplexSymbolFactory.ComplexSymbol;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import java.util.HashMap;
import source.*;
import tree.DeclNode;
import tree.ConstExp;
import tree.StatementNode;
import tree.ExpNode;
import tree.Operator;
import syms.*;
import java_cup.runtime.ComplexSymbolFactory.Location;
import java_cup.runtime.XMLElement;
/** CUP v0.11b 20160615 (GIT 4ac7450) generated parser.
*/
@SuppressWarnings({"rawtypes"})
public class CUPParser extends java_cup.runtime.lr_parser {
public final Class getSymbolContainer() {
return CUPToken.class;
}
/** Default constructor. */
@Deprecated
public CUPParser() {super();}
/** Constructor which sets the default scanner. */
@Deprecated
public CUPParser(java_cup.runtime.Scanner s) {super(s);}
/** Constructor which sets the default scanner. */
public CUPParser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);}
/** Production table. */
protected static final short _production_table[][] =
unpackFromStrings(new String[] {
"\000\127\000\002\046\002\000\002\002\004\000\002\002" +
"\004\000\002\002\003\000\002\003\004\000\002\004\005" +
"\000\002\004\004\000\002\004\002\000\002\005\004\000" +
"\002\005\004\000\002\005\004\000\002\006\003\000\002" +
"\006\004\000\002\007\006\000\002\007\003\000\002\010" +
"\003\000\002\010\004\000\002\010\003\000\002\010\003" +
"\000\002\011\003\000\002\011\004\000\002\012\006\000" +
"\002\012\003\000\002\013\003\000\002\013\007\000\002" +
"\013\003\000\002\015\003\000\002\016\003\000\002\016" +
"\004\000\002\017\006\000\002\017\003\000\002\020\005" +
"\000\002\021\010\000\002\021\005\000\002\014\004\000" +
"\002\014\002\000\002\022\006\000\002\027\004\000\002" +
"\027\002\000\002\041\004\000\002\041\002\000\002\042" +
"\005\000\002\042\002\000\002\042\003\000\002\025\005" +
"\000\002\023\003\000\002\023\005\000\002\024\006\000" +
"\002\024\010\000\002\024\003\000\002\024\004\000\002" +
"\024\004\000\002\024\005\000\002\024\007\000\002\024" +
"\004\000\002\024\003\000\002\045\004\000\002\045\002" +
"\000\002\044\005\000\002\044\002\000\002\043\005\000" +
"\002\040\003\000\002\026\003\000\002\030\003\000\002" +
"\030\005\000\002\034\003\000\002\034\003\000\002\034" +
"\003\000\002\034\003\000\002\034\003\000\002\034\003" +
"\000\002\031\003\000\002\031\005\000\002\035\003\000" +
"\002\035\003\000\002\032\003\000\002\032\005\000\002" +
"\036\003\000\002\036\003\000\002\033\004\000\002\033" +
"\004\000\002\033\005\000\002\033\003\000\002\033\003" +
"\000\002\033\006\000\002\033\003\000\002\037\003" });
/** Access to production table. */
public short[][] production_table() {return _production_table;}
/** Parse-action table. */
protected static final short[][] _action_table =
unpackFromStrings(new String[] {
"\000\227\000\016\003\005\030\001\032\001\037\001\043" +
"\001\044\001\001\002\000\004\002\231\001\002\000\004" +
"\002\ufffe\001\002\000\014\030\ufffa\032\ufffa\037\ufffa\043" +
"\ufffa\044\ufffa\001\002\000\004\002\000\001\002\000\014" +
"\030\020\032\021\037\011\043\017\044\013\001\002\000" +
"\004\050\205\001\002\000\006\002\ufffd\006\ufffd\001\002" +
"\000\006\003\176\050\200\001\002\000\004\006\174\001" +
"\002\000\014\030\ufffb\032\ufffb\037\ufffb\043\ufffb\044\ufffb" +
"\001\002\000\004\016\172\001\002\000\006\003\152\050" +
"\153\001\002\000\024\003\047\030\020\031\042\036\052" +
"\040\044\041\037\045\040\046\046\050\050\001\002\000" +
"\006\003\022\050\024\001\002\000\020\003\ufff3\030\ufff3" +
"\032\ufff3\037\ufff3\043\ufff3\044\ufff3\050\ufff3\001\002\000" +
"\020\003\022\030\ufff9\032\ufff9\037\ufff9\043\ufff9\044\ufff9" +
"\050\024\001\002\000\004\016\026\001\002\000\020\003" +
"\ufff6\030\ufff6\032\ufff6\037\ufff6\043\ufff6\044\ufff6\050\ufff6" +
"\001\002\000\012\003\027\013\032\050\031\051\030\001" +
"\002\000\010\006\uffef\024\uffef\027\uffef\001\002\000\010" +
"\006\ufff2\024\ufff2\027\ufff2\001\002\000\010\006\ufff0\024" +
"\ufff0\027\ufff0\001\002\000\012\003\027\013\032\050\031" +
"\051\030\001\002\000\004\006\034\001\002\000\020\003" +
"\ufff4\030\ufff4\032\ufff4\037\ufff4\043\ufff4\044\ufff4\050\ufff4" +
"\001\002\000\010\006\ufff1\024\ufff1\027\ufff1\001\002\000" +
"\020\003\ufff5\030\ufff5\032\ufff5\037\ufff5\043\ufff5\044\ufff5" +
"\050\ufff5\001\002\000\016\003\063\004\066\012\060\013" +
"\053\050\064\051\055\001\002\000\016\003\063\004\066" +
"\012\060\013\053\050\064\051\055\001\002\000\010\006" +
"\uffd0\034\uffd0\035\uffd0\001\002\000\004\050\142\001\002" +
"\000\006\006\137\035\140\001\002\000\004\050\050\001" +
"\002\000\006\006\uffd4\035\uffd4\001\002\000\016\003\063" +
"\004\066\012\060\013\053\050\064\051\055\001\002\000" +
"\010\006\uffca\034\uffca\035\uffca\001\002\000\012\006\uffc4" +
"\010\uffc4\034\uffc4\035\uffc4\001\002\000\004\010\133\001" +
"\002\000\016\003\063\004\066\012\060\013\053\050\064" +
"\051\055\001\002\000\016\003\uffab\004\uffab\012\uffab\013" +
"\uffab\050\uffab\051\uffab\001\002\000\022\003\uffc3\005\uffc3" +
"\006\uffc3\025\uffc3\033\uffc3\034\uffc3\035\uffc3\042\uffc3\001" +
"\002\000\046\003\uffaf\005\uffaf\006\uffaf\012\uffaf\013\uffaf" +
"\014\uffaf\015\uffaf\016\uffaf\017\uffaf\020\uffaf\021\uffaf\022" +
"\uffaf\023\uffaf\025\uffaf\033\uffaf\034\uffaf\035\uffaf\042\uffaf" +
"\001\002\000\042\003\uffc2\005\uffc2\006\uffc2\012\123\013" +
"\117\016\130\017\122\020\120\021\124\022\126\023\121" +
"\025\uffc2\033\uffc2\034\uffc2\035\uffc2\042\uffc2\001\002\000" +
"\004\042\113\001\002\000\016\003\063\004\066\012\060" +
"\013\053\050\064\051\055\001\002\000\046\003\uffba\005" +
"\uffba\006\uffba\012\uffba\013\uffba\014\107\015\106\016\uffba" +
"\017\uffba\020\uffba\021\uffba\022\uffba\023\uffba\025\uffba\033" +
"\uffba\034\uffba\035\uffba\042\uffba\001\002\000\046\003\uffb6" +
"\005\uffb6\006\uffb6\012\uffb6\013\uffb6\014\uffb6\015\uffb6\016" +
"\uffb6\017\uffb6\020\uffb6\021\uffb6\022\uffb6\023\uffb6\025\uffb6" +
"\033\uffb6\034\uffb6\035\uffb6\042\uffb6\001\002\000\046\003" +
"\uffac\005\uffac\006\uffac\012\uffac\013\uffac\014\uffac\015\uffac" +
"\016\uffac\017\uffac\020\uffac\021\uffac\022\uffac\023\uffac\025" +
"\uffac\033\uffac\034\uffac\035\uffac\042\uffac\001\002\000\050" +
"\003\uffc4\004\073\005\uffc4\006\uffc4\012\uffc4\013\uffc4\014" +
"\uffc4\015\uffc4\016\uffc4\017\uffc4\020\uffc4\021\uffc4\022\uffc4" +
"\023\uffc4\025\uffc4\033\uffc4\034\uffc4\035\uffc4\042\uffc4\001" +
"\002\000\016\003\063\004\066\012\060\013\053\050\064" +
"\051\055\001\002\000\016\003\063\004\066\012\060\013" +
"\053\050\064\051\055\001\002\000\046\003\uffae\005\uffae" +
"\006\uffae\012\uffae\013\uffae\014\uffae\015\uffae\016\uffae\017" +
"\uffae\020\uffae\021\uffae\022\uffae\023\uffae\025\uffae\033\uffae" +
"\034\uffae\035\uffae\042\uffae\001\002\000\004\005\071\001" +
"\002\000\046\003\uffb0\005\uffb0\006\uffb0\012\uffb0\013\uffb0" +
"\014\uffb0\015\uffb0\016\uffb0\017\uffb0\020\uffb0\021\uffb0\022" +
"\uffb0\023\uffb0\025\uffb0\033\uffb0\034\uffb0\035\uffb0\042\uffb0" +
"\001\002\000\046\003\uffb1\005\uffb1\006\uffb1\012\uffb1\013" +
"\uffb1\014\uffb1\015\uffb1\016\uffb1\017\uffb1\020\uffb1\021\uffb1" +
"\022\uffb1\023\uffb1\025\uffb1\033\uffb1\034\uffb1\035\uffb1\042" +
"\uffb1\001\002\000\006\005\uffc8\050\075\001\002\000\006" +
"\005\uffc6\025\102\001\002\000\004\011\100\001\002\000" +
"\004\005\077\001\002\000\046\003\uffad\005\uffad\006\uffad" +
"\012\uffad\013\uffad\014\uffad\015\uffad\016\uffad\017\uffad\020" +
"\uffad\021\uffad\022\uffad\023\uffad\025\uffad\033\uffad\034\uffad" +
"\035\uffad\042\uffad\001\002\000\016\003\063\004\066\012" +
"\060\013\053\050\064\051\055\001\002\000\006\005\uffc5" +
"\025\uffc5\001\002\000\004\050\075\001\002\000\004\005" +
"\uffc9\001\002\000\006\005\uffc6\025\102\001\002\000\004" +
"\005\uffc7\001\002\000\016\003\uffb3\004\uffb3\012\uffb3\013" +
"\uffb3\050\uffb3\051\uffb3\001\002\000\016\003\uffb4\004\uffb4" +
"\012\uffb4\013\uffb4\050\uffb4\051\uffb4\001\002\000\016\003" +
"\063\004\066\012\060\013\053\050\064\051\055\001\002" +
"\000\046\003\uffb5\005\uffb5\006\uffb5\012\uffb5\013\uffb5\014" +
"\uffb5\015\uffb5\016\uffb5\017\uffb5\020\uffb5\021\uffb5\022\uffb5" +
"\023\uffb5\025\uffb5\033\uffb5\034\uffb5\035\uffb5\042\uffb5\001" +
"\002\000\046\003\uffb2\005\uffb2\006\uffb2\012\uffb2\013\uffb2" +
"\014\uffb2\015\uffb2\016\uffb2\017\uffb2\020\uffb2\021\uffb2\022" +
"\uffb2\023\uffb2\025\uffb2\033\uffb2\034\uffb2\035\uffb2\042\uffb2" +
"\001\002\000\024\003\047\030\020\031\042\036\052\040" +
"\044\041\037\045\040\046\046\050\050\001\002\000\004" +
"\034\115\001\002\000\024\003\047\030\020\031\042\036" +
"\052\040\044\041\037\045\040\046\046\050\050\001\002" +
"\000\010\006\uffd1\034\uffd1\035\uffd1\001\002\000\016\003" +
"\uffb7\004\uffb7\012\uffb7\013\uffb7\050\uffb7\051\uffb7\001\002" +
"\000\016\003\uffbe\004\uffbe\012\uffbe\013\uffbe\050\uffbe\051" +
"\uffbe\001\002\000\016\003\uffbc\004\uffbc\012\uffbc\013\uffbc" +
"\050\uffbc\051\uffbc\001\002\000\016\003\uffbf\004\uffbf\012" +
"\uffbf\013\uffbf\050\uffbf\051\uffbf\001\002\000\016\003\uffb8" +
"\004\uffb8\012\uffb8\013\uffb8\050\uffb8\051\uffb8\001\002\000" +
"\016\003\uffbb\004\uffbb\012\uffbb\013\uffbb\050\uffbb\051\uffbb" +
"\001\002\000\016\003\063\004\066\012\060\013\053\050" +
"\064\051\055\001\002\000\016\003\uffbd\004\uffbd\012\uffbd" +
"\013\uffbd\050\uffbd\051\uffbd\001\002\000\016\003\063\004" +
"\066\012\060\013\053\050\064\051\055\001\002\000\016" +
"\003\uffc0\004\uffc0\012\uffc0\013\uffc0\050\uffc0\051\uffc0\001" +
"\002\000\026\003\uffc1\005\uffc1\006\uffc1\012\123\013\117" +
"\025\uffc1\033\uffc1\034\uffc1\035\uffc1\042\uffc1\001\002\000" +
"\046\003\uffb9\005\uffb9\006\uffb9\012\uffb9\013\uffb9\014\107" +
"\015\106\016\uffb9\017\uffb9\020\uffb9\021\uffb9\022\uffb9\023" +
"\uffb9\025\uffb9\033\uffb9\034\uffb9\035\uffb9\042\uffb9\001\002" +
"\000\016\003\063\004\066\012\060\013\053\050\064\051" +
"\055\001\002\000\010\006\uffcd\034\uffcd\035\uffcd\001\002" +
"\000\014\006\uffce\012\123\013\117\034\uffce\035\uffce\001" +
"\002\000\010\006\uffcf\034\uffcf\035\uffcf\001\002\000\024" +
"\003\047\030\020\031\042\036\052\040\044\041\037\045" +
"\040\046\046\050\050\001\002\000\012\002\uffd5\006\uffd5" +
"\034\uffd5\035\uffd5\001\002\000\006\006\uffd3\035\uffd3\001" +
"\002\000\004\004\143\001\002\000\006\005\uffc8\050\075" +
"\001\002\000\004\005\145\001\002\000\010\006\uffcc\034" +
"\uffcc\035\uffcc\001\002\000\004\033\147\001\002\000\024" +
"\003\047\030\020\031\042\036\052\040\044\041\037\045" +
"\040\046\046\050\050\001\002\000\010\006\uffd2\034\uffd2" +
"\035\uffd2\001\002\000\010\006\uffcb\034\uffcb\035\uffcb\001" +
"\002\000\020\003\uffeb\030\uffeb\032\uffeb\037\uffeb\043\uffeb" +
"\044\uffeb\050\uffeb\001\002\000\004\016\157\001\002\000" +
"\020\003\uffee\030\uffee\032\uffee\037\uffee\043\uffee\044\uffee" +
"\050\uffee\001\002\000\020\003\152\030\ufff8\032\ufff8\037" +
"\ufff8\043\ufff8\044\ufff8\050\153\001\002\000\020\003\uffed" +
"\030\uffed\032\uffed\037\uffed\043\uffed\044\uffed\050\uffed\001" +
"\002\000\010\003\161\026\164\050\162\001\002\000\004" +
"\006\171\001\002\000\004\006\uffe8\001\002\000\016\003" +
"\uffe7\005\uffe7\006\uffe7\011\uffe7\016\uffe7\025\uffe7\001\002" +
"\000\004\006\uffea\001\002\000\012\003\027\013\032\050" +
"\031\051\030\001\002\000\004\024\166\001\002\000\012" +
"\003\027\013\032\050\031\051\030\001\002\000\004\027" +
"\170\001\002\000\004\006\uffe9\001\002\000\020\003\uffec" +
"\030\uffec\032\uffec\037\uffec\043\uffec\044\uffec\050\uffec\001" +
"\002\000\014\030\ufffa\032\ufffa\037\ufffa\043\ufffa\044\ufffa" +
"\001\002\000\004\006\uffe2\001\002\000\014\030\ufffc\032" +
"\ufffc\037\ufffc\043\ufffc\044\ufffc\001\002\000\020\003\176" +
"\030\ufff7\032\ufff7\037\ufff7\043\ufff7\044\ufff7\050\200\001" +
"\002\000\020\003\uffe3\030\uffe3\032\uffe3\037\uffe3\043\uffe3" +
"\044\uffe3\050\uffe3\001\002\000\020\003\uffe6\030\uffe6\032" +
"\uffe6\037\uffe6\043\uffe6\044\uffe6\050\uffe6\001\002\000\004" +
"\007\201\001\002\000\004\050\162\001\002\000\004\006" +
"\203\001\002\000\020\003\uffe4\030\uffe4\032\uffe4\037\uffe4" +
"\043\uffe4\044\uffe4\050\uffe4\001\002\000\020\003\uffe5\030" +
"\uffe5\032\uffe5\037\uffe5\043\uffe5\044\uffe5\050\uffe5\001\002" +
"\000\006\003\206\004\207\001\002\000\004\016\uffe0\001" +
"\002\000\006\005\uffd9\050\212\001\002\000\010\003\225" +
"\005\uffd7\025\224\001\002\000\004\005\220\001\002\000" +
"\004\007\213\001\002\000\004\050\162\001\002\000\012" +
"\003\uffdb\005\uffdb\011\215\025\uffdb\001\002\000\016\003" +
"\063\004\066\012\060\013\053\050\064\051\055\001\002" +
"\000\010\003\uffdd\005\uffdd\025\uffdd\001\002\000\010\003" +
"\uffdc\005\uffdc\025\uffdc\001\002\000\006\007\222\016\uffde" +
"\001\002\000\004\016\uffe1\001\002\000\004\050\162\001" +
"\002\000\004\016\uffdf\001\002\000\004\050\212\001\002" +
"\000\004\005\uffd6\001\002\000\004\005\uffda\001\002\000" +
"\010\003\225\005\uffd7\025\224\001\002\000\004\005\uffd8" +
"\001\002\000\004\002\uffff\001\002" });
/** Access to parse-action table. */
public short[][] action_table() {return _action_table;}
/** <code>reduce_goto</code> table. */
protected static final short[][] _reduce_table =
unpackFromStrings(new String[] {
"\000\227\000\006\002\003\046\005\001\001\000\002\001" +
"\001\000\002\001\001\000\006\003\006\004\007\001\001" +
"\000\002\001\001\000\012\005\014\020\013\021\015\025" +
"\011\001\001\000\002\001\001\000\002\001\001\000\006" +
"\016\174\017\176\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\006\011\154\012\153\001\001" +
"\000\012\023\042\024\044\025\040\040\050\001\001\000" +
"\006\006\022\007\024\001\001\000\002\001\001\000\004" +
"\007\035\001\001\000\002\001\001\000\002\001\001\000" +
"\004\010\032\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\004\010\034\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\020\026\150\030\053\031\055\032\060\033\061\037" +
"\064\040\066\001\001\000\020\026\145\030\053\031\055" +
"\032\060\033\061\037\064\040\066\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\004\040\135" +
"\001\001\000\002\001\001\000\014\031\134\032\060\033" +
"\061\037\064\040\066\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\020\026\056\030\053\031" +
"\055\032\060\033\061\037\064\040\066\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\006\034" +
"\126\035\124\001\001\000\002\001\001\000\010\033\111" +
"\037\064\040\066\001\001\000\004\036\107\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\010" +
"\033\071\037\064\040\066\001\001\000\020\026\067\030" +
"\053\031\055\032\060\033\061\037\064\040\066\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\006\043\073\045\075\001\001\000\004" +
"\044\102\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\020\026\100\030\053\031\055\032\060" +
"\033\061\037\064\040\066\001\001\000\002\001\001\000" +
"\004\043\103\001\001\000\002\001\001\000\004\044\104" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\010\033\110\037\064\040\066\001\001\000\002" +
"\001\001\000\002\001\001\000\010\024\113\025\040\040" +
"\050\001\001\000\002\001\001\000\010\024\115\025\040" +
"\040\050\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\012\032\131\033\061\037" +
"\064\040\066\001\001\000\002\001\001\000\014\031\130" +
"\032\060\033\061\037\064\040\066\001\001\000\002\001" +
"\001\000\004\035\124\001\001\000\004\036\107\001\001" +
"\000\020\026\133\030\053\031\055\032\060\033\061\037" +
"\064\040\066\001\001\000\002\001\001\000\004\035\124" +
"\001\001\000\002\001\001\000\010\024\140\025\040\040" +
"\050\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\006\043\073\045\143\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\010\024\147" +
"\025\040\040\050\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\004\012\155\001\001\000\002\001\001\000\006\013" +
"\157\015\162\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\004\010\164\001" +
"\001\000\002\001\001\000\004\010\166\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\006\003" +
"\172\004\007\001\001\000\002\001\001\000\002\001\001" +
"\000\004\017\203\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\004\015\201\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\006\022\207\041\210\001\001" +
"\000\004\042\225\001\001\000\002\001\001\000\002\001" +
"\001\000\004\015\213\001\001\000\004\027\215\001\001" +
"\000\020\026\216\030\053\031\055\032\060\033\061\037" +
"\064\040\066\001\001\000\002\001\001\000\002\001\001" +
"\000\004\014\220\001\001\000\002\001\001\000\004\015" +
"\222\001\001\000\002\001\001\000\004\022\226\001\001" +
"\000\002\001\001\000\002\001\001\000\004\042\227\001" +
"\001\000\002\001\001\000\002\001\001" });
/** Access to <code>reduce_goto</code> table. */
public short[][] reduce_table() {return _reduce_table;}
/** Instance of action encapsulation class. */
protected CUP$CUPParser$actions action_obj;
/** Action encapsulation object initializer. */
protected void init_actions()
{
action_obj = new CUP$CUPParser$actions(this);
}
/** Invoke a user supplied parse action. */
public java_cup.runtime.Symbol do_action(
int act_num,
java_cup.runtime.lr_parser parser,
java.util.Stack stack,
int top)
throws java.lang.Exception
{
/* call code in generated class */
return action_obj.CUP$CUPParser$do_action(act_num, parser, stack, top);
}
/** Indicates start state. */
public int start_state() {return 0;}
/** Indicates start production. */
public int start_production() {return 2;}
/** <code>EOF</code> Symbol index. */
public int EOF_sym() {return 0;}
/** <code>error</code> Symbol index. */
public int error_sym() {return 1;}
/* This section provides some methods used by Java_CUP during parsing.
They override its default methods for reporting syntax errors. */
/** Retrieve the error handler to handle error messages. */
private Errors errors = ErrorHandler.getErrorHandler();
/** Override the default CUP syntax_error method with one
* that integrates better with the compiler's error reporting. */
@Override
public void syntax_error( Symbol cur_token ) {
errors.error( "PL0 syntax error", ((ComplexSymbol) cur_token).xleft );
}
/** Override the default CUP unrecovered_syntax_error method with one
* that integrates better with the compiler's error reporting. */
@Override
public void unrecovered_syntax_error( Symbol cur_token ) {
errors.error( "PL0 unrecovered syntax error",
((ComplexSymbol) cur_token).xleft );
}
/** Cup generated class to encapsulate user supplied action code.*/
@SuppressWarnings({"rawtypes", "unchecked", "unused"})
class CUP$CUPParser$actions {
/* This section provides global variables and methods used in the
* semantics actions associated with parsing rules.
* These are the only global variables you should need. */
/** Error handler for reporting error messages. */
private Errors errors = ErrorHandler.getErrorHandler();
/** The current symbol table scope is available globally.
* Its current scope corresponds to the procedure/main program
* being processed.
*/
Scope currentScope;
private final CUPParser parser;
/** Constructor */
CUP$CUPParser$actions(CUPParser parser) {
this.parser = parser;
}
/** Method 0 with the actual generated action code for actions 0 to 300. */
public final java_cup.runtime.Symbol CUP$CUPParser$do_action_part00000000(
int CUP$CUPParser$act_num,
java_cup.runtime.lr_parser CUP$CUPParser$parser,
java.util.Stack CUP$CUPParser$stack,
int CUP$CUPParser$top)
throws java.lang.Exception
{
/* Symbol object for return from actions */
java_cup.runtime.Symbol CUP$CUPParser$result;
/* select the action based on the action number */
switch (CUP$CUPParser$act_num)
{
/*. . . . . . . . . . . . . . . . . . . .*/
case 0: // NT$0 ::=
{
DeclNode.ProgramNode RESULT =null;
/* This action occurs before the whole program is recognised.
* Construct initial symbol table with current scope the
* predefined scope. */
SymbolTable symtab = new SymbolTable();
currentScope = symtab.getPredefinedScope();
/* Set up a dummy symbol table entry for the main program */
SymEntry.ProcedureEntry proc =
currentScope.addProcedure( "<main>", ErrorHandler.NO_LOCATION );
if( proc == null ) {
errors.fatal( "Could not add main program to symbol table",
ErrorHandler.NO_LOCATION );
}
/* Enter the scope for the main program and save the new local
* scope in main's symbol table entry */
currentScope = currentScope.newScope( proc );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("NT$0",36, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 1: // Program ::= NT$0 Block
{
DeclNode.ProgramNode RESULT =null;
// propagate RESULT from NT$0
RESULT = (DeclNode.ProgramNode) ((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location blockxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location blockxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode.BlockNode block = (StatementNode.BlockNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
/* Returned result of the whole parsing phase */
RESULT = new DeclNode.ProgramNode( currentScope, block );
/* This action is executed after the whole program
* has been recognised */
currentScope = currentScope.getParent();
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Program",0, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 2: // $START ::= Program EOF
{
Object RESULT =null;
Location start_valxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location start_valxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
DeclNode.ProgramNode start_val = (DeclNode.ProgramNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
RESULT = start_val;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
/* ACCEPT */
CUP$CUPParser$parser.done_parsing();
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 3: // Program ::= error
{
DeclNode.ProgramNode RESULT =null;
/* A null result from Program will cause the compiler to
avoid further processing. */
RESULT = null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Program",0, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 4: // Block ::= DeclarationList CompoundStatement
{
StatementNode.BlockNode RESULT =null;
Location dlxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location dlxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
DeclNode.DeclListNode dl = (DeclNode.DeclListNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location bxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location bxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode b = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.BlockNode( bxleft, dl, b, currentScope );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Block",1, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 5: // DeclarationList ::= DeclarationList ProcedureDef SEMICOLON
{
DeclNode.DeclListNode RESULT =null;
Location dlxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location dlxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
DeclNode.DeclListNode dl = (DeclNode.DeclListNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location pxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location pxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
DeclNode.ProcedureNode p = (DeclNode.ProcedureNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
dl.addDeclaration(p);
RESULT = dl;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("DeclarationList",2, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 6: // DeclarationList ::= DeclarationList Declaration
{
DeclNode.DeclListNode RESULT =null;
Location dlxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location dlxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
DeclNode.DeclListNode dl = (DeclNode.DeclListNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
RESULT = dl;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("DeclarationList",2, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 7: // DeclarationList ::=
{
DeclNode.DeclListNode RESULT =null;
RESULT = new DeclNode.DeclListNode();
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("DeclarationList",2, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 8: // Declaration ::= KW_CONST ConstDefSeq
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Declaration",3, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 9: // Declaration ::= KW_TYPE TypeDefSeq
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Declaration",3, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 10: // Declaration ::= KW_VAR VarDeclSeq
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Declaration",3, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 11: // ConstDefSeq ::= ConstDef
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ConstDefSeq",4, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 12: // ConstDefSeq ::= ConstDefSeq ConstDef
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ConstDefSeq",4, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 13: // ConstDef ::= IDENTIFIER EQUALS Constant SEMICOLON
{
Object RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
ConstExp c = (ConstExp)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
/* The attribute idxleft represents the location of the start
* character of the IDENTIFIER token in the input stream.
*/
/* addConstant returns null if id is already defined
* in the current scope */
if( currentScope.addConstant( id, idxleft, c ) == null ) {
errors.error( id + " already defined", idxleft );
}
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ConstDef",5, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 14: // ConstDef ::= error
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ConstDef",5, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 15: // Constant ::= NUMBER
{
ConstExp RESULT =null;
Location nxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location nxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Integer n = (Integer)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ConstExp.NumberNode( nxleft, currentScope,
Predefined.INTEGER_TYPE, n );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Constant",6, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 16: // Constant ::= MINUS Constant
{
ConstExp RESULT =null;
Location opxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location opxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Object op = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ConstExp c = (ConstExp)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ConstExp.NegateNode( opxleft, currentScope, c );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Constant",6, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 17: // Constant ::= IDENTIFIER
{
ConstExp RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ConstExp.ConstIdNode( idxleft, currentScope, id );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Constant",6, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 18: // Constant ::= error
{
ConstExp RESULT =null;
Location errxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location errxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Object err = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ConstExp.ErrorNode( errxleft, currentScope );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Constant",6, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 19: // TypeDefSeq ::= TypeDef
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("TypeDefSeq",7, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 20: // TypeDefSeq ::= TypeDefSeq TypeDef
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("TypeDefSeq",7, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 21: // TypeDef ::= IDENTIFIER EQUALS Type SEMICOLON
{
Object RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location typexleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location typexright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Type type = (Type)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
SymEntry.TypeEntry entry = currentScope.addType( id, idxleft, type );
if( entry == null ) {
errors.error( id + " already defined", idxleft );
}
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("TypeDef",8, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 22: // TypeDef ::= error
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("TypeDef",8, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 23: // Type ::= TypeIdentifier
{
Type RESULT =null;
Location typexleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location typexright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Type type = (Type)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = type;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Type",9, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 24: // Type ::= LBRACKET Constant RANGE Constant RBRACKET
{
Type RESULT =null;
Location loxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location loxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
ConstExp lo = (ConstExp)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location hixleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location hixright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
ConstExp hi = (ConstExp)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
RESULT = new Type.SubrangeType( lo, hi );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Type",9, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 25: // Type ::= error
{
Type RESULT =null;
Location errxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location errxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Object err = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = Type.ERROR_TYPE;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Type",9, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 26: // TypeIdentifier ::= IDENTIFIER
{
Type RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
/* As the type identifier may not be defined at this point
* the abstract syntax tree records the id, as well as the
* symbol table context to look it up within later.
*/
RESULT = new Type.IdRefType( id, currentScope, idxleft );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("TypeIdentifier",11, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 27: // VarDeclSeq ::= VarDecl
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("VarDeclSeq",12, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 28: // VarDeclSeq ::= VarDeclSeq VarDecl
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("VarDeclSeq",12, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 29: // VarDecl ::= IDENTIFIER COLON TypeIdentifier SEMICOLON
{
Object RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location typexleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location typexright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Type type = (Type)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
// Variables are always of ReferenceType.
Type.ReferenceType varType = new Type.ReferenceType( type );
if(currentScope.addVariable(id, idxleft, varType) == null) {
errors.error( id + " already declared", idxleft );
}
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("VarDecl",13, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 30: // VarDecl ::= error
{
Object RESULT =null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("VarDecl",13, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 31: // ProcedureDef ::= ProcedureHead EQUALS Block
{
DeclNode.ProcedureNode RESULT =null;
Location procEntryxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location procEntryxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
SymEntry.ProcedureEntry procEntry = (SymEntry.ProcedureEntry)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location bxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location bxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode.BlockNode b = (StatementNode.BlockNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
/* Executed after recognising the whole procedure */
currentScope = currentScope.getParent();
RESULT = new DeclNode.ProcedureNode( procEntry, b );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ProcedureDef",14, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 32: // ProcedureHead ::= KW_PROCEDURE IDENTIFIER LPAREN FormalParamList RPAREN OptReturnType
{
SymEntry.ProcedureEntry RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)).value;
Location plxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location plxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
List<SymEntry.ParamEntry> pl = (List<SymEntry.ParamEntry>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location ortxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location ortxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Type ort = (Type)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
SymEntry.ProcedureEntry procEntry;
/* Add an entry for the procedure to the current scope */
procEntry = currentScope.addProcedure( id, idxleft );
if( procEntry == null ) {
errors.error( id + " already declared", idxleft );
/* Create a dummy symbol table entry.
* Note that this entry isn't in symtab. */
procEntry = new SymEntry.ProcedureEntry( id, idxleft );
procEntry.setScope( currentScope );
}
/* Create a new scope for the symbols local to
* the procedure. */
currentScope = currentScope.newScope( procEntry );
// Set up the return type and formal parameters
Type.ProcedureType procType = procEntry.getType();
// Set the result type, will either be a Type or null
procType.setResultType(ort);
// Used to check for duplicate identifiers
ArrayList<String> identifiers = new ArrayList<String>();
for (int i = (pl.size() - 1); i >= 0; i--) {
SymEntry.ParamEntry param = pl.get(i);
String paramId = param.getIdent();
if (identifiers.contains(paramId)) {
errors.error(paramId + " repeated", param.getLocation());
} else {
identifiers.add(paramId);
// Add to the formal parameters
procType.getFormalParams().add(param);
// Add the variable to the scope
currentScope.addEntry(param);
}
}
RESULT = procEntry;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ProcedureHead",15, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-5)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 33: // ProcedureHead ::= KW_PROCEDURE IDENTIFIER error
{
SymEntry.ProcedureEntry RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
SymEntry.ProcedureEntry procEntry =
new SymEntry.ProcedureEntry( id, idxleft );
procEntry.setScope( currentScope );
currentScope = currentScope.newScope( procEntry );
RESULT = procEntry;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ProcedureHead",15, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 34: // OptReturnType ::= COLON TypeIdentifier
{
Type RESULT =null;
Location tixleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location tixright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Type ti = (Type)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = ti;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptReturnType",10, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 35: // OptReturnType ::=
{
Type RESULT =null;
RESULT = null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptReturnType",10, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 36: // FormalParam ::= IDENTIFIER COLON TypeIdentifier OptDefaultValue
{
SymEntry.ParamEntry RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location tixleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location tixright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Type ti = (Type)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location odfxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location odfxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode odf = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
// Create a new reference type to ti
Type.ReferenceType refType = new Type.ReferenceType(ti);
SymEntry.ParamEntry param = new SymEntry.ParamEntry(id, idxleft, refType);
// Set the default parameter, will either be a ExpNode or null
param.setDefaultParam(odf);
RESULT = param;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("FormalParam",16, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 37: // OptDefaultValue ::= GETS Condition
{
ExpNode RESULT =null;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode c = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
// Return the condition
RESULT = c;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptDefaultValue",21, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 38: // OptDefaultValue ::=
{
ExpNode RESULT =null;
// No default value
RESULT = null;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptDefaultValue",21, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 39: // FormalParamList ::= FormalParam OptFormalParams
{
List<SymEntry.ParamEntry> RESULT =null;
Location fpxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location fpxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
SymEntry.ParamEntry fp = (SymEntry.ParamEntry)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location ofpxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location ofpxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
List<SymEntry.ParamEntry> ofp = (List<SymEntry.ParamEntry>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
// Add the first parameter
ofp.add(fp);
RESULT = ofp;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("FormalParamList",31, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 40: // FormalParamList ::=
{
List<SymEntry.ParamEntry> RESULT =null;
// Return an empty list
List<SymEntry.ParamEntry> params = new ArrayList<SymEntry.ParamEntry>();
RESULT = params;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("FormalParamList",31, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 41: // OptFormalParams ::= COMMA FormalParam OptFormalParams
{
List<SymEntry.ParamEntry> RESULT =null;
Location fpxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location fpxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
SymEntry.ParamEntry fp = (SymEntry.ParamEntry)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location ofpxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location ofpxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
List<SymEntry.ParamEntry> ofp = (List<SymEntry.ParamEntry>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
// Add to the current list then return
ofp.add(fp);
RESULT = ofp;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptFormalParams",32, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 42: // OptFormalParams ::=
{
List<SymEntry.ParamEntry> RESULT =null;
// Create the list
RESULT = new ArrayList<SymEntry.ParamEntry>();
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptFormalParams",32, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 43: // OptFormalParams ::= error
{
List<SymEntry.ParamEntry> RESULT =null;
// If we have errors, still get a list of parameters
RESULT = new ArrayList<SymEntry.ParamEntry>();
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptFormalParams",32, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 44: // CompoundStatement ::= KW_BEGIN StatementList KW_END
{
StatementNode RESULT =null;
Location slxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location slxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
StatementNode.ListNode sl = (StatementNode.ListNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
RESULT = sl;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("CompoundStatement",19, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 45: // StatementList ::= Statement
{
StatementNode.ListNode RESULT =null;
Location sxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location sxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode s = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.ListNode( sxleft );
RESULT.addStatement(s);
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("StatementList",17, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 46: // StatementList ::= StatementList SEMICOLON Statement
{
StatementNode.ListNode RESULT =null;
Location slxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location slxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
StatementNode.ListNode sl = (StatementNode.ListNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location sxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location sxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode s = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
sl.addStatement( s );
RESULT = sl;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("StatementList",17, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 47: // Statement ::= KW_WHILE Condition KW_DO Statement
{
StatementNode RESULT =null;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
ExpNode c = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location sxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location sxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode s = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.WhileNode( cxleft, c, s );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 48: // Statement ::= KW_IF Condition KW_THEN Statement KW_ELSE Statement
{
StatementNode RESULT =null;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)).xright;
ExpNode c = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)).value;
Location s1xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location s1xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
StatementNode s1 = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location s2xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location s2xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode s2 = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.IfNode( cxleft, c, s1, s2 );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-5)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 49: // Statement ::= CompoundStatement
{
StatementNode RESULT =null;
Location sxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location sxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
StatementNode s = (StatementNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = s;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 50: // Statement ::= KW_READ LValue
{
StatementNode RESULT =null;
Location rxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location rxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Object r = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location lvalxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location lvalxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode lval = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.AssignmentNode( lvalxleft,
lval, new ExpNode.ReadNode( rxleft ) );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 51: // Statement ::= KW_WRITE Exp
{
StatementNode RESULT =null;
Location exleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location exright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.WriteNode( exleft, e );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 52: // Statement ::= LValue ASSIGN Condition
{
StatementNode RESULT =null;
Location lvalxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location lvalxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
ExpNode lval = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location rvalxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location rvalxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode rval = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.AssignmentNode( lvalxleft, lval, rval );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 53: // Statement ::= KW_CALL IDENTIFIER LPAREN ActualParamList RPAREN
{
StatementNode RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location plxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location plxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
List<ExpNode.ActualParamNode> pl = (List<ExpNode.ActualParamNode>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
StatementNode.CallNode call = new StatementNode.CallNode( idxleft, id );
ArrayList<String> identifiers = new ArrayList<String>();
for (int i = pl.size() - 1; i >= 0; i--) {
ExpNode.ActualParamNode param = pl.get(i);
if (identifiers.contains(param.getIdentifier())) {
errors.error(param.getIdentifier() + " repeated", param.getLocation());
}
identifiers.add(param.getIdentifier());
}
call.setParameters(pl);
RESULT = call;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-4)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 54: // Statement ::= KW_RETURN Condition
{
StatementNode RESULT =null;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode c = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
StatementNode.ReturnNode rt = new StatementNode.ReturnNode(cxleft, c);
RESULT = rt;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 55: // Statement ::= error
{
StatementNode RESULT =null;
Location pxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location pxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Object p = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new StatementNode.ErrorNode( pxleft );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Statement",18, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 56: // ActualParamList ::= ActualParam OptActualParams
{
List<ExpNode.ActualParamNode> RESULT =null;
Location apxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location apxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
ExpNode.ActualParamNode ap = (ExpNode.ActualParamNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location oapxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location oapxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
List<ExpNode.ActualParamNode> oap = (List<ExpNode.ActualParamNode>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
// Add the parameter
oap.add(ap);
RESULT = oap;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ActualParamList",35, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 57: // ActualParamList ::=
{
List<ExpNode.ActualParamNode> RESULT =null;
RESULT = new ArrayList<ExpNode.ActualParamNode>();
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ActualParamList",35, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 58: // OptActualParams ::= COMMA ActualParam OptActualParams
{
List<ExpNode.ActualParamNode> RESULT =null;
Location apxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location apxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
ExpNode.ActualParamNode ap = (ExpNode.ActualParamNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location oapxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location oapxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
List<ExpNode.ActualParamNode> oap = (List<ExpNode.ActualParamNode>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
// Add the parameter
oap.add(ap);
RESULT = oap;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptActualParams",34, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 59: // OptActualParams ::=
{
List<ExpNode.ActualParamNode> RESULT =null;
RESULT = new ArrayList<ExpNode.ActualParamNode>();
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("OptActualParams",34, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 60: // ActualParam ::= IDENTIFIER GETS Condition
{
ExpNode.ActualParamNode RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode c = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.ActualParamNode( idxleft, id, c );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("ActualParam",33, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 61: // LValue ::= IDENTIFIER
{
ExpNode RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.IdentifierNode( idxleft, id );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("LValue",30, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 62: // Condition ::= RelCondition
{
ExpNode RESULT =null;
Location exleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location exright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = e;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Condition",20, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 63: // RelCondition ::= Exp
{
ExpNode RESULT =null;
Location exleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location exright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = e;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("RelCondition",22, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 64: // RelCondition ::= Exp Relation Exp
{
ExpNode RESULT =null;
Location e1xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location e1xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
ExpNode e1 = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location opxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location opxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Operator op = (Operator)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location e2xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location e2xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e2 = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.OperatorNode( opxleft,
op, new ExpNode.ArgumentsNode(e1,e2) );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("RelCondition",22, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 65: // Relation ::= EQUALS
{
Operator RESULT =null;
RESULT = Operator.EQUALS_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Relation",26, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 66: // Relation ::= NEQUALS
{
Operator RESULT =null;
RESULT = Operator.NEQUALS_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Relation",26, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 67: // Relation ::= LEQUALS
{
Operator RESULT =null;
RESULT = Operator.LEQUALS_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Relation",26, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 68: // Relation ::= LESS
{
Operator RESULT =null;
RESULT = Operator.LESS_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Relation",26, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 69: // Relation ::= GREATER
{
Operator RESULT =null;
RESULT = Operator.GREATER_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Relation",26, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 70: // Relation ::= GEQUALS
{
Operator RESULT =null;
RESULT = Operator.GEQUALS_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Relation",26, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 71: // Exp ::= Term
{
ExpNode RESULT =null;
Location txleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location txright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode t = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = t;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Exp",23, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 72: // Exp ::= Exp AddOp Term
{
ExpNode RESULT =null;
Location e1xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location e1xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
ExpNode e1 = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location opxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location opxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Operator op = (Operator)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location e2xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location e2xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e2 = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.OperatorNode( opxleft, op,
new ExpNode.ArgumentsNode(e1,e2) );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Exp",23, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 73: // AddOp ::= PLUS
{
Operator RESULT =null;
RESULT = Operator.ADD_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("AddOp",27, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 74: // AddOp ::= MINUS
{
Operator RESULT =null;
RESULT = Operator.SUB_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("AddOp",27, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 75: // Term ::= Factor
{
ExpNode RESULT =null;
Location fxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location fxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode f = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = f;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Term",24, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 76: // Term ::= Term MulOp Factor
{
ExpNode RESULT =null;
Location e1xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xleft;
Location e1xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).xright;
ExpNode e1 = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)).value;
Location opxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location opxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Operator op = (Operator)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location e2xleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location e2xright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e2 = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.OperatorNode( opxleft, op,
new ExpNode.ArgumentsNode(e1,e2) );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Term",24, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 77: // MulOp ::= TIMES
{
Operator RESULT =null;
RESULT = Operator.MUL_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("MulOp",28, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 78: // MulOp ::= DIVIDE
{
Operator RESULT =null;
RESULT = Operator.DIV_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("MulOp",28, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 79: // Factor ::= PLUS Factor
{
ExpNode RESULT =null;
Location exleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location exright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = e;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 80: // Factor ::= UnaryOperator Factor
{
ExpNode RESULT =null;
Location opxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location opxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
Operator op = (Operator)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
Location exleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location exright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode e = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.OperatorNode( opxleft, op, e );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 81: // Factor ::= LPAREN Condition RPAREN
{
ExpNode RESULT =null;
Location cxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location cxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
ExpNode c = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
RESULT = c;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-2)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 82: // Factor ::= NUMBER
{
ExpNode RESULT =null;
Location nxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location nxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Integer n = (Integer)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.ConstNode( nxleft,
Predefined.INTEGER_TYPE, n.intValue() );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 83: // Factor ::= LValue
{
ExpNode RESULT =null;
Location lvalxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location lvalxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
ExpNode lval = (ExpNode)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = lval;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 84: // Factor ::= IDENTIFIER LPAREN ActualParamList RPAREN
{
ExpNode RESULT =null;
Location idxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xleft;
Location idxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).xright;
String id = (String)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)).value;
Location plxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xleft;
Location plxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).xright;
List<ExpNode.ActualParamNode> pl = (List<ExpNode.ActualParamNode>)((java_cup.runtime.Symbol) CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-1)).value;
// Similar to call node
ExpNode.ReturnExpNode call = new ExpNode.ReturnExpNode( idxleft, id );
ArrayList<String> identifiers = new ArrayList<String>();
for (int i = pl.size() - 1; i >= 0; i--) {
ExpNode.ActualParamNode param = pl.get(i);
if (identifiers.contains(param.getIdentifier())) {
errors.error(param.getIdentifier() + " repeated", param.getLocation());
}
identifiers.add(param.getIdentifier());
}
call.setParameters(pl);
RESULT = call;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.elementAt(CUP$CUPParser$top-3)), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 85: // Factor ::= error
{
ExpNode RESULT =null;
Location exleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location exright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Object e = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = new ExpNode.ErrorNode( exleft );
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("Factor",25, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 86: // UnaryOperator ::= MINUS
{
Operator RESULT =null;
Location opxleft = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xleft;
Location opxright = ((java_cup.runtime.ComplexSymbolFactory.ComplexSymbol)CUP$CUPParser$stack.peek()).xright;
Object op = (Object)((java_cup.runtime.Symbol) CUP$CUPParser$stack.peek()).value;
RESULT = Operator.NEG_OP;
CUP$CUPParser$result = parser.getSymbolFactory().newSymbol("UnaryOperator",29, ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), ((java_cup.runtime.Symbol)CUP$CUPParser$stack.peek()), RESULT);
}
return CUP$CUPParser$result;
/* . . . . . .*/
default:
throw new Exception(
"Invalid action number "+CUP$CUPParser$act_num+"found in internal parse table");
}
} /* end of method */
/** Method splitting the generated action code into several parts. */
public final java_cup.runtime.Symbol CUP$CUPParser$do_action(
int CUP$CUPParser$act_num,
java_cup.runtime.lr_parser CUP$CUPParser$parser,
java.util.Stack CUP$CUPParser$stack,
int CUP$CUPParser$top)
throws java.lang.Exception
{
return CUP$CUPParser$do_action_part00000000(
CUP$CUPParser$act_num,
CUP$CUPParser$parser,
CUP$CUPParser$stack,
CUP$CUPParser$top);
}
}
}
| 57.212325 | 239 | 0.639389 |
54af6e7a9afd0413d543b33aaadad278d174b76a | 22,781 | /*
* Copyright 2015-2017 OpenCB
*
* 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.opencb.opencga.catalog.monitor;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.exceptions.CatalogIOException;
import org.opencb.opencga.catalog.io.CatalogIOManager;
import org.opencb.opencga.catalog.managers.CatalogManager;
import org.opencb.opencga.catalog.utils.FileScanner;
import org.opencb.opencga.core.models.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Created by jacobo on 4/11/14.
*
* Scans the temporal output directory from a job to find all generated files.
* Modifies the job status to set the output and endTime.
* If the job was type:INDEX, modify the index status.
*/
public class ExecutionOutputRecorder {
private static Logger logger = LoggerFactory.getLogger(ExecutionOutputRecorder.class);
private final CatalogManager catalogManager;
private CatalogIOManager ioManager;
private final String sessionId;
private final boolean calculateChecksum = false; //TODO: Read from config file
private final FileScanner.FileScannerPolicy fileScannerPolicy = FileScanner.FileScannerPolicy.DELETE; //TODO: Read from config file
public ExecutionOutputRecorder(CatalogManager catalogManager, String sessionId) throws CatalogIOException {
this.catalogManager = catalogManager;
this.ioManager = catalogManager.getCatalogIOManagerFactory().get("file");
this.sessionId = sessionId;
}
@Deprecated
public void recordJobOutputAndPostProcess(Job job, boolean jobFailed) throws CatalogException {
}
//
// public void recordJobOutputAndPostProcess(Job job, String status) throws CatalogException, IOException, URISyntaxException {
// /** Modifies the job to set the output and endTime. **/
// URI uri = UriUtils.createUri(catalogManager.getConfiguration().getTempJobsDir());
// Path tmpOutdirPath = Paths.get(uri.getPath()).resolve("J_" + job.getId());
//// Path tmpOutdirPath = Paths.get(catalogManager.getCatalogConfiguration().getTempJobsDir(), "J_" + job.getId());
// this.ioManager = catalogManager.getCatalogIOManagerFactory().get(tmpOutdirPath.toUri());
// recordJobOutput(job, tmpOutdirPath);
// updateJobStatus(job, new Job.JobStatus(status));
// }
@Deprecated
public void recordJobOutputOld(Job job) {
}
// /**
// * Scans the temporal output folder for the job and adds all the output files to catalog.
// *
// * @param job job.
// * @param tmpOutdirPath Temporal output directory path.
// * @param userToken valid token.
// * @throws CatalogException catalogException.
// * @throws IOException ioException.
// */
// public void recordJobOutput(Job job, Path tmpOutdirPath, String userToken) throws CatalogException, IOException {
// // parameters to update in the job
// ObjectMap parameters = new ObjectMap();
//
// logger.debug("Moving data from temporary folder {} to catalog folder...", tmpOutdirPath);
//
// // Delete job.status file
// Path path = Paths.get(tmpOutdirPath.toString(), JOB_STATUS_FILE);
// if (path.toFile().exists()) {
// logger.info("Deleting " + JOB_STATUS_FILE + " file: {}", path.toUri());
// try {
// ioManager.deleteFile(path.toUri());
// } catch (CatalogIOException e) {
// logger.error("Could not delete " + JOB_STATUS_FILE + " file");
// throw e;
// }
// }
//
// URI tmpOutDirUri = tmpOutdirPath.toUri();
// /* Scans the output directory from a job or index to find all files. **/
// logger.debug("Scan the temporal output directory ({}) from a job to find all generated files.", tmpOutDirUri);
//
// // Create the catalog output directory
// String studyStr = (String) job.getAttributes().get(Job.OPENCGA_STUDY);
// String outputDir = (String) job.getAttributes().get(Job.OPENCGA_OUTPUT_DIR);
//
// if (StringUtils.isEmpty(outputDir)) {
// // If Job.OPENCGA_OUTPUT_DIR, we will suppose the job was not intended to register any file in catalog, so we will only remove
// // the temporal directory
// ioManager.deleteDirectory(tmpOutDirUri);
//
// return;
// }
//
//// String userToken = (String) job.getAttributes().get(Job.OPENCGA_USER_TOKEN);
// File outDir;
//
// // If outputDir is the root
// if ("/".equals(outputDir)) {
// outDir = catalogManager.getFileManager().get(studyStr, outputDir, QueryOptions.empty(), userToken).first();
// } else {
// try {
// outDir = catalogManager.getFileManager().createFolder(studyStr, outputDir, new File.FileStatus(), true, "",
// QueryOptions.empty(), userToken).first();
// parameters.append(JobDBAdaptor.QueryParams.OUT_DIR.key(), outDir);
// } catch (CatalogException e) {
// logger.error("Cannot find file {}. Error: {}", job.getOutDir().getPath(), e.getMessage());
// throw e;
// }
// }
//
// FileScanner fileScanner = new FileScanner(catalogManager);
// List<File> files;
// try {
// logger.info("Scanning files from {} to move to {}", outDir.getPath(), tmpOutdirPath);
// files = fileScanner.scan(outDir, tmpOutDirUri, fileScannerPolicy, calculateChecksum, true, uri -> true,
// sessionId);
// } catch (IOException e) {
// logger.warn("IOException when scanning temporal directory. Error: {}", e.getMessage());
// throw e;
// } catch (CatalogException e) {
// logger.warn("CatalogException when scanning temporal directory. Error: {}", e.getMessage());
// throw e;
// }
//
// if (!ioManager.exists(tmpOutDirUri)) {
// logger.warn("Output folder doesn't exist");
// return;
// }
//
// List<URI> uriList;
// try {
// uriList = ioManager.listFiles(tmpOutDirUri);
// } catch (CatalogIOException e) {
// logger.warn("Could not obtain the URI of the files within the directory {}", tmpOutDirUri);
// logger.error(e.getMessage());
// throw e;
// }
//
// if (uriList.isEmpty()) {
// try {
// ioManager.deleteDirectory(tmpOutDirUri);
// } catch (CatalogIOException e) {
// if (ioManager.exists(tmpOutDirUri)) {
// logger.error("Could not delete empty directory {}. Error: {}", tmpOutDirUri, e.getMessage());
// throw e;
// }
// }
// } else {
// logger.error("Error processing job output. Temporal job out dir is not empty. " + uriList);
// }
//
// parameters.put(JobDBAdaptor.QueryParams.OUTPUT.key(), files);
// parameters.put(JobDBAdaptor.QueryParams.END_TIME.key(), System.currentTimeMillis());
// try {
// catalogManager.getJobManager().update(studyStr, job.getUuid(), parameters, null, this.sessionId);
// } catch (CatalogException e) {
// logger.error("Critical error. Could not update job output files from job {} with output {}. Error: {}", job.getUuid(),
// StringUtils.join(files.stream().map(File::getPath).collect(Collectors.toList()), ","), e.getMessage());
// throw e;
// }
//
// //TODO: "input" files could be modified by the tool. Have to be scanned, calculate the new Checksum and
// }
// /**
// * Scans the temporal output folder for the job and adds all the output files to catalog.
// * @deprecated The output directory should be created in this function and not before.
// *
// * @param job job.
// * @param tmpOutdirPath Temporal output directory path.
// * @throws CatalogException catalogException.
// * @throws IOException ioException.
// */
// @Deprecated
// public void recordJobOutputOld(Job job, Path tmpOutdirPath) throws CatalogException, IOException {
// logger.debug("Moving data from temporary folder to catalog folder...");
//
// // Delete job.status file
// Path path = Paths.get(tmpOutdirPath.toString(), JOB_STATUS_FILE);
// if (path.toFile().exists()) {
// logger.info("Deleting " + JOB_STATUS_FILE + " file: {}", path.toUri());
// try {
// ioManager.deleteFile(path.toUri());
// } catch (CatalogIOException e) {
// logger.error("Could not delete " + JOB_STATUS_FILE + " file");
// throw e;
// }
// }
//
// URI tmpOutDirUri = tmpOutdirPath.toUri();
// /* Scans the output directory from a job or index to find all files. **/
// logger.debug("Scan the temporal output directory ({}) from a job to find all generated files.", tmpOutDirUri);
//
// // TODO: Create output directory in catalog
// File outDir;
// try {
// outDir = catalogManager.getFileManager().get(job.getOutDir().getUid(), new QueryOptions(), sessionId).getResults().get(0);
// } catch (CatalogException e) {
// logger.error("Cannot find file {}. Error: {}", job.getOutDir().getUid(), e.getMessage());
// throw e;
// }
//
// FileScanner fileScanner = new FileScanner(catalogManager);
// List<File> files;
// try {
// logger.info("Scanning files from {} to move to {}", outDir.getPath(), tmpOutdirPath);
// files = fileScanner.scan(outDir, tmpOutDirUri, fileScannerPolicy, calculateChecksum, true, uri -> true,
// sessionId);
// } catch (IOException e) {
// logger.warn("IOException when scanning temporal directory. Error: {}", e.getMessage());
// throw e;
// } catch (CatalogException e) {
// logger.warn("CatalogException when scanning temporal directory. Error: {}", e.getMessage());
// throw e;
// }
// if (!ioManager.exists(tmpOutDirUri)) {
// logger.warn("Output folder doesn't exist");
// return;
// }
//
// List<URI> uriList;
// try {
// uriList = ioManager.listFiles(tmpOutDirUri);
// } catch (CatalogIOException e) {
// logger.warn("Could not obtain the URI of the files within the directory {}", tmpOutDirUri);
// logger.error(e.getMessage());
// throw e;
// }
//
// if (uriList.isEmpty()) {
// try {
// ioManager.deleteDirectory(tmpOutDirUri);
// } catch (CatalogIOException e) {
// if (ioManager.exists(tmpOutDirUri)) {
// logger.error("Could not delete empty directory {}. Error: {}", tmpOutDirUri, e.getMessage());
// throw e;
// }
// }
// } else {
// logger.error("Error processing job output. Temporal job out dir is not empty. " + uriList);
// }
//
// ObjectMap parameters = new ObjectMap();
// parameters.put(JobDBAdaptor.QueryParams.OUTPUT.key(), files);
// parameters.put(JobDBAdaptor.QueryParams.END_TIME.key(), System.currentTimeMillis());
// try {
// catalogManager.getJobManager().update(job.getUid(), parameters, null, this.sessionId);
// } catch (CatalogException e) {
// logger.error("Critical error. Could not update job output files from job {} with output {}. Error: {}", job.getUid(),
// StringUtils.join(files.stream().map(File::getUid).collect(Collectors.toList()), ","), e.getMessage());
// throw e;
// }
//
// //TODO: "input" files could be modified by the tool. Have to be scanned, calculate the new Checksum and
// }
// public void updateJobStatus(Job job, Job.JobStatus jobStatus) throws CatalogException {
// if (jobStatus != null) {
// if (jobStatus.getName().equalsIgnoreCase(Job.JobStatus.DONE)) {
// jobStatus.setName(Job.JobStatus.READY);
// jobStatus.setMessage("The job has finished");
// } else if (jobStatus.getName().equalsIgnoreCase(Job.JobStatus.ERROR)) {
// jobStatus.setName(Job.JobStatus.ERROR);
// jobStatus.setMessage("The job finished with an error");
// } else {
// logger.error("This block should never be executed. Accepted status in " + JOB_STATUS_FILE + " file are DONE and ERROR");
// jobStatus.setName(Job.JobStatus.ERROR);
// jobStatus.setMessage("The finished with an unexpected error");
// }
//// ObjectMap params = new ObjectMap(JobDBAdaptor.QueryParams.STATUS.key(), jobStatus);
//// catalogManager.getJobManager().update(job.getId(), params, new QueryOptions(), sessionId);
// Study study = catalogManager.getJobManager().getStudy(job, sessionId);
// catalogManager.getJobManager().setStatus(study.getFqn(), job.getId(), jobStatus.getName(), jobStatus.getMessage(), sessionId);
// } else {
// logger.error("This code should never be executed.");
// throw new CatalogException("Job status = null");
// }
// }
// @Deprecated
// public void postProcessJob(Job job) throws CatalogException, IOException {
// Path path = Paths.get(this.tmpOutDirPath.toString(), JOB_STATUS_FILE);
// logger.info("POST PROCESS: {}", path.toUri());
// Job.JobStatus jobStatus = objectMapper.reader(Job.JobStatus.class).readValue(path.toFile());
// if (jobStatus != null) {
// if (jobStatus.getName().equalsIgnoreCase(Job.JobStatus.DONE)) {
// jobStatus.setName(Job.JobStatus.READY);
// } else if (jobStatus.getName().equalsIgnoreCase(Job.JobStatus.ERROR)) {
// jobStatus.setName(Job.JobStatus.ERROR);
// } else {
// logger.error("This block should never be executed. Accepted status in job.status file are DONE and ERROR");
// jobStatus.setName(Job.JobStatus.ERROR);
// }
// ObjectMap params = new ObjectMap(CatalogJobDBAdaptor.QueryParams.STATUS.key(), jobStatus);
// catalogManager.getJobManager().update(job.getId(), params, new QueryOptions(), sessionId);
// // Delete job.status file
// ioManager.deleteFile(path.toUri());
// } else {
// logger.error("This code should never be executed.");
// throw new CatalogException("Job status = null");
// }
// }
// @Deprecated
// public void postProcessJob(Job job, boolean jobFailed) throws CatalogException {
// String type = job.getAttributes().containsKey(Job.TYPE) ?
// job.getAttributes().get(Job.TYPE).toString() : Job.Type.ANALYSIS.toString();
// switch(Job.Type.valueOf(type)) {
// case INDEX:
// final StorageETLResult storageETLResult = readStorageETLResult(job.getId());
// postProcessIndexJob(job, storageETLResult, null, sessionId);
// break;
// case COHORT_STATS:
// List<Integer> cohortIds = new ObjectMap(job.getAttributes()).getAsIntegerList("cohortIds");
// ObjectMap updateParams = new ObjectMap(CatalogCohortDBAdaptor.QueryParams.STATUS_NAME.key(), jobFailed
// ? Cohort.CohortStatus.INVALID : Cohort.CohortStatus.READY);
// for (Integer cohortId : cohortIds) {
// catalogManager.modifyCohort(cohortId, updateParams, new QueryOptions(), sessionId);
// }
// break;
// case ANALYSIS:
// break;
// default:
// break;
// }
// }
//
// public void saveStorageResult(Job job, StorageETLResult storageETLResult) throws CatalogException {
// if (storageETLResult != null) {
// catalogManager.modifyJob(job.getId(), new ObjectMap("attributes", new ObjectMap("storageETLResult", storageETLResult)),
// sessionId);
// }
// }
//
// public StorageETLResult readStorageETLResult(long jobId) throws CatalogException {
// Object object = catalogManager.getJob(jobId, null, sessionId).first().getAttributes().get("storageETLResult");
// final StorageETLResult storageETLResult;
// try {
// if (object != null) {
// storageETLResult = objectMapper.readValue(objectMapper.writeValueAsString(object), StorageETLResult.class);
// } else {
// storageETLResult = null;
// }
// } catch (IOException e) {
// throw new CatalogException(e);
// }
// return storageETLResult;
// }
//
// public void postProcessIndexJob(Job job, StorageETLResult storageETLResult, Exception e, String sessionId) throws CatalogException {
// boolean jobFailed = storageETLResult == null || storageETLResult.getLoadError() != null || storageETLResult.getTransformError()
// != null;
//
// Long indexedFileId = ((Number) job.getAttributes().get(Job.INDEXED_FILE_ID)).longValue();
// File indexedFile = catalogManager.getFile(indexedFileId, sessionId).first();
// final FileIndex index;
//
// boolean transformedSuccess = storageETLResult != null && storageETLResult.isTransformExecuted()
// && storageETLResult.getTransformError() == null;
// boolean loadedSuccess = storageETLResult != null && storageETLResult.isLoadExecuted() && storageETLResult.getLoadError() == null;
//
// if (indexedFile.getIndex() != null) {
// index = indexedFile.getIndex();
// switch (index.getStatus().getName()) {
// case FileIndex.IndexStatus.NONE:
// case FileIndex.IndexStatus.TRANSFORMED:
// logger.warn("Unexpected index status. Expected "
// + FileIndex.IndexStatus.TRANSFORMING + ", "
// + FileIndex.IndexStatus.LOADING + " or "
// + FileIndex.IndexStatus.INDEXING
// + " and got " + index.getStatus());
// case FileIndex.IndexStatus.READY: //Do not show warn message when index status is READY.
// break;
// case FileIndex.IndexStatus.TRANSFORMING:
// if (jobFailed) {
// logger.warn("Job failed. Restoring status from " +
// FileIndex.IndexStatus.TRANSFORMING + " to " + FileIndex.IndexStatus.NONE);
// index.getStatus().setName(FileIndex.IndexStatus.NONE);
// } else {
// index.getStatus().setName(FileIndex.IndexStatus.TRANSFORMED);
// }
// break;
// case FileIndex.IndexStatus.LOADING:
// if (jobFailed) {
// logger.warn("Job failed. Restoring status from " +
// FileIndex.IndexStatus.LOADING + " to " + FileIndex.IndexStatus.TRANSFORMED);
// index.getStatus().setName(FileIndex.IndexStatus.TRANSFORMED);
// } else {
// index.getStatus().setName(FileIndex.IndexStatus.READY);
// }
// break;
// case FileIndex.IndexStatus.INDEXING:
// if (jobFailed) {
// String newStatus;
// // If transform was executed, restore status to Transformed.
// if (transformedSuccess) {
// newStatus = FileIndex.IndexStatus.TRANSFORMED;
// } else {
// newStatus = FileIndex.IndexStatus.NONE;
// }
// logger.warn("Job failed. Restoring status from " +
// FileIndex.IndexStatus.INDEXING + " to " + newStatus);
// index.getStatus().setName(newStatus);
// } else {
// index.getStatus().setName(FileIndex.IndexStatus.READY);
// }
// break;
// }
// } else {
// index = new FileIndex(job.getUserId(), job.getCreationDate(), new FileIndex.IndexStatus(FileIndex.IndexStatus.READY),
// job.getId(),
// new HashMap<>());
// logger.warn("Expected INDEX object on the indexed file " +
// "{ id:" + indexedFile.getId() + ", path:\"" + indexedFile.getPath() + "\"}");
// }
//
// if (transformedSuccess) {
// FileMetadataReader.get(catalogManager).updateVariantFileStats(job, sessionId);
// }
//
// catalogManager.modifyFile(indexedFileId, new ObjectMap("index", index), sessionId); //Modify status
// boolean calculateStats = Boolean.parseBoolean(job.getAttributes()
// .getOrDefault(VariantStorageManager.Options.CALCULATE_STATS.key(),
// VariantStorageManager.Options.CALCULATE_STATS.defaultValue()).toString());
//
// if (index.getStatus().getName().equals(FileIndex.IndexStatus.READY) && calculateStats) {
// QueryResult<Cohort> queryResult = catalogManager.getAllCohorts(catalogManager.getStudyIdByJobId(job.getId()),
// new Query(CatalogCohortDBAdaptor.QueryParams.NAME.key(), StudyEntry.DEFAULT_COHORT), new QueryOptions(), sessionId);
// if (queryResult.getNumResults() != 0) {
// logger.debug("Default cohort status set to READY");
// Cohort defaultCohort = queryResult.first();
// catalogManager.modifyCohort(defaultCohort.getId(),
// new ObjectMap(CatalogCohortDBAdaptor.QueryParams.STATUS_NAME.key(), Cohort.CohortStatus.READY),
// new QueryOptions(), sessionId);
// }
// }
// }
}
| 49.416486 | 140 | 0.594267 |
c1a9f9d34c7196e2c2c292956c3b35e6b3652f8b | 1,088 | package com.yarashevich.kiryl.ipd;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class ExampleMaterialAboutFragmentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example_material_about_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, ExampleMaterialAboutFragment.newInstance(new ExampleMaterialAboutFragment()))
.commit();
setTitle("Информация");
if (NavUtils.getParentActivityName(this) != null) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
}
| 32.969697 | 118 | 0.700368 |
3525b25f6f28751bdf5a1d75e97d43750532e748 | 678 | package org.jtrim2.cache;
/**
* @see GenericReference#getNoReference()
*/
final class NoVolatileReference<ReferentType>
implements VolatileReference<ReferentType> {
private static final NoVolatileReference<?> INSTANCE
= new NoVolatileReference<>();
@SuppressWarnings("unchecked")
public static <V> NoVolatileReference<V> getInstance() {
return (NoVolatileReference<V>) INSTANCE;
}
private NoVolatileReference() {
}
@Override
public ReferentType get() {
return null;
}
@Override
public void clear() {
}
@Override
public String toString() {
return "NoReference";
}
}
| 19.941176 | 60 | 0.644543 |
508fe08c6e6d11553066d6fb6b6f3d742cfe46da | 894 | package com.domain.food.consts;
import com.domain.food.config.BusinessException;
import lombok.Getter;
/**
* 错误码
*/
@Getter
public enum ErrorCode {
OK(200, "业务执行成功"),
BAD(500, "服务器错误"),
ILLEGAL_ARGUMENTS(1000, "参数错误"),
CONDITION_CHECK(1001, "业务检查未通过"),
/*------------------ 登陆错误 5000 - 5010 ------------------*/
LOGIN_USER_NOT_LOGIN(5000, "用户未登录"),
LOGIN_USER_NOT_EXISTS(5001, "用户不存在"),
LOGIN_PASSWORD_ERROR(5002, "密码错误"),
/*------------------ 文件上传错误 5030 - 5040 ------------------*/
UPLOAD_IMAGE_UNSUPPORTED_SUFFIX(5030, "图片格式不支持"),
;
int code;
String msg;
ErrorCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 抛出异常
*
* @param ext 扩展信息
* @return
*/
public void shutdown(String... ext) {
throw new BusinessException(this, ext);
}
}
| 19.866667 | 68 | 0.543624 |
a62bbec27f2d06d9bfdcb04a459379face8500c0 | 2,404 | package algs.coding_jam;
/*
A string S of lowercase letters is given. We want to partition this
string into as many parts as possible so that each letter appears
in at most one part, and return a list of integers representing the
size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Note:
S will have length in range [1, 500].
S will consist of lowercase letters ('a' to 'z') only.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<Integer> partitionLabels(String S) {
int[] mins = new int['z'-'a'+1];
int[] maxs = new int['z'-'a'+1];
List<Integer> result = new ArrayList<>();
for (int i = 0; i < S.length(); i++)
{
int j = S.charAt(i)-'a';
if (mins[j] == 0)
mins[j] = i+1;
maxs[j] = i+1;
}
Byte[] idx = new Byte[mins.length];
for (byte i = 0; i < mins.length; i++)
idx[i] = i;
Arrays.sort(idx, (a, b) -> mins[a] - mins[b]);
int i = 0;
while (i < mins.length && mins[idx[i]] == 0)
i++;
for (int j = i+1; i < mins.length; i = j, j = i+1)
{
int m = maxs[idx[i]];
while (j < mins.length && mins[idx[j]] <= m)
{
m = Math.max(m, maxs[idx[j]]);
j++;
}
result.add(m-mins[idx[i]]+1);
}
return result;
}
////
public List<Integer> partitionLabels2(String S) {
int[] last = new int[26];
for (int i = 0; i < S.length(); ++i)
last[S.charAt(i) - 'a'] = i;
int j = 0;
int anchor = 0;
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < S.length(); ++i)
{
j = Math.max(j, last[S.charAt(i) - 'a']);
if (i == j)
{
ans.add(i - anchor + 1);
anchor = i + 1;
}
}
return ans;
}
} | 24.783505 | 98 | 0.473794 |
082240b0f6b4588c0d734ae260f16ddfcc0907ae | 1,998 | package com.example.schemainfer.protogen.rules;
import com.example.schemainfer.protogen.utils.CommonUtils;
import com.example.schemainfer.protogen.utils.Constants ;
import org.apache.commons.lang3.StringUtils;
import java.text.DecimalFormat;
public class InferJsonDatatype {
public static String determineInferDatatype(String instr) {
if (instr != null && !instr.isEmpty()) {
if (CommonUtils.isBoolean(instr)) {
return Constants.DATATYPES.Boolean.name();
} else if (CommonUtils.isAlpha3(instr)) {
return Constants.DATATYPES.String.name();
} else if (StringUtils.isNumeric(instr)) {
return Constants.DATATYPES.Integer.name();
} else if (CommonUtils.isDouble(instr)) {
return Constants.DATATYPES.Double.name();
} else {
return CommonUtils.isFloat(instr) ? Constants.DATATYPES.Float.name() : Constants.DATATYPES.Null.name();
}
} else {
return null;
}
}
public static String determineProtoDatatype(String datatype1, String datatype2) {
if (datatype1 != null && !datatype1.isEmpty()) {
if (CommonUtils.isBoolean(datatype1)) {
return Constants.DATATYPES.Boolean.name();
} else if (CommonUtils.isAlpha3(datatype1)) {
return Constants.DATATYPES.String.name();
} else if (StringUtils.isNumeric(datatype1)) {
return Constants.DATATYPES.Integer.name();
} else if (CommonUtils.isDouble(datatype1)) {
return Constants.DATATYPES.Double.name();
} else {
return CommonUtils.isFloat(datatype1) ? Constants.DATATYPES.Float.name() : Constants.DATATYPES.Null.name();
}
} else {
return null;
}
}
public static boolean precisionGreatherThan3(String s) {
return s.replaceAll(".*\\.", "").length() > 3;
}
}
| 38.423077 | 123 | 0.607107 |
d4e752391e4e734afe673514b2370e9ea68afd11 | 860 | package net.kodar.restaurantapi.business.transformer.param.menuitem;
import org.springframework.stereotype.Component;
import net.kodar.restaurantapi.business.transformer.param.ParamTransformer;
import net.kodar.restaurantapi.data.entities.MenuItem;
import net.kodar.restaurantapi.presentation.param.MenuItemParam;
@Component
public class MenuItemParamTransformer implements ParamTransformer<MenuItemParam, MenuItem, MenuItem> {
@Override
public MenuItem apply(MenuItemParam param, MenuItem entity) {
if (entity == null) {
entity = new MenuItem();
entity.setId(param.getId());
}
entity.setCode(param.getCode());
entity.setDescription(param.getDescription());
entity.setName(param.getName());
entity.setLocked(param.isLocked());
entity.setMeasure(param.getMeasure());
entity.setPrice(param.getPrice());
return entity;
}
}
| 28.666667 | 102 | 0.777907 |
4d29a1081475a48a2f2a5a0c12dc11a8ae6f685f | 598 | // Copyright (c) Committed Software 2018, [email protected]
package uk.gov.dstl.baleen.graph.value;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class MinValueStrategyTest {
@Test
public void aggregateTest() {
Min strategy = new Min();
assertFalse(strategy.aggregate(ImmutableList.of()).isPresent());
assertEquals(0, strategy.aggregate(ImmutableList.of(0)).get());
assertEquals(0, strategy.aggregate(ImmutableList.of(0, 10, 9, 3)).get());
}
}
| 28.47619 | 77 | 0.747492 |
dd606ced80eebf1426e58b2da3a3d93eafb0d0e7 | 4,700 | /*
* Copyright (c) 2015 Spotify AB.
*
* 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.spotify.helios.client;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.spotify.helios.common.Clock;
import org.hamcrest.CoreMatchers;
import org.joda.time.Instant;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Matchers;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class RetryingRequestDispatcherTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
private final RequestDispatcher delegate = mock(RequestDispatcher.class);
private final Clock clock = mock(Clock.class);
private RetryingRequestDispatcher dispatcher;
@Before
public void setUp() {
dispatcher = RetryingRequestDispatcher.forDispatcher(delegate)
.setExecutor(newSingleThreadScheduledExecutor())
.setClock(clock)
.setDelayOnFailure(0, SECONDS)
.build();
}
@Test
public void testSuccess() throws Exception {
when(delegate.request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any()))
.thenReturn(Futures.<Response>immediateFuture(null));
when(clock.now()).thenReturn(new Instant(0));
dispatcher.request(new URI("http://example.com"), "GET", null,
Collections.<String, List<String>>emptyMap());
// Verify the delegate was only called once if it returns successfully on the first try
verify(delegate, times(1)).request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any());
}
@Test
public void testSuccessOnRetry() throws Exception {
when(delegate.request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any()))
.thenReturn(Futures.<Response>immediateFailedFuture(new IOException()))
.thenReturn(Futures.<Response>immediateFuture(null));
when(clock.now()).thenReturn(new Instant(0));
dispatcher.request(new URI("http://example.com"), "GET", null,
Collections.<String, List<String>>emptyMap());
// Verify the delegate was called twice if it returns successfully on the second try before the
// deadline
verify(delegate, times(2)).request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any());
}
@Test
public void testFailureOnTimeout() throws Exception {
when(delegate.request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any()))
.thenReturn(Futures.<Response>immediateFailedFuture(new IOException()))
.thenReturn(Futures.<Response>immediateFuture(null));
when(clock.now()).thenReturn(new Instant(0)).thenReturn(new Instant(80000));
final ListenableFuture<Response> future = dispatcher.request(
new URI("http://example.com"), "GET", null, Collections.<String, List<String>>emptyMap());
// Verify the delegate was only called once if it failed on the first try and the deadline
// has passed before the second try was attempted.
verify(delegate, times(1)).request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any());
exception.expect(ExecutionException.class);
exception.expectCause(CoreMatchers.any(IOException.class));
future.get();
}
}
| 37.903226 | 99 | 0.7 |
1c5f49388d8536f0667c28d72ab7ab538fc70eda | 1,564 | /*
* Tencent is pleased to support the open source community by making Polaris available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.polaris.api.rpc;
import com.tencent.polaris.api.pojo.ServiceEventKey;
import com.tencent.polaris.api.pojo.ServiceInstances;
import com.tencent.polaris.api.pojo.ServiceRule;
import java.util.Map;
/**
* 获取资源的应答
*/
public class GetResourcesResponse {
private final Map<ServiceEventKey, ServiceInstances> services;
private final Map<ServiceEventKey, ServiceRule> rules;
public GetResourcesResponse(
Map<ServiceEventKey, ServiceInstances> services, Map<ServiceEventKey, ServiceRule> rules) {
this.services = services;
this.rules = rules;
}
public Map<ServiceEventKey, ServiceInstances> getServices() {
return services;
}
public Map<ServiceEventKey, ServiceRule> getRules() {
return rules;
}
}
| 32.583333 | 104 | 0.713555 |
0ea430626e6251704bb9385c06b94ae8414007fb | 58,176 | package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.easing.Expo;
import it.sephiroth.android.library.imagezoom.easing.Linear;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews.RemoteView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.graphics.Point2D;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
// TODO: Auto-generated Javadoc
/**
* Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or
* content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and
* provides various display options such as scaling and tinting.
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
* @attr ref android.R.styleable#ImageView_src
* @attr ref android.R.styleable#ImageView_maxWidth
* @attr ref android.R.styleable#ImageView_maxHeight
* @attr ref android.R.styleable#ImageView_tint
* @attr ref android.R.styleable#ImageView_scaleType
* @attr ref android.R.styleable#ImageView_cropToPadding
*/
@RemoteView
public class AdjustImageViewFreeRotation extends View {
/** The Constant LOG_TAG. */
static final String LOG_TAG = "rotate";
// settable by the client
/** The m uri. */
private Uri mUri;
/** The m resource. */
private int mResource = 0;
/** The m matrix. */
private Matrix mMatrix;
/** The m scale type. */
private ScaleType mScaleType;
/** The m adjust view bounds. */
private boolean mAdjustViewBounds = false;
/** The m max width. */
private int mMaxWidth = Integer.MAX_VALUE;
/** The m max height. */
private int mMaxHeight = Integer.MAX_VALUE;
// these are applied to the drawable
/** The m color filter. */
private ColorFilter mColorFilter;
/** The m alpha. */
private int mAlpha = 255;
/** The m view alpha scale. */
private int mViewAlphaScale = 256;
/** The m color mod. */
private boolean mColorMod = false;
/** The m drawable. */
private Drawable mDrawable = null;
/** The m state. */
private int[] mState = null;
/** The m merge state. */
private boolean mMergeState = false;
/** The m level. */
private int mLevel = 0;
/** The m drawable width. */
private int mDrawableWidth;
/** The m drawable height. */
private int mDrawableHeight;
/** The m draw matrix. */
private Matrix mDrawMatrix = null;
/** The m rotate matrix. */
private Matrix mRotateMatrix = new Matrix();
/** The m flip matrix. */
private Matrix mFlipMatrix = new Matrix();
// Avoid allocations...
/** The m temp src. */
private RectF mTempSrc = new RectF();
/** The m temp dst. */
private RectF mTempDst = new RectF();
/** The m crop to padding. */
private boolean mCropToPadding;
/** The m baseline. */
private int mBaseline = -1;
/** The m baseline align bottom. */
private boolean mBaselineAlignBottom = false;
/** The m have frame. */
private boolean mHaveFrame;
/** The m easing. */
private Easing mEasing = new Expo();
/** View is in the reset state. */
boolean isReset = false;
/** reset animation time. */
int resetAnimTime = 200;
Path mClipPath = new Path();
Path mInversePath = new Path();
Rect mViewDrawRect = new Rect();
Paint mOutlinePaint = new Paint();
Paint mOutlineFill = new Paint();
RectF mDrawRect;
PointF mCenter = new PointF();
Path mLinesPath = new Path();
Paint mLinesPaint = new Paint();
Paint mLinesPaintShadow = new Paint();
Drawable mResizeDrawable;
int handleWidth, handleHeight;
final int grid_rows = 3;
final int grid_cols = 3;
private boolean mEnableFreeRotate;
static Logger logger = LoggerFactory.getLogger( "rotate", LoggerType.ConsoleLoggerType );
/**
* Sets the reset anim duration.
*
* @param value
* the new reset anim duration
*/
public void setResetAnimDuration( int value ) {
resetAnimTime = value;
}
public void setEnableFreeRotate( boolean value ) {
mEnableFreeRotate = value;
}
public boolean isFreeRotateEnabled() {
return mEnableFreeRotate;
}
/**
* The listener interface for receiving onReset events. The class that is interested in processing a onReset event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnResetListener<code> method. When
* the onReset event occurs, that object's appropriate
* method is invoked.
*
* @see OnResetEvent
*/
public interface OnResetListener {
/**
* On reset complete.
*/
void onResetComplete();
}
/** The m reset listener. */
private OnResetListener mResetListener;
/**
* Sets the on reset listener.
*
* @param listener
* the new on reset listener
*/
public void setOnResetListener( OnResetListener listener ) {
mResetListener = listener;
}
/** The Constant sScaleTypeArray. */
@SuppressWarnings("unused")
private static final ScaleType[] sScaleTypeArray = {
ScaleType.MATRIX, ScaleType.FIT_XY, ScaleType.FIT_START, ScaleType.FIT_CENTER, ScaleType.FIT_END, ScaleType.CENTER,
ScaleType.CENTER_CROP, ScaleType.CENTER_INSIDE };
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
*/
public AdjustImageViewFreeRotation( Context context ) {
super( context );
initImageView();
}
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public AdjustImageViewFreeRotation( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public AdjustImageViewFreeRotation( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
initImageView();
}
/**
* Sets the easing.
*
* @param value
* the new easing
*/
public void setEasing( Easing value ) {
mEasing = value;
}
int mOutlinePaintAlpha, mOutlineFillAlpha, mLinesAlpha, mLinesShadowAlpha;
/**
* Inits the image view.
*/
private void initImageView() {
mMatrix = new Matrix();
mScaleType = ScaleType.FIT_CENTER;
Context context = getContext();
int highlight_color = context.getResources().getColor( R.color.feather_rotate_highlight_stroke_color );
int highlight_stroke_internal_color = context.getResources().getColor( R.color.feather_rotate_highlight_grid_stroke_color );
int highlight_stroke_internal_width = context.getResources()
.getInteger( R.integer.feather_rotate_highlight_grid_stroke_width );
int highlight_outside_color = context.getResources().getColor( R.color.feather_rotate_highlight_outside );
int highlight_stroke_width = context.getResources().getInteger( R.integer.feather_rotate_highlight_stroke_width );
mOutlinePaint.setStrokeWidth( highlight_stroke_width );
mOutlinePaint.setStyle( Paint.Style.STROKE );
mOutlinePaint.setAntiAlias( true );
mOutlinePaint.setColor( highlight_color );
mOutlineFill.setStyle( Paint.Style.FILL );
mOutlineFill.setAntiAlias( false );
mOutlineFill.setColor( highlight_outside_color );
mOutlineFill.setDither( false );
try {
ReflectionUtils.invokeMethod( mOutlineFill, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaint.setStrokeWidth( highlight_stroke_internal_width );
mLinesPaint.setAntiAlias( false );
mLinesPaint.setDither( false );
mLinesPaint.setStyle( Paint.Style.STROKE );
mLinesPaint.setColor( highlight_stroke_internal_color );
try {
ReflectionUtils.invokeMethod( mLinesPaint, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaintShadow.setStrokeWidth( highlight_stroke_internal_width );
mLinesPaintShadow.setAntiAlias( true );
mLinesPaintShadow.setColor( Color.BLACK );
mLinesPaintShadow.setStyle( Paint.Style.STROKE );
mLinesPaintShadow.setMaskFilter( new BlurMaskFilter( 2, Blur.NORMAL ) );
mOutlineFillAlpha = mOutlineFill.getAlpha();
mOutlinePaintAlpha = mOutlinePaint.getAlpha();
mLinesAlpha = mLinesPaint.getAlpha();
mLinesShadowAlpha = mLinesPaintShadow.getAlpha();
mOutlinePaint.setAlpha( 0 );
mOutlineFill.setAlpha( 0 );
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
android.content.res.Resources resources = getContext().getResources();
mResizeDrawable = resources.getDrawable( R.drawable.feather_highlight_crop_handle );
double w = mResizeDrawable.getIntrinsicWidth();
double h = mResizeDrawable.getIntrinsicHeight();
handleWidth = (int) Math.ceil( w / 2.0 );
handleHeight = (int) Math.ceil( h / 2.0 );
}
/*
* (non-Javadoc)
*
* @see android.view.View#verifyDrawable(android.graphics.drawable.Drawable)
*/
@Override
protected boolean verifyDrawable( Drawable dr ) {
return mDrawable == dr || super.verifyDrawable( dr );
}
/*
* (non-Javadoc)
*
* @see android.view.View#invalidateDrawable(android.graphics.drawable.Drawable)
*/
@Override
public void invalidateDrawable( Drawable dr ) {
if ( dr == mDrawable ) {
/*
* we invalidate the whole view in this case because it's very hard to know where the drawable actually is. This is made
* complicated because of the offsets and transformations that can be applied. In theory we could get the drawable's bounds
* and run them through the transformation and offsets, but this is probably not worth the effort.
*/
invalidate();
} else {
super.invalidateDrawable( dr );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSetAlpha(int)
*/
@Override
protected boolean onSetAlpha( int alpha ) {
if ( getBackground() == null ) {
int scale = alpha + ( alpha >> 7 );
if ( mViewAlphaScale != scale ) {
mViewAlphaScale = scale;
mColorMod = true;
applyColorMod();
}
return true;
}
return false;
}
private boolean isDown;
private double originalAngle;
private PointF getCenter() {
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
return new PointF( (float) vwidth / 2, (float) vheight / 2 );
}
private RectF getViewRect() {
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
return new RectF( 0, 0, vwidth, vheight );
}
private RectF getImageRect() {
return new RectF( 0, 0, mDrawableWidth, mDrawableHeight );
}
private void onTouchStart( float x, float y ) {
isDown = true;
PointF current = new PointF( x, y );
PointF center = getCenter();
double currentAngle = getRotationFromMatrix( mRotateMatrix );
originalAngle = Point2D.angle360( currentAngle + Point2D.angleBetweenPoints( center, current ) );
if ( mFadeHandlerStarted ) {
fadeinGrid( 300 );
} else {
fadeinOutlines( 600 );
}
}
private void onTouchMove( float x, float y ) {
if ( isDown ) {
PointF current = new PointF( x, y );
PointF center = getCenter();
float angle = (float) Point2D.angle360( originalAngle - Point2D.angleBetweenPoints( center, current ) );
logger.log( "ANGLE: " + angle + " .. " + getAngle90( angle ) );
setImageRotation( angle, false );
mRotation = angle;
invalidate();
}
}
private void setImageRotation( double angle, boolean invert ) {
PointF center = getCenter();
Matrix tempMatrix = new Matrix( mDrawMatrix );
RectF src = getImageRect();
RectF dst = getViewRect();
tempMatrix.setRotate( (float) angle, center.x, center.y );
tempMatrix.mapRect( src );
tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) );
float[] scale = getMatrixScale( tempMatrix );
float fScale = Math.min( scale[0], scale[1] );
if ( invert ) {
mRotateMatrix.setRotate( (float) angle, center.x, center.y );
mRotateMatrix.postScale( fScale, fScale, center.x, center.y );
} else {
mRotateMatrix.setScale( fScale, fScale, center.x, center.y );
mRotateMatrix.postRotate( (float) angle, center.x, center.y );
}
}
private void onTouchUp( float x, float y ) {
isDown = false;
setImageRotation( mRotation, true );
invalidate();
fadeoutGrid( 300 );
}
@Override
public boolean onTouchEvent( MotionEvent event ) {
if ( !mEnableFreeRotate ) return true;
if ( isRunning() ) return true;
int action = event.getAction() & MotionEvent.ACTION_MASK;
float x = event.getX();
float y = event.getY();
if ( action == MotionEvent.ACTION_DOWN ) {
onTouchStart( x, y );
} else if ( action == MotionEvent.ACTION_MOVE ) {
onTouchMove( x, y );
} else if ( action == MotionEvent.ACTION_UP ) {
onTouchUp( x, y );
} else
return true;
return true;
}
private double getRotationFromMatrix( Matrix matrix ) {
float[] pts = { 0, 0, 0, -100 };
matrix.mapPoints( pts );
double angle = Point2D.angleBetweenPoints( pts[0], pts[1], pts[2], pts[3], 0 );
return -angle;
}
/**
* Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
*
* @param adjustViewBounds
* Whether to adjust the bounds of this view to presrve the original aspect ratio of the drawable
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
*/
public void setAdjustViewBounds( boolean adjustViewBounds ) {
mAdjustViewBounds = adjustViewBounds;
if ( adjustViewBounds ) {
setScaleType( ScaleType.FIT_CENTER );
}
}
/**
* An optional argument to supply a maximum width for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been set
* to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.
*
* <p>
* Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image
* to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)}
* to determine how to fit the image within the bounds.
* </p>
*
* @param maxWidth
* maximum width for this view
*
* @attr ref android.R.styleable#ImageView_maxWidth
*/
public void setMaxWidth( int maxWidth ) {
mMaxWidth = maxWidth;
}
/**
* An optional argument to supply a maximum height for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been
* set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.
*
* <p>
* Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image
* to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)}
* to determine how to fit the image within the bounds.
* </p>
*
* @param maxHeight
* maximum height for this view
*
* @attr ref android.R.styleable#ImageView_maxHeight
*/
public void setMaxHeight( int maxHeight ) {
mMaxHeight = maxHeight;
}
/**
* Return the view's drawable, or null if no drawable has been assigned.
*
* @return the drawable
*/
public Drawable getDrawable() {
return mDrawable;
}
/**
* Sets a drawable as the content of this ImageView.
*
* <p class="note">
* This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using
*
* @param resId
* the resource identifier of the the drawable {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead.
* </p>
* @attr ref android.R.styleable#ImageView_src
*/
public void setImageResource( int resId ) {
if ( mUri != null || mResource != resId ) {
updateDrawable( null );
mResource = resId;
mUri = null;
resolveUri();
requestLayout();
invalidate();
}
}
/**
* Sets the content of this ImageView to the specified Uri.
*
* <p class="note">
* This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using
*
* @param uri
* The Uri of an image {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead.
* </p>
*/
public void setImageURI( Uri uri ) {
if ( mResource != 0 || ( mUri != uri && ( uri == null || mUri == null || !uri.equals( mUri ) ) ) ) {
updateDrawable( null );
mResource = 0;
mUri = uri;
resolveUri();
requestLayout();
invalidate();
}
}
/**
* Sets a drawable as the content of this ImageView.
*
* @param drawable
* The drawable to set
*/
public void setImageDrawable( Drawable drawable ) {
if ( mDrawable != drawable ) {
mResource = 0;
mUri = null;
int oldWidth = mDrawableWidth;
int oldHeight = mDrawableHeight;
updateDrawable( drawable );
if ( oldWidth != mDrawableWidth || oldHeight != mDrawableHeight ) {
requestLayout();
}
invalidate();
}
}
/**
* Sets a Bitmap as the content of this ImageView.
*
* @param bm
* The bitmap to set
*/
public void setImageBitmap( Bitmap bm ) {
// if this is used frequently, may handle bitmaps explicitly
// to reduce the intermediate drawable object
setImageDrawable( new BitmapDrawable( getContext().getResources(), bm ) );
}
/**
* Sets the image state.
*
* @param state
* the state
* @param merge
* the merge
*/
public void setImageState( int[] state, boolean merge ) {
mState = state;
mMergeState = merge;
if ( mDrawable != null ) {
refreshDrawableState();
resizeFromDrawable();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#setSelected(boolean)
*/
@Override
public void setSelected( boolean selected ) {
super.setSelected( selected );
resizeFromDrawable();
}
/**
* Sets the image level, when it is constructed from a {@link android.graphics.drawable.LevelListDrawable}.
*
* @param level
* The new level for the image.
*/
public void setImageLevel( int level ) {
mLevel = level;
if ( mDrawable != null ) {
mDrawable.setLevel( level );
resizeFromDrawable();
}
}
/**
* Options for scaling the bounds of an image to the bounds of this view.
*/
public enum ScaleType {
/**
* Scale using the image matrix when drawing. The image matrix can be set using {@link ImageView#setImageMatrix(Matrix)}. From
* XML, use this syntax: <code>android:scaleType="matrix"</code>.
*/
MATRIX( 0 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#FILL}. From XML, use this syntax: <code>android:scaleType="fitXY"</code>.
*/
FIT_XY( 1 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#START}. From XML, use this syntax: <code>android:scaleType="fitStart"</code>
* .
*/
FIT_START( 2 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#CENTER}. From XML, use this syntax:
* <code>android:scaleType="fitCenter"</code>.
*/
FIT_CENTER( 3 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#END}. From XML, use this syntax: <code>android:scaleType="fitEnd"</code>.
*/
FIT_END( 4 ),
/**
* Center the image in the view, but perform no scaling. From XML, use this syntax: <code>android:scaleType="center"</code>.
*/
CENTER( 5 ),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will
* be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view.
* From XML, use this syntax: <code>android:scaleType="centerCrop"</code>.
*/
CENTER_CROP( 6 ),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will
* be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view.
* From XML, use this syntax: <code>android:scaleType="centerInside"</code>.
*/
CENTER_INSIDE( 7 );
/**
* Instantiates a new scale type.
*
* @param ni
* the ni
*/
ScaleType( int ni ) {
nativeInt = ni;
}
/** The native int. */
final int nativeInt;
}
/**
* Controls how the image should be resized or moved to match the size of this ImageView.
*
* @param scaleType
* The desired scaling mode.
*
* @attr ref android.R.styleable#ImageView_scaleType
*/
public void setScaleType( ScaleType scaleType ) {
if ( scaleType == null ) {
throw new NullPointerException();
}
if ( mScaleType != scaleType ) {
mScaleType = scaleType;
setWillNotCacheDrawing( mScaleType == ScaleType.CENTER );
requestLayout();
invalidate();
}
}
/**
* Return the current scale type in use by this ImageView.
*
* @return the scale type
* @see ImageView.ScaleType
* @attr ref android.R.styleable#ImageView_scaleType
*/
public ScaleType getScaleType() {
return mScaleType;
}
/**
* Return the view's optional matrix. This is applied to the view's drawable when it is drawn. If there is not matrix, this
* method will return null. Do not change this matrix in place. If you want a different matrix applied to the drawable, be sure
* to call setImageMatrix().
*
* @return the image matrix
*/
public Matrix getImageMatrix() {
return mMatrix;
}
/**
* Sets the image matrix.
*
* @param matrix
* the new image matrix
*/
public void setImageMatrix( Matrix matrix ) {
// collaps null and identity to just null
if ( matrix != null && matrix.isIdentity() ) {
matrix = null;
}
// don't invalidate unless we're actually changing our matrix
if ( matrix == null && !mMatrix.isIdentity() || matrix != null && !mMatrix.equals( matrix ) ) {
mMatrix.set( matrix );
configureBounds();
invalidate();
}
}
/**
* Resolve uri.
*/
private void resolveUri() {
if ( mDrawable != null ) {
return;
}
Resources rsrc = getResources();
if ( rsrc == null ) {
return;
}
Drawable d = null;
if ( mResource != 0 ) {
try {
d = rsrc.getDrawable( mResource );
} catch ( Exception e ) {
Log.w( LOG_TAG, "Unable to find resource: " + mResource, e );
// Don't try again.
mUri = null;
}
} else if ( mUri != null ) {
String scheme = mUri.getScheme();
if ( ContentResolver.SCHEME_ANDROID_RESOURCE.equals( scheme ) ) {
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) || ContentResolver.SCHEME_FILE.equals( scheme ) ) {
try {
d = Drawable.createFromStream( getContext().getContentResolver().openInputStream( mUri ), null );
} catch ( Exception e ) {
Log.w( LOG_TAG, "Unable to open content: " + mUri, e );
}
} else {
d = Drawable.createFromPath( mUri.toString() );
}
if ( d == null ) {
System.out.println( "resolveUri failed on bad bitmap uri: " + mUri );
// Don't try again.
mUri = null;
}
} else {
return;
}
updateDrawable( d );
}
/*
* (non-Javadoc)
*
* @see android.view.View#onCreateDrawableState(int)
*/
@Override
public int[] onCreateDrawableState( int extraSpace ) {
if ( mState == null ) {
return super.onCreateDrawableState( extraSpace );
} else if ( !mMergeState ) {
return mState;
} else {
return mergeDrawableStates( super.onCreateDrawableState( extraSpace + mState.length ), mState );
}
}
/**
* Update drawable.
*
* @param d
* the d
*/
private void updateDrawable( Drawable d ) {
if ( mDrawable != null ) {
mDrawable.setCallback( null );
unscheduleDrawable( mDrawable );
}
mDrawable = d;
if ( d != null ) {
d.setCallback( this );
if ( d.isStateful() ) {
d.setState( getDrawableState() );
}
d.setLevel( mLevel );
mDrawableWidth = d.getIntrinsicWidth();
mDrawableHeight = d.getIntrinsicHeight();
applyColorMod();
configureBounds();
} else {
mDrawableWidth = mDrawableHeight = -1;
}
}
/**
* Resize from drawable.
*/
private void resizeFromDrawable() {
Drawable d = mDrawable;
if ( d != null ) {
int w = d.getIntrinsicWidth();
if ( w < 0 ) w = mDrawableWidth;
int h = d.getIntrinsicHeight();
if ( h < 0 ) h = mDrawableHeight;
if ( w != mDrawableWidth || h != mDrawableHeight ) {
mDrawableWidth = w;
mDrawableHeight = h;
requestLayout();
}
}
}
/** The Constant sS2FArray. */
private static final Matrix.ScaleToFit[] sS2FArray = {
Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END };
/**
* Scale type to scale to fit.
*
* @param st
* the st
* @return the matrix. scale to fit
*/
private static Matrix.ScaleToFit scaleTypeToScaleToFit( ScaleType st ) {
// ScaleToFit enum to their corresponding Matrix.ScaleToFit values
return sS2FArray[st.nativeInt - 1];
}
/*
* (non-Javadoc)
*
* @see android.view.View#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
if ( changed ) {
mHaveFrame = true;
double oldRotation = mRotation;
boolean flip_h = getHorizontalFlip();
boolean flip_v = getVerticalFlip();
configureBounds();
if ( flip_h || flip_v ) {
flip( flip_h, flip_v );
}
if ( oldRotation != 0 ) {
setImageRotation( oldRotation, false );
mRotation = oldRotation;
}
invalidate();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
resolveUri();
int w;
int h;
// Desired aspect ratio of the view's contents (not including padding)
float desiredAspect = 0.0f;
// We are allowed to change the view's width
boolean resizeWidth = false;
// We are allowed to change the view's height
boolean resizeHeight = false;
final int widthSpecMode = MeasureSpec.getMode( widthMeasureSpec );
final int heightSpecMode = MeasureSpec.getMode( heightMeasureSpec );
if ( mDrawable == null ) {
// If no drawable, its intrinsic size is 0.
mDrawableWidth = -1;
mDrawableHeight = -1;
w = h = 0;
} else {
w = mDrawableWidth;
h = mDrawableHeight;
if ( w <= 0 ) w = 1;
if ( h <= 0 ) h = 1;
// We are supposed to adjust view bounds to match the aspect
// ratio of our drawable. See if that is possible.
if ( mAdjustViewBounds ) {
resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
desiredAspect = (float) w / (float) h;
}
}
int pleft = getPaddingLeft();
int pright = getPaddingRight();
int ptop = getPaddingTop();
int pbottom = getPaddingBottom();
int widthSize;
int heightSize;
if ( resizeWidth || resizeHeight ) {
/*
* If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at
* least one dimension.
*/
// Get the max possible width given our constraints
widthSize = resolveAdjustedSize( w + pleft + pright, mMaxWidth, widthMeasureSpec );
// Get the max possible height given our constraints
heightSize = resolveAdjustedSize( h + ptop + pbottom, mMaxHeight, heightMeasureSpec );
if ( desiredAspect != 0.0f ) {
// See what our actual aspect ratio is
float actualAspect = (float) ( widthSize - pleft - pright ) / ( heightSize - ptop - pbottom );
if ( Math.abs( actualAspect - desiredAspect ) > 0.0000001 ) {
boolean done = false;
// Try adjusting width to be proportional to height
if ( resizeWidth ) {
int newWidth = (int) ( desiredAspect * ( heightSize - ptop - pbottom ) ) + pleft + pright;
if ( newWidth <= widthSize ) {
widthSize = newWidth;
done = true;
}
}
// Try adjusting height to be proportional to width
if ( !done && resizeHeight ) {
int newHeight = (int) ( ( widthSize - pleft - pright ) / desiredAspect ) + ptop + pbottom;
if ( newHeight <= heightSize ) {
heightSize = newHeight;
}
}
}
}
} else {
/*
* We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just
* measure in the normal way.
*/
w += pleft + pright;
h += ptop + pbottom;
w = Math.max( w, getSuggestedMinimumWidth() );
h = Math.max( h, getSuggestedMinimumHeight() );
widthSize = resolveSize( w, widthMeasureSpec );
heightSize = resolveSize( h, heightMeasureSpec );
}
setMeasuredDimension( widthSize, heightSize );
}
/**
* Resolve adjusted size.
*
* @param desiredSize
* the desired size
* @param maxSize
* the max size
* @param measureSpec
* the measure spec
* @return the int
*/
private int resolveAdjustedSize( int desiredSize, int maxSize, int measureSpec ) {
int result = desiredSize;
int specMode = MeasureSpec.getMode( measureSpec );
int specSize = MeasureSpec.getSize( measureSpec );
switch ( specMode ) {
case MeasureSpec.UNSPECIFIED:
/*
* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves.
*/
result = Math.min( desiredSize, maxSize );
break;
case MeasureSpec.AT_MOST:
// Parent says we can be as big as we want, up to specSize.
// Don't be larger than specSize, and don't be larger than
// the max size imposed on ourselves.
result = Math.min( Math.min( desiredSize, specSize ), maxSize );
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
/**
* Configure bounds.
*/
private void configureBounds() {
if ( mDrawable == null || !mHaveFrame ) {
return;
}
int dwidth = mDrawableWidth;
int dheight = mDrawableHeight;
int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
boolean fits = ( dwidth < 0 || vwidth == dwidth ) && ( dheight < 0 || vheight == dheight );
if ( dwidth <= 0 || dheight <= 0 || ScaleType.FIT_XY == mScaleType ) {
/*
* If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view.
*/
mDrawable.setBounds( 0, 0, vwidth, vheight );
mDrawMatrix = null;
} else {
// We need to do the scaling ourself, so have the drawable
// use its native size.
mDrawable.setBounds( 0, 0, dwidth, dheight );
if ( ScaleType.MATRIX == mScaleType ) {
// Use the specified matrix as-is.
if ( mMatrix.isIdentity() ) {
mDrawMatrix = null;
} else {
mDrawMatrix = mMatrix;
}
} else if ( fits ) {
// The bitmap fits exactly, no transform needed.
mDrawMatrix = null;
} else if ( ScaleType.CENTER == mScaleType ) {
// Center bitmap in view, no scaling.
mDrawMatrix = mMatrix;
mDrawMatrix.setTranslate( (int) ( ( vwidth - dwidth ) * 0.5f + 0.5f ), (int) ( ( vheight - dheight ) * 0.5f + 0.5f ) );
} else if ( ScaleType.CENTER_CROP == mScaleType ) {
mDrawMatrix = mMatrix;
float scale;
float dx = 0, dy = 0;
if ( dwidth * vheight > vwidth * dheight ) {
scale = (float) vheight / (float) dheight;
dx = ( vwidth - dwidth * scale ) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = ( vheight - dheight * scale ) * 0.5f;
}
mDrawMatrix.setScale( scale, scale );
mDrawMatrix.postTranslate( (int) ( dx + 0.5f ), (int) ( dy + 0.5f ) );
} else if ( ScaleType.CENTER_INSIDE == mScaleType ) {
mDrawMatrix = mMatrix;
float scale;
float dx;
float dy;
if ( dwidth <= vwidth && dheight <= vheight ) {
scale = 1.0f;
} else {
scale = Math.min( (float) vwidth / (float) dwidth, (float) vheight / (float) dheight );
}
dx = (int) ( ( vwidth - dwidth * scale ) * 0.5f + 0.5f );
dy = (int) ( ( vheight - dheight * scale ) * 0.5f + 0.5f );
mDrawMatrix.setScale( scale, scale );
mDrawMatrix.postTranslate( dx, dy );
} else {
// Generate the required transform.
mTempSrc.set( 0, 0, dwidth, dheight );
mTempDst.set( 0, 0, vwidth, vheight );
mDrawMatrix = mMatrix;
mDrawMatrix.setRectToRect( mTempSrc, mTempDst, scaleTypeToScaleToFit( mScaleType ) );
mCurrentScale = getMatrixScale( mDrawMatrix )[0];
Matrix tempMatrix = new Matrix( mMatrix );
RectF src = new RectF();
RectF dst = new RectF();
src.set( 0, 0, dheight, dwidth );
dst.set( 0, 0, vwidth, vheight );
tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) );
tempMatrix = new Matrix( mDrawMatrix );
tempMatrix.invert( tempMatrix );
float invertScale = getMatrixScale( tempMatrix )[0];
mDrawMatrix.postScale( invertScale, invertScale, vwidth / 2, vheight / 2 );
mRotateMatrix.reset();
mFlipMatrix.reset();
mFlipType = FlipType.FLIP_NONE.nativeInt;
mRotation = 0;
mRotateMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 );
mDrawRect = getImageRect();
mCenter = getCenter();
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#drawableStateChanged()
*/
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
Drawable d = mDrawable;
if ( d != null && d.isStateful() ) {
d.setState( getDrawableState() );
}
}
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
if ( mDrawable == null ) {
return; // couldn't resolve the URI
}
if ( mDrawableWidth == 0 || mDrawableHeight == 0 ) {
return; // nothing to draw (empty bounds)
}
final int mPaddingTop = getPaddingTop();
final int mPaddingLeft = getPaddingLeft();
final int mPaddingBottom = getPaddingBottom();
final int mPaddingRight = getPaddingRight();
if ( mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0 ) {
mDrawable.draw( canvas );
} else {
int saveCount = canvas.getSaveCount();
canvas.save();
if ( mCropToPadding ) {
final int scrollX = getScrollX();
final int scrollY = getScrollY();
canvas.clipRect( scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + getRight() - getLeft() - mPaddingRight,
scrollY + getBottom() - getTop() - mPaddingBottom );
}
canvas.translate( mPaddingLeft, mPaddingTop );
if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix );
if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix );
if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix );
mDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
if ( mEnableFreeRotate ) {
mDrawRect = getImageRect();
getDrawingRect( mViewDrawRect );
mClipPath.reset();
mInversePath.reset();
mLinesPath.reset();
float[] points = new float[] {
mDrawRect.left, mDrawRect.top, mDrawRect.right, mDrawRect.top, mDrawRect.right, mDrawRect.bottom, mDrawRect.left,
mDrawRect.bottom };
Matrix matrix = new Matrix( mDrawMatrix );
matrix.postConcat( mRotateMatrix );
matrix.mapPoints( points );
RectF invertRect = new RectF( mViewDrawRect );
invertRect.top -= mPaddingLeft;
invertRect.left -= mPaddingTop;
mInversePath.addRect( invertRect, Path.Direction.CW );
double sx = Point2D.distance( points[2], points[3], points[0], points[1] );
double sy = Point2D.distance( points[6], points[7], points[0], points[1] );
double angle = getAngle90( mRotation );
RectF rect;
if ( angle < 45 ) {
rect = crop( (float) sx, (float) sy, angle, mDrawableWidth, mDrawableHeight, mCenter, null );
} else {
rect = crop( (float) sx, (float) sy, angle, mDrawableHeight, mDrawableWidth, mCenter, null );
}
float colStep = (float) rect.height() / grid_cols;
float rowStep = (float) rect.width() / grid_rows;
for ( int i = 1; i < grid_cols; i++ ) {
// mLinesPath.addRect( (int)rect.left, (int)(rect.top + colStep * i), (int)rect.right, (int)(rect.top + colStep * i)
// + 3, Path.Direction.CW );
mLinesPath.moveTo( (int) rect.left, (int) ( rect.top + colStep * i ) );
mLinesPath.lineTo( (int) rect.right, (int) ( rect.top + colStep * i ) );
}
for ( int i = 1; i < grid_rows; i++ ) {
// mLinesPath.addRect( (int)(rect.left + rowStep * i), (int)rect.top, (int)(rect.left + rowStep * i) + 3,
// (int)rect.bottom, Path.Direction.CW );
mLinesPath.moveTo( (int) ( rect.left + rowStep * i ), (int) rect.top );
mLinesPath.lineTo( (int) ( rect.left + rowStep * i ), (int) rect.bottom );
}
mClipPath.addRect( rect, Path.Direction.CW );
mInversePath.addRect( rect, Path.Direction.CCW );
saveCount = canvas.save();
canvas.translate( mPaddingLeft, mPaddingTop );
canvas.drawPath( mInversePath, mOutlineFill );
// canvas.drawPath( mLinesPath, mLinesPaintShadow );
canvas.drawPath( mLinesPath, mLinesPaint );
canvas.drawPath( mClipPath, mOutlinePaint );
// if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix );
// if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix );
// if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix );
// mResizeDrawable.setBounds( (int) mDrawRect.right - handleWidth, (int) mDrawRect.bottom - handleHeight, (int)
// mDrawRect.right + handleWidth, (int) mDrawRect.bottom + handleHeight );
// mResizeDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
saveCount = canvas.save();
canvas.translate( mPaddingLeft, mPaddingTop );
mResizeDrawable.setBounds( (int) ( points[4] - handleWidth ), (int) ( points[5] - handleHeight ),
(int) ( points[4] + handleWidth ), (int) ( points[5] + handleHeight ) );
mResizeDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
}
}
}
Handler mFadeHandler = new Handler();
boolean mFadeHandlerStarted;
protected void fadeinGrid( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final float startAlpha = mLinesPaint.getAlpha();
final float startAlphaShadow = mLinesPaintShadow.getAlpha();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_lines = (float) easing.easeNone( currentMs, startAlpha, mLinesAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, startAlphaShadow, mLinesShadowAlpha, durationMs );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mLinesPaint.setAlpha( mLinesAlpha );
mLinesPaintShadow.setAlpha( mLinesShadowAlpha );
invalidate();
}
}
} );
}
protected void fadeoutGrid( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final float startAlpha = mLinesPaint.getAlpha();
final float startAlphaShadow = mLinesPaintShadow.getAlpha();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_lines = (float) easing.easeNone( currentMs, 0, startAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, startAlphaShadow, durationMs );
mLinesPaint.setAlpha( (int) startAlpha - (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) startAlphaShadow - (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
invalidate();
}
}
} );
}
protected void fadeinOutlines( final int durationMs ) {
if ( mFadeHandlerStarted ) return;
mFadeHandlerStarted = true;
final long startTime = System.currentTimeMillis();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_fill = (float) easing.easeNone( currentMs, 0, mOutlineFillAlpha, durationMs );
float new_alpha_paint = (float) easing.easeNone( currentMs, 0, mOutlinePaintAlpha, durationMs );
float new_alpha_lines = (float) easing.easeNone( currentMs, 0, mLinesAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, mLinesShadowAlpha, durationMs );
mOutlineFill.setAlpha( (int) new_alpha_fill );
mOutlinePaint.setAlpha( (int) new_alpha_paint );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mOutlineFill.setAlpha( mOutlineFillAlpha );
mOutlinePaint.setAlpha( mOutlinePaintAlpha );
mLinesPaint.setAlpha( mLinesAlpha );
mLinesPaintShadow.setAlpha( mLinesShadowAlpha );
invalidate();
}
}
} );
}
static double getAngle90( double value ) {
double rotation = Point2D.angle360( value );
double angle = rotation;
if ( rotation >= 270 ) {
angle = 360 - rotation;
} else if ( rotation >= 180 ) {
angle = rotation - 180;
} else if ( rotation > 90 ) {
angle = 180 - rotation;
}
return angle;
}
RectF crop( float originalWidth, float originalHeight, double angle, float targetWidth, float targetHeight, PointF center,
Canvas canvas ) {
double radians = Point2D.radians( angle );
PointF[] original = new PointF[] {
new PointF( 0, 0 ), new PointF( originalWidth, 0 ), new PointF( originalWidth, originalHeight ),
new PointF( 0, originalHeight ) };
Point2D.translate( original, -originalWidth / 2, -originalHeight / 2 );
PointF[] rotated = new PointF[original.length];
System.arraycopy( original, 0, rotated, 0, original.length );
Point2D.rotate( rotated, radians );
if ( angle >= 0 ) {
PointF[] ray = new PointF[] { new PointF( 0, 0 ), new PointF( -targetWidth / 2, -targetHeight / 2 ) };
PointF[] bound = new PointF[] { rotated[0], rotated[3] };
// Top Left intersection.
PointF intersectTL = Point2D.intersection( ray, bound );
PointF[] ray2 = new PointF[] { new PointF( 0, 0 ), new PointF( targetWidth / 2, -targetHeight / 2 ) };
PointF[] bound2 = new PointF[] { rotated[0], rotated[1] };
// Top Right intersection.
PointF intersectTR = Point2D.intersection( ray2, bound2 );
// Pick the intersection closest to the origin
PointF intersect = new PointF( Math.max( intersectTL.x, -intersectTR.x ), Math.max( intersectTL.y, intersectTR.y ) );
RectF newRect = new RectF( intersect.x, intersect.y, -intersect.x, -intersect.y );
newRect.offset( center.x, center.y );
if ( canvas != null ) { // debug
Point2D.translate( rotated, center.x, center.y );
Point2D.translate( ray, center.x, center.y );
Point2D.translate( ray2, center.x, center.y );
Paint paint = new Paint( Paint.ANTI_ALIAS_FLAG );
paint.setColor( 0x66FFFF00 );
paint.setStyle( Paint.Style.STROKE );
paint.setStrokeWidth( 2 );
// draw rotated
drawRect( rotated, canvas, paint );
paint.setColor( Color.GREEN );
drawLine( ray, canvas, paint );
paint.setColor( Color.BLUE );
drawLine( ray2, canvas, paint );
paint.setColor( Color.CYAN );
drawLine( bound, canvas, paint );
paint.setColor( Color.WHITE );
drawLine( bound2, canvas, paint );
paint.setColor( Color.GRAY );
canvas.drawRect( newRect, paint );
}
return newRect;
} else {
throw new IllegalArgumentException( "angle cannot be < 0" );
}
}
void drawLine( PointF[] line, Canvas canvas, Paint paint ) {
canvas.drawLine( line[0].x, line[0].y, line[1].x, line[1].y, paint );
}
void drawRect( PointF[] rect, Canvas canvas, Paint paint ) {
// draw rotated
Path path = new Path();
path.moveTo( rect[0].x, rect[0].y );
path.lineTo( rect[1].x, rect[1].y );
path.lineTo( rect[2].x, rect[2].y );
path.lineTo( rect[3].x, rect[3].y );
path.lineTo( rect[0].x, rect[0].y );
canvas.drawPath( path, paint );
}
/**
* <p>
* Return the offset of the widget's text baseline from the widget's top boundary.
* </p>
*
* @return the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported.
*/
@Override
public int getBaseline() {
if ( mBaselineAlignBottom ) {
return getMeasuredHeight();
} else {
return mBaseline;
}
}
/**
* <p>
* Set the offset of the widget's text baseline from the widget's top boundary. This value is overridden by the
*
* @param baseline
* The baseline to use, or -1 if none is to be provided. {@link #setBaselineAlignBottom(boolean)} property.
* </p>
* @see #setBaseline(int)
* @attr ref android.R.styleable#ImageView_baseline
*/
public void setBaseline( int baseline ) {
if ( mBaseline != baseline ) {
mBaseline = baseline;
requestLayout();
}
}
/**
* Set whether to set the baseline of this view to the bottom of the view. Setting this value overrides any calls to setBaseline.
*
* @param aligned
* If true, the image view will be baseline aligned with based on its bottom edge.
*
* @attr ref android.R.styleable#ImageView_baselineAlignBottom
*/
public void setBaselineAlignBottom( boolean aligned ) {
if ( mBaselineAlignBottom != aligned ) {
mBaselineAlignBottom = aligned;
requestLayout();
}
}
/**
* Return whether this view's baseline will be considered the bottom of the view.
*
* @return the baseline align bottom
* @see #setBaselineAlignBottom(boolean)
*/
public boolean getBaselineAlignBottom() {
return mBaselineAlignBottom;
}
/**
* Set a tinting option for the image.
*
* @param color
* Color tint to apply.
* @param mode
* How to apply the color. The standard mode is {@link PorterDuff.Mode#SRC_ATOP}
*
* @attr ref android.R.styleable#ImageView_tint
*/
public final void setColorFilter( int color, PorterDuff.Mode mode ) {
setColorFilter( new PorterDuffColorFilter( color, mode ) );
}
/**
* Set a tinting option for the image. Assumes {@link PorterDuff.Mode#SRC_ATOP} blending mode.
*
* @param color
* Color tint to apply.
* @attr ref android.R.styleable#ImageView_tint
*/
public final void setColorFilter( int color ) {
setColorFilter( color, PorterDuff.Mode.SRC_ATOP );
}
/**
* Clear color filter.
*/
public final void clearColorFilter() {
setColorFilter( null );
}
/**
* Apply an arbitrary colorfilter to the image.
*
* @param cf
* the colorfilter to apply (may be null)
*/
public void setColorFilter( ColorFilter cf ) {
if ( mColorFilter != cf ) {
mColorFilter = cf;
mColorMod = true;
applyColorMod();
invalidate();
}
}
/**
* Sets the alpha.
*
* @param alpha
* the new alpha
*/
public void setAlpha( int alpha ) {
alpha &= 0xFF; // keep it legal
if ( mAlpha != alpha ) {
mAlpha = alpha;
mColorMod = true;
applyColorMod();
invalidate();
}
}
/**
* Apply color mod.
*/
private void applyColorMod() {
// Only mutate and apply when modifications have occurred. This should
// not reset the mColorMod flag, since these filters need to be
// re-applied if the Drawable is changed.
if ( mDrawable != null && mColorMod ) {
mDrawable = mDrawable.mutate();
mDrawable.setColorFilter( mColorFilter );
mDrawable.setAlpha( mAlpha * mViewAlphaScale >> 8 );
}
}
/** The m handler. */
protected Handler mHandler = new Handler();
/** The m rotation. */
protected double mRotation = 0;
/** The m current scale. */
protected float mCurrentScale = 0;
/** The m running. */
protected boolean mRunning = false;
/**
* Rotate90.
*
* @param cw
* the cw
* @param durationMs
* the duration ms
*/
public void rotate90( boolean cw, int durationMs ) {
final double destRotation = ( cw ? 90 : -90 );
rotateBy( destRotation, durationMs );
}
/**
* Rotate to.
*
* @param cw
* the cw
* @param durationMs
* the duration ms
*/
protected void rotateBy( final double deltaRotation, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
final long startTime = System.currentTimeMillis();
final double destRotation = mRotation + deltaRotation;
final double srcRotation = mRotation;
setImageRotation( mRotation, false );
invalidate();
mHandler.post( new Runnable() {
@SuppressWarnings("unused")
float old_scale = 0;
@SuppressWarnings("unused")
float old_rotation = 0;
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_rotation = (float) mEasing.easeInOut( currentMs, 0, deltaRotation, durationMs );
mRotation = Point2D.angle360( srcRotation + new_rotation );
setImageRotation( mRotation, false );
old_rotation = new_rotation;
invalidate();
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
mRotation = Point2D.angle360( destRotation );
setImageRotation( mRotation, true );
invalidate();
printDetails();
mRunning = false;
if ( isReset ) {
onReset();
}
}
}
} );
}
/**
* Prints the details.
*/
public void printDetails() {
Log.i( LOG_TAG, "details:" );
Log.d( LOG_TAG, " flip horizontal: "
+ ( ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt ) );
Log.d( LOG_TAG, " flip vertical: " + ( ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt ) );
Log.d( LOG_TAG, " rotation: " + mRotation );
Log.d( LOG_TAG, "--------" );
}
/**
* Flip.
*
* @param horizontal
* the horizontal
* @param durationMs
* the duration ms
*/
public void flip( boolean horizontal, int durationMs ) {
flipTo( horizontal, durationMs );
}
/** The m camera enabled. */
private boolean mCameraEnabled;
/**
* Sets the camera enabled.
*
* @param value
* the new camera enabled
*/
public void setCameraEnabled( final boolean value ) {
if ( android.os.Build.VERSION.SDK_INT >= 14 && value )
mCameraEnabled = value;
else
mCameraEnabled = false;
}
/**
* Flip to.
*
* @param horizontal
* the horizontal
* @param durationMs
* the duration ms
*/
protected void flipTo( final boolean horizontal, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
final long startTime = System.currentTimeMillis();
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
final float centerx = vwidth / 2;
final float centery = vheight / 2;
final Camera camera = new Camera();
mHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
double currentMs = Math.min( durationMs, now - startTime );
if ( mCameraEnabled ) {
float degrees = (float) ( 0 + ( ( -180 - 0 ) * ( currentMs / durationMs ) ) );
camera.save();
if ( horizontal ) {
camera.rotateY( degrees );
} else {
camera.rotateX( degrees );
}
camera.getMatrix( mFlipMatrix );
camera.restore();
mFlipMatrix.preTranslate( -centerx, -centery );
mFlipMatrix.postTranslate( centerx, centery );
} else {
double new_scale = mEasing.easeInOut( currentMs, 1, -2, durationMs );
if ( horizontal )
mFlipMatrix.setScale( (float) new_scale, 1, centerx, centery );
else
mFlipMatrix.setScale( 1, (float) new_scale, centerx, centery );
}
invalidate();
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
if ( horizontal ) {
mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt;
mDrawMatrix.postScale( -1, 1, centerx, centery );
} else {
mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt;
mDrawMatrix.postScale( 1, -1, centerx, centery );
}
mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), centerx, centery );
mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) );
mFlipMatrix.reset();
invalidate();
printDetails();
mRunning = false;
if ( isReset ) {
onReset();
}
}
}
} );
}
private void flip( boolean horizontal, boolean vertical ) {
PointF center = getCenter();
if ( horizontal ) {
mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt;
mDrawMatrix.postScale( -1, 1, center.x, center.y );
}
if ( vertical ) {
mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt;
mDrawMatrix.postScale( 1, -1, center.x, center.y );
}
mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), center.x, center.y );
mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) );
mFlipMatrix.reset();
}
/** The m matrix values. */
protected final float[] mMatrixValues = new float[9];
/**
* Gets the value.
*
* @param matrix
* the matrix
* @param whichValue
* the which value
* @return the value
*/
protected float getValue( Matrix matrix, int whichValue ) {
matrix.getValues( mMatrixValues );
return mMatrixValues[whichValue];
}
/**
* Gets the matrix scale.
*
* @param matrix
* the matrix
* @return the matrix scale
*/
protected float[] getMatrixScale( Matrix matrix ) {
float[] result = new float[2];
result[0] = getValue( matrix, Matrix.MSCALE_X );
result[1] = getValue( matrix, Matrix.MSCALE_Y );
return result;
}
/** The m flip type. */
protected int mFlipType = FlipType.FLIP_NONE.nativeInt;
/**
* The Enum FlipType.
*/
public enum FlipType {
/** The FLI p_ none. */
FLIP_NONE( 1 << 0 ),
/** The FLI p_ horizontal. */
FLIP_HORIZONTAL( 1 << 1 ),
/** The FLI p_ vertical. */
FLIP_VERTICAL( 1 << 2 );
/**
* Instantiates a new flip type.
*
* @param ni
* the ni
*/
FlipType( int ni ) {
nativeInt = ni;
}
/** The native int. */
public final int nativeInt;
}
/*
* (non-Javadoc)
*
* @see android.view.View#getRotation()
*/
public float getRotation() {
return (float) mRotation;
}
/**
* Gets the horizontal flip.
*
* @return the horizontal flip
*/
public boolean getHorizontalFlip() {
if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) {
return ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt;
}
return false;
}
/**
* Gets the vertical flip.
*
* @return the vertical flip
*/
public boolean getVerticalFlip() {
if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) {
return ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt;
}
return false;
}
/**
* Gets the flip type.
*
* @return the flip type
*/
public int getFlipType() {
return mFlipType;
}
/**
* Checks if is running.
*
* @return true, if is running
*/
public boolean isRunning() {
return mRunning;
}
/**
* Reset the image to the original state.
*/
public void reset() {
isReset = true;
onReset();
}
/**
* On reset.
*/
private void onReset() {
if ( isReset ) {
final boolean hflip = getHorizontalFlip();
final boolean vflip = getVerticalFlip();
boolean handled = false;
if ( mRotation != 0 ) {
rotateBy( -mRotation, resetAnimTime );
handled = true;
}
if ( hflip ) {
flip( true, resetAnimTime );
handled = true;
}
if ( vflip ) {
flip( false, resetAnimTime );
handled = true;
}
if ( !handled ) {
fireOnResetComplete();
}
}
}
/**
* Fire on reset complete.
*/
private void fireOnResetComplete() {
if ( mResetListener != null ) {
mResetListener.onResetComplete();
}
}
}
| 27.928949 | 130 | 0.662576 |
261787753aaba402bb85a13b4201aa11640a7981 | 4,597 | package com.arnaudpiroelle.muzei.marvel.ui.settings.fragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.arnaudpiroelle.muzei.marvel.R;
import com.arnaudpiroelle.muzei.marvel.core.inject.Injector;
import com.arnaudpiroelle.muzei.marvel.core.utils.PreferencesUtils;
import com.arnaudpiroelle.muzei.marvel.core.utils.TrackerUtils;
import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnItemClick;
public class MyTagsFragment extends Fragment {
@Inject
protected PreferencesUtils preferencesUtils;
@Inject
TrackerUtils trackerUtils;
@InjectView(R.id.list)
ListView mList;
@InjectView(R.id.tag)
EditText mTag;
@InjectView(R.id.empty)
View mEmpty;
private TagAdapter mTagAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Injector.inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mytags, container, false);
ButterKnife.inject(this, view);
return view;
}
@Override
public void onResume() {
trackerUtils.sendScreen("MyTagsFragment");
mTagAdapter = new TagAdapter();
mList.setAdapter(mTagAdapter);
mList.setEmptyView(mEmpty);
mTag.setImeActionLabel(getString(R.string.add), EditorInfo.IME_ACTION_DONE);
getActivity().setTitle(R.string.pref_tags);
super.onResume();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@OnClick(R.id.empty)
void onEmptyClick() {
if (mTag.requestFocus()) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mTag, InputMethodManager.SHOW_IMPLICIT);
}
}
@OnItemClick(R.id.list)
void onTagClick(int i) {
mTagAdapter.remove(i);
}
@OnEditorAction(R.id.tag)
boolean onTagEditorAction(int i) {
if (i == EditorInfo.IME_ACTION_DONE) {
onAddClick();
}
return false;
}
@OnClick(R.id.add)
void onAddClick() {
String tag = mTag.getText().toString();
if (TextUtils.isEmpty(tag)) {
Toast.makeText(getActivity(), getString(R.string.bad_tag_format), Toast.LENGTH_SHORT).show();
return;
}
mTagAdapter.add(tag);
mTag.setText(null);
}
private class TagAdapter extends BaseAdapter {
private List<String> mTags;
private TagAdapter() {
mTags = preferencesUtils.getTags();
}
private void updateTagsInPref(List<String> tags) {
preferencesUtils.setTags(tags);
}
public void add(String tag) {
if (mTags.contains(tag)) {
return;
}
mTags.add(0, tag);
updateTagsInPref(mTags);
notifyDataSetChanged();
}
void remove(int position) {
mTags.remove(position);
updateTagsInPref(mTags);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTags.size();
}
@Override
public String getItem(int i) {
return mTags.get(i);
}
@Override
public long getItemId(int i) {
return getItem(i).hashCode();
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.item_tag, viewGroup, false);
}
TextView tagTextView = (TextView) view.findViewById(R.id.tag_name);
String tag = getItem(i);
tagTextView.setText(tag);
return view;
}
}
}
| 25.39779 | 119 | 0.636285 |
71f4f8bd86c89bfd348936462936ccf711625f55 | 39,175 | package fr.insee.arc.web.dao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import fr.insee.arc.core.model.IDbConstant;
import fr.insee.arc.core.model.JeuDeRegle;
import fr.insee.arc.core.model.RegleMappingEntity;
import fr.insee.arc.core.model.TraitementEtat;
import fr.insee.arc.core.model.TraitementPhase;
import fr.insee.arc.core.service.ApiMappingService;
import fr.insee.arc.core.service.engine.mapping.RegleMappingFactory;
import fr.insee.arc.core.service.engine.mapping.VariableMapping;
import fr.insee.arc.core.service.engine.mapping.regles.AbstractRegleMapping;
import fr.insee.arc.utils.dao.EntityDao;
import fr.insee.arc.utils.dao.PreparedStatementBuilder;
import fr.insee.arc.utils.dao.UtilitaireDao;
import fr.insee.arc.utils.format.Format;
import fr.insee.arc.utils.textUtils.IConstanteCaractere;
import fr.insee.arc.utils.utils.FormatSQL;
import fr.insee.arc.utils.utils.LoggerHelper;
import fr.insee.arc.utils.utils.ManipString;
import fr.insee.arc.utils.utils.SQLExecutor;
import fr.insee.arc.web.action.GererNormeAction;
import fr.insee.arc.web.util.EAlphaNumConstante;
import fr.insee.arc.web.util.VObject;
import fr.insee.arc.web.util.VObjectService;
import fr.insee.arc.web.util.WebLoggerDispatcher;
/**
* Will own all the utilitary methode used in the {@link GererNormeAction}
*
* @author Pépin Rémi
*
*/
@Component
public class GererNormeDao implements IDbConstant {
private static final Logger LOGGER = LogManager.getLogger(GererNormeDao.class);
private static final String CLEF_CONSOLIDATION = "{clef}";
public final int INDEX_COLONNE_VARIABLE_TABLE_REGLE_MAPPING = 6;
private static final String TOKEN_NOM_VARIABLE = "{tokenNomVariable}";
private static final String MESSAGE_VARIABLE_CLEF_NULL = "La variable {tokenNomVariable} est une variable clef pour la consolidation.\nVous devez vous assurer qu'elle ne soit jamais null.";
@Autowired
private WebLoggerDispatcher loggerDispatcher;
@Autowired
@Qualifier("defaultVObjectService")
private VObjectService viewObject;
/**
* Return the SQL to get all the rules bond to a rule set. It suppose the a rule
* set is selected
*
* @param viewRulesSet : the Vobject containing the rules
* @param table : the sql to get the rules in the database
* @return an sql query to get all the rules bond to a rule set
*/
public PreparedStatementBuilder recupRegle(VObject viewRulesSet, String table) {
PreparedStatementBuilder requete = new PreparedStatementBuilder();
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
HashMap<String, String> type = viewRulesSet.mapHeadersType();
requete.append("select * from " + table + " ");
whereRuleSetEquals(requete, selection, type);
return requete;
}
/** Appends a where clause for rulesets. */
private void whereRuleSetEquals(PreparedStatementBuilder requete, Map<String, ArrayList<String>> selection,
HashMap<String, String> type) {
requete.append(" where id_norme" + requete.sqlEqual(selection.get("id_norme").get(0), type.get("id_norme")));
requete.append(" and periodicite" + requete.sqlEqual(selection.get("periodicite").get(0), type.get("periodicite")));
requete.append(" and validite_inf" + requete.sqlEqual(selection.get("validite_inf").get(0), type.get("validite_inf")));
requete.append(" and validite_sup" + requete.sqlEqual(selection.get("validite_sup").get(0), type.get("validite_sup")));
requete.append(" and version" + requete.sqlEqual(selection.get("version").get(0), type.get("version")));
}
/**
* Initialize the {@value GererNormeAction#viewNorme}. Request the full general
* norm table.
*/
public void initializeViewNorme(VObject viewNorme, String theTableName) {
LoggerHelper.debug(LOGGER, "/* initializeNorme */");
HashMap<String, String> defaultInputFields = new HashMap<>();
viewObject.initialize(
viewNorme,
new PreparedStatementBuilder("SELECT id_famille, id_norme, periodicite, def_norme, def_validite, etat FROM arc.ihm_norme order by id_norme"), theTableName, defaultInputFields);
}
/**
* Initialize the {@value GererNormeAction#viewCalendar}. Only get the calendar
* link to the selected norm.
*/
public void initializeViewCalendar(VObject viewCalendar, VObject viewNorme, String theTableName) {
LoggerHelper.debug(LOGGER, "/* initializeCalendar */");
// get the norm selected
Map<String, ArrayList<String>> selection = viewNorme.mapContentSelected();
if (!selection.isEmpty()) {
// Get the type of the column for casting
HashMap<String, String> type = viewNorme.mapHeadersType();
// requete de la vue
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append("select id_norme, periodicite, validite_inf, validite_sup, etat from arc.ihm_calendrier");
requete.append(
" where id_norme" + requete.sqlEqual(selection.get("id_norme").get(0), type.get("id_norme")));
requete.append(" and periodicite"
+ requete.sqlEqual(selection.get("periodicite").get(0), type.get("periodicite")));
// construction des valeurs par défaut pour les ajouts
HashMap<String, String> defaultInputFields = new HashMap<String, String>();
defaultInputFields.put("id_norme", selection.get("id_norme").get(0));
defaultInputFields.put("periodicite", selection.get("periodicite").get(0));
viewCalendar.setAfterInsertQuery(new PreparedStatementBuilder("select arc.fn_check_calendrier(); "));
viewCalendar.setAfterUpdateQuery(new PreparedStatementBuilder("select arc.fn_check_calendrier(); "));
// Create the vobject
viewObject.initialize(viewCalendar, requete, theTableName, defaultInputFields);
} else {
viewObject.destroy(viewCalendar);
}
}
/**
* Initialize the {@value GererNormeAction#viewRulesSet}. Only get the rulesset
* link to the selected norm and calendar.
*/
public void initializeViewRulesSet(VObject viewRulesSet, VObject viewCalendar, String theTableName) {
loggerDispatcher.info("/* initializeViewRulesSet *", LOGGER);
// Get the selected calendar for requesting the rule set
Map<String, ArrayList<String>> selection = viewCalendar.mapContentSelected();
if (!selection.isEmpty()) {
HashMap<String, String> type = viewCalendar.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append(
"select id_norme, periodicite, validite_inf, validite_sup, version, etat from arc.ihm_jeuderegle ");
requete.append(
" where id_norme" + requete.sqlEqual(selection.get("id_norme").get(0), type.get("id_norme")));
requete.append(" and periodicite"
+ requete.sqlEqual(selection.get("periodicite").get(0), type.get("periodicite")));
requete.append(" and validite_inf"
+ requete.sqlEqual(selection.get("validite_inf").get(0), type.get("validite_inf")));
requete.append(" and validite_sup"
+ requete.sqlEqual(selection.get("validite_sup").get(0), type.get("validite_sup")));
HashMap<String, String> defaultInputFields = new HashMap<>();
defaultInputFields.put("id_norme", selection.get("id_norme").get(0));
defaultInputFields.put("periodicite", selection.get("periodicite").get(0));
defaultInputFields.put("validite_inf", selection.get("validite_inf").get(0));
defaultInputFields.put("validite_sup", selection.get("validite_sup").get(0));
viewRulesSet.setAfterInsertQuery(new PreparedStatementBuilder("select arc.fn_check_jeuderegle(); "));
viewRulesSet.setAfterUpdateQuery(new PreparedStatementBuilder("select arc.fn_check_jeuderegle(); "));
viewObject.initialize(viewRulesSet, requete, theTableName, defaultInputFields);
} else {
viewObject.destroy(viewRulesSet);
}
}
/**
* Initialize the {@link VObject} of a load ruleset. Only
* get the load rule link to the selected rule set.
*/
public void initializeChargement(VObject moduleView, VObject viewRulesSet, String theTableName,
String scope) {
loggerDispatcher.info(String.format("Initialize view table %s", theTableName), LOGGER);
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
if (!selection.isEmpty() && scope != null) {
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append("select id_norme,periodicite,validite_inf,validite_sup,version,id_regle,type_fichier, delimiter, format, commentaire from arc.ihm_chargement_regle");
whereRuleSetEquals(requete, selection, type);
viewObject.initialize(moduleView, requete, theTableName, defaultRuleInputFields(selection));
} else {
viewObject.destroy(moduleView);
}
}
private HashMap<String, String> defaultRuleInputFields(Map<String, ArrayList<String>> selection) {
HashMap<String, String> defaultInputFields = new HashMap<>();
defaultInputFields.put("id_norme", selection.get("id_norme").get(0));
defaultInputFields.put("periodicite", selection.get("periodicite").get(0));
defaultInputFields.put("validite_inf", selection.get("validite_inf").get(0));
defaultInputFields.put("validite_sup", selection.get("validite_sup").get(0));
defaultInputFields.put("version", selection.get("version").get(0));
return defaultInputFields;
}
/**
* Initialize the {@link VObject} of a load ruleset. Only
* get the load rule link to the selected rule set.
*/
public void initializeNormage(VObject moduleView, VObject viewRulesSet, String theTableName,
String scope) {
loggerDispatcher.info(String.format("Initialize view table %s", theTableName), LOGGER);
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
if (!selection.isEmpty() && scope != null) {
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append("select id_norme,periodicite,validite_inf,validite_sup,version,id_regle,id_classe,rubrique,rubrique_nmcl,commentaire from arc.ihm_normage_regle");
whereRuleSetEquals(requete, selection, type);
viewObject.initialize(moduleView, requete, theTableName, defaultRuleInputFields(selection));
} else {
viewObject.destroy(moduleView);
}
}
/**
* Initialize the {@link VObject} of a control ruleset. Only
* get the load rule link to the selected rule set.
*/
public void initializeControle(VObject moduleView, VObject viewRulesSet, String theTableName,
String scope) {
loggerDispatcher.info(String.format("Initialize view table %s", theTableName), LOGGER);
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
if (!selection.isEmpty() && scope != null) {
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append("select id_norme,periodicite,validite_inf,validite_sup,version,id_regle,id_classe,rubrique_pere,rubrique_fils,borne_inf,borne_sup,condition,blocking_threshold,error_row_processing,pre_action,xsd_ordre,xsd_label_fils,xsd_role,commentaire from arc.ihm_controle_regle");
whereRuleSetEquals(requete, selection, type);
viewObject.initialize(moduleView, requete, theTableName, defaultRuleInputFields(selection));
} else {
viewObject.destroy(moduleView);
}
}
/**
* Initialize the {@link VObject} of a filter ruleset. Only
* get the load rule link to the selected rule set.
*/
public void initializeFiltrage(VObject moduleView, VObject viewRulesSet, String theTableName,
String scope) {
loggerDispatcher.info(String.format("Initialize view table %s", theTableName), LOGGER);
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
if (!selection.isEmpty() && scope != null) {
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append("select * from arc.ihm_filtrage_regle");
whereRuleSetEquals(requete, selection, type);
viewObject.initialize(moduleView, requete, theTableName, defaultRuleInputFields(selection));
} else {
viewObject.destroy(moduleView);
}
}
/**
* Initialize the {@link VObject} of the mapping rule. Only get the load
* rule link to the selected rule set.
*/
public void initializeMapping(VObject viewMapping, VObject viewRulesSet, String theTableName, String scope) {
System.out.println("/* initializeMapping */");
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
if (!selection.isEmpty() && scope != null) {
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder(
"SELECT mapping.id_regle, mapping.id_norme, mapping.validite_inf, mapping.validite_sup, mapping.version, mapping.periodicite, mapping.variable_sortie, mapping.expr_regle_col, mapping.commentaire, variables.type_variable_metier type_sortie, variables.nom_table_metier nom_table_metier /*, variables.nom_table_metier nom_table_metier */ ");
requete.append("\n FROM arc.ihm_mapping_regle mapping INNER JOIN arc.ihm_jeuderegle jdr");
requete.append("\n ON mapping.id_norme = jdr.id_norme AND mapping.periodicite = jdr.periodicite AND mapping.validite_inf = jdr.validite_inf AND mapping.validite_sup = jdr.validite_sup AND mapping.version = jdr.version");
requete.append("\n INNER JOIN arc.ihm_norme norme");
requete.append("\n ON norme.id_norme = jdr.id_norme AND norme.periodicite = jdr.periodicite");
requete.append("\n LEFT JOIN (SELECT id_famille, nom_variable_metier, type_variable_metier, string_agg(nom_table_metier,',') as nom_table_metier FROM arc.ihm_mod_variable_metier group by id_famille, nom_variable_metier, type_variable_metier) variables");
requete.append("\n ON variables.id_famille = norme.id_famille AND variables.nom_variable_metier = mapping.variable_sortie");
requete.append("\n WHERE mapping.id_norme" + requete.sqlEqual(selection.get("id_norme").get(0), type.get("id_norme")));
requete.append("\n AND mapping.periodicite" + requete.sqlEqual(selection.get("periodicite").get(0), type.get("periodicite")));
requete.append("\n AND mapping.validite_inf" + requete.sqlEqual(selection.get("validite_inf").get(0), type.get("validite_inf")));
requete.append("\n AND mapping.validite_sup" + requete.sqlEqual(selection.get("validite_sup").get(0), type.get("validite_sup")));
requete.append("\n AND mapping.version" + requete.sqlEqual(selection.get("version").get(0), type.get("version")));
viewObject.initialize(viewMapping,requete,theTableName, defaultRuleInputFields(selection));
} else {
viewObject.destroy(viewMapping);
}
}
/**
* Initialize the {@link VObject} of the expression. Only
* get the load rule link to the selected rule set.
*/
public void initializeExpression(VObject moduleView, VObject viewRulesSet, String theTableName,
String scope) {
loggerDispatcher.info(String.format("Initialize view table %s", theTableName), LOGGER);
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
if (!selection.isEmpty() && scope != null) {
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete = new PreparedStatementBuilder();;
requete.append("select id_norme,periodicite,validite_inf,validite_sup,version,id_regle,expr_nom, expr_valeur, commentaire from arc.ihm_expression");
whereRuleSetEquals(requete, selection, type);
viewObject.initialize(moduleView, requete, theTableName, defaultRuleInputFields(selection));
} else {
viewObject.destroy(moduleView);
}
}
/**
* Initialize the {@value GererNormeAction#viewJeuxDeReglesCopie}. Get in
* database all the reccord the rule sets.
*
* @param viewJeuxDeReglesCopie
*/
public void initializeJeuxDeReglesCopie(VObject viewJeuxDeReglesCopie, VObject viewRulesSet,
String theTableName, String scope) {
LoggerHelper.info(LOGGER, "initializeJeuxDeReglesCopie");
if (scope != null) {
PreparedStatementBuilder requete = new PreparedStatementBuilder();
requete.append("select id_norme, periodicite, validite_inf, validite_sup, version, etat from arc.ihm_jeuderegle ");
HashMap<String, String> defaultInputFields = new HashMap<>();
viewObject.initialize(viewJeuxDeReglesCopie, requete, theTableName, defaultInputFields);
} else {
viewObject.destroy(viewJeuxDeReglesCopie);
}
}
/**
* Send a rule set to production.
*/
@SQLExecutor
public void sendRuleSetToProduction(VObject viewRulesSet, String theTable) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:HH");
Date dNow = new Date();
loggerDispatcher.warn("Rule set send to production", LOGGER);
try {
PreparedStatementBuilder requete= new PreparedStatementBuilder();
requete.append("update " + theTable + " set last_init='"+ dateFormat.format(dNow) + "', operation=case when operation='R' then 'O' else operation end;");
UtilitaireDao.get("arc").executeRequest(null, requete);
viewRulesSet.setMessage("Go to production registered");
} catch (SQLException e) {
viewRulesSet.setMessage("Error in the go to production");
LoggerHelper.warn(LOGGER, "Error in the go to production");
}
}
/**
*
* @param viewRulesSet
* @return
*/
public JeuDeRegle fetchJeuDeRegle(VObject viewRulesSet) {
HashMap<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
/*
* Fabrication d'un JeuDeRegle pour conserver les informations sur norme et calendrier
*/
JeuDeRegle jdr = new JeuDeRegle();
jdr.setIdNorme(selection.get("id_norme").get(0));
jdr.setPeriodicite(selection.get("periodicite").get(0));
jdr.setValiditeInfString(selection.get("validite_inf").get(0), "yyyy-MM-dd");
jdr.setValiditeSupString(selection.get("validite_sup").get(0), "yyyy-MM-dd");
jdr.setVersion(selection.get("version").get(0));
jdr.setEtat(selection.get("etat").get(0));
return jdr;
}
/**
* Empty all the rules of a norm modul
*
* @param table
* @return
*/
public void emptyRuleTable(VObject viewRulesSet, String table) {
loggerDispatcher.info("Empty all the rules of a module", LOGGER);
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
HashMap<String, String> type = viewRulesSet.mapHeadersType();
PreparedStatementBuilder requete= new PreparedStatementBuilder();
requete.append("DELETE FROM " + table);
requete.append(" WHERE id_norme" + requete.sqlEqual(selection.get("id_norme").get(0), type.get("id_norme")));
requete.append(" AND periodicite" + requete.sqlEqual(selection.get("periodicite").get(0), type.get("periodicite")));
requete.append(" AND validite_inf" + requete.sqlEqual(selection.get("validite_inf").get(0), type.get("validite_inf")));
requete.append(" AND validite_sup" + requete.sqlEqual(selection.get("validite_sup").get(0), type.get("validite_sup")));
requete.append(" AND version" + requete.sqlEqual(selection.get("version").get(0), type.get("version")));
requete.append(" ;");
try {
UtilitaireDao.get("arc").executeRequest(null, requete);
} catch (SQLException e) {
LoggerHelper.error(LOGGER, String.format("Error when emptying the rules %s", e.toString()));
}
}
public String createTableTest(String aNomTable, List<String> listRubrique) {
StringBuilder sb = new StringBuilder();
sb.append("DROP TABLE IF EXISTS " + aNomTable + ";");
sb.append("CREATE TABLE " + aNomTable);
sb.append("(id_norme text, periodicite text, id_source text, validite text, id integer, controle text, brokenrules text[] ");
//Je m'assure que les ubriques de base ne sont pas dans la liste des rubriques du filtre (sinon requête invalide),
//--> cas possible lorsque par exemple, le paramètre {validite} apparait dans la règle de filtrage.
listRubrique.remove("id_norme");
listRubrique.remove("periodicite");
listRubrique.remove("id_source");
listRubrique.remove("validite");
listRubrique.remove("id");
listRubrique.remove("controle");
listRubrique.remove("brokenrules");
for (String rub : listRubrique) {
if (rub.toUpperCase().startsWith("I")) {
sb.append("," + rub + " integer");
} else {
sb.append("," + rub + " text");
}
}
sb.append(");");
return sb.toString();
}
private static List<String> getTableEnvironnement(String state) {
StringBuilder requete = new StringBuilder();
String zeEnv = ManipString.substringAfterFirst(state, EAlphaNumConstante.DOT.getValue());
String zeSchema = ManipString.substringBeforeFirst(state, EAlphaNumConstante.DOT.getValue());
requete.append("SELECT replace(lower(relname), '" + zeEnv + "', '') ")//
.append("\n FROM pg_class a ")//
.append("\n INNER JOIN pg_namespace b ON a.relnamespace=b.oid ")//
.append("\n WHERE lower(b.nspname)=lower('" + zeSchema + "') ")//
.append("\n AND lower(relname) LIKE '" + zeEnv.toLowerCase() + "\\_%'; ");
return UtilitaireDao.get(poolName).getList(null, requete, new ArrayList<String>());
}
/**
* @param afterUpdate
* @param isRegleOk
* @return
*/
public boolean testerReglesMapping(VObject viewMapping, VObject viewRulesSet, VObject viewNorme,
Map<String, ArrayList<String>> afterUpdate) {
boolean isRegleOk = true;
List<String> tableADropper = new ArrayList<>();
String zeExpression = null;
String zeVariable = null;
if (!afterUpdate.isEmpty() && !afterUpdate.get("expr_regle_col").isEmpty()) {
try {
/*
* Récupération du jeu de règle
*/
JeuDeRegle jdr = fetchJeuDeRegle(viewRulesSet);
/*
* recopie des tables de l'environnement
*/
List<String> tables = getTableEnvironnement(jdr.getEtat());
List<String> sources = new ArrayList<>();
List<String> targets = new ArrayList<>();
String envTarget = jdr.getEtat().replace(EAlphaNumConstante.DOT.getValue(), ".test_");
for (int i = 0; i < tables.size(); i++) {
sources.add(jdr.getEtat() + tables.get(i));
targets.add(envTarget + tables.get(i));
}
tableADropper.addAll(targets);
UtilitaireDao.get(poolName).dupliquerVers(null, sources, targets, "false");
List<AbstractRegleMapping> listRegle = new ArrayList<>();
RegleMappingFactory regleMappingFactory = new RegleMappingFactory(null, envTarget,
new HashSet<String>(), new HashSet<String>());
String idFamille = viewNorme.mapContentSelected().get("id_famille").get(0);
regleMappingFactory.setIdFamille(idFamille);
for (int i = 0; i < afterUpdate.get("expr_regle_col").size(); i++) {
String expression = afterUpdate.get("expr_regle_col").get(i);
String variable = afterUpdate.get("variable_sortie").get(i);
String type = afterUpdate.get("type_sortie").get(i);
VariableMapping variableMapping = new VariableMapping(regleMappingFactory, variable, type);
variableMapping.setExpressionRegle(regleMappingFactory.get(expression, variableMapping));
listRegle.add(variableMapping.getExpressionRegle());
}
/*
* on dérive pour avoir de belles expressions à tester et connaitre les noms de
* colonnes
*/
for (int i = 0; i < listRegle.size(); i++) {
listRegle.get(i).deriverTest();
}
Set<Integer> groupesUtiles = groupesUtiles(listRegle);
/*
* on fait remonter les noms de colonnes dans colUtiles
*/
Set<String> colUtiles = new TreeSet<>();
for (int i = 0; i < listRegle.size(); i++) {
for (Integer groupe : groupesUtiles) {
colUtiles.addAll(listRegle.get(i).getEnsembleIdentifiantsRubriques(groupe));
colUtiles.addAll(listRegle.get(i).getEnsembleNomsRubriques(groupe));
}
colUtiles.addAll(listRegle.get(i).getEnsembleIdentifiantsRubriques());
colUtiles.addAll(listRegle.get(i).getEnsembleNomsRubriques());
}
createTablePhasePrecedente(envTarget, colUtiles, tableADropper);
for (int i = 0; i < listRegle.size(); i++) {
zeExpression = listRegle.get(i).getExpression();
zeVariable = listRegle.get(i).getVariableMapping().getNomVariable();
// Test de l'expression
groupesUtiles = groupesUtiles(Arrays.asList(listRegle.get(i)));
if (groupesUtiles.isEmpty()) {
if (createRequeteSelect(envTarget, listRegle.get(i))
&& CLEF_CONSOLIDATION.equalsIgnoreCase(afterUpdate.get("type_consolidation").get(i))) {
throw new IllegalArgumentException(MESSAGE_VARIABLE_CLEF_NULL.replace(TOKEN_NOM_VARIABLE,
listRegle.get(i).getVariableMapping().getNomVariable()));
}
} else {
for (Integer groupe : groupesUtiles) {
if (createRequeteSelect(envTarget, listRegle.get(i), groupe) && CLEF_CONSOLIDATION
.equalsIgnoreCase(afterUpdate.get("type_consolidation").get(i))) {
throw new IllegalArgumentException(MESSAGE_VARIABLE_CLEF_NULL.replace(
TOKEN_NOM_VARIABLE, listRegle.get(i).getVariableMapping().getNomVariable()
+ "(groupe " + groupe + ")"));
}
}
}
}
} catch (Exception ex) {
isRegleOk = false;
LoggerHelper.error(LOGGER, ex, "");
viewMapping.setMessage((zeVariable == null ? EAlphaNumConstante.EMPTY.getValue()
: "La règle " + zeVariable + " ::= " + zeExpression + " est erronée.\n") + "Exception levée : "
+ ex.getMessage());
} finally {
UtilitaireDao.get(poolName).dropTable(null, tableADropper.toArray(new String[0]));
}
}
return isRegleOk;
}
/**
* @param listRegle
* @param returned
* @return
* @throws Exception
*/
private static Set<Integer> groupesUtiles(List<AbstractRegleMapping> listRegle) throws Exception {
Set<Integer> returned = new TreeSet<>();
for (int i = 0; i < listRegle.size(); i++) {
returned.addAll(listRegle.get(i).getEnsembleGroupes());
}
return returned;
}
/**
* Exécution d'une règle sur la table <anEnvTarget>_filtrage_ok
*
* @param anEnvTarget
* @param regleMapping
* @return
* @throws SQLException
*/
private static Boolean createRequeteSelect(String anEnvTarget, AbstractRegleMapping regleMapping) throws Exception {
StringBuilder requete = new StringBuilder("SELECT CASE WHEN ")//
.append("(" + regleMapping.getExpressionSQL() + ")::" + regleMapping.getVariableMapping().getType())//
.append(" IS NULL THEN false ELSE false END")//
.append(" AS " + regleMapping.getVariableMapping().getNomVariable());
requete.append("\n FROM " + anEnvTarget + EAlphaNumConstante.UNDERSCORE.getValue() + "filtrage_ok ;");
return UtilitaireDao.get(poolName).getBoolean(null, new PreparedStatementBuilder(requete));
}
private static Boolean createRequeteSelect(String anEnvTarget, AbstractRegleMapping regleMapping, Integer groupe)
throws Exception {
StringBuilder requete = new StringBuilder("SELECT CASE WHEN ");//
requete.append("(" + regleMapping.getExpressionSQL(groupe) + ")::"
+ regleMapping.getVariableMapping().getType().replace("[]", ""))//
.append(" IS NULL THEN false ELSE false END")//
.append(" AS " + regleMapping.getVariableMapping().getNomVariable());
requete.append("\n FROM " + anEnvTarget + EAlphaNumConstante.UNDERSCORE.getValue() + "filtrage_ok ;");
return UtilitaireDao.get(poolName).getBoolean(null, new PreparedStatementBuilder(requete));
}
/**
* Creation d'une table vide avec les colonnes adéquates.<br/>
* En particulier, si la règle n'utilise pas du tout de noms de colonnes, une
* colonne {@code col$null} est créée, qui permette un requêtage.
*
* @param anEnvTarget
* @param colUtiles
* @param tableADropper
* @throws SQLException
*/
private static void createTablePhasePrecedente(String anEnvTarget, Set<String> colUtiles,
List<String> tableADropper) throws SQLException {
PreparedStatementBuilder requete=new PreparedStatementBuilder();
requete.append("DROP TABLE IF EXISTS " + anEnvTarget + "_" + TraitementPhase.FILTRAGE + "_"+TraitementEtat.OK+";");
requete.append("CREATE TABLE " + anEnvTarget + "_" + TraitementPhase.FILTRAGE + "_"+TraitementEtat.OK+" (");
requete.append(Format.untokenize(colUtiles, " text, "));
requete.append(colUtiles.isEmpty() ? "col$null text" : " text")//
.append(");");
requete.append("\nINSERT INTO " + anEnvTarget + "_" + TraitementPhase.FILTRAGE + "_"+TraitementEtat.OK+" (")//
.append(Format.untokenize(colUtiles, ", "))//
.append(colUtiles.isEmpty() ? "col$null" : "")//
.append(") VALUES (");
boolean isFirst = true;
for (String variable : colUtiles) {
if (isFirst) {
isFirst = false;
} else {
requete.append(", ");
}
if (ApiMappingService.colNeverNull.contains(variable)) {
requete.append(requete.quoteText(variable));
} else {
requete.append("null");
}
}
requete.append(colUtiles.isEmpty() ? "null" : "")//
.append(");");
tableADropper.add(anEnvTarget + EAlphaNumConstante.UNDERSCORE.getValue() + TraitementPhase.FILTRAGE + "_"+TraitementEtat.OK);
UtilitaireDao.get(poolName).executeRequest(null, requete);
}
public void calculerVariableToType(VObject viewNorme, Map<String, String> mapVariableToType,
Map<String, String> mapVariableToTypeConso) throws SQLException {
PreparedStatementBuilder requete=new PreparedStatementBuilder();
requete.append("SELECT DISTINCT lower(nom_variable_metier) AS nom_variable_metier, type_variable_metier, type_consolidation AS type_sortie ");
requete.append("\n FROM arc.ihm_mod_variable_metier ");
requete.append("\n WHERE id_famille="+requete.quoteText(viewNorme.mapContentSelected().get("id_famille").get(0))+" ");
ArrayList<ArrayList<String>> resultat = UtilitaireDao.get("arc").executeRequest(null, requete);
for (int i = 2; i < resultat.size(); i++) {
mapVariableToType.put(resultat.get(i).get(0), resultat.get(i).get(1));
mapVariableToTypeConso.put(resultat.get(i).get(0), resultat.get(i).get(2));
}
}
public Map<String, ArrayList<String>> calculerReglesAImporter(MultipartFile aFileUpload,
List<RegleMappingEntity> listeRegle, EntityDao<RegleMappingEntity> dao,
Map<String, String> mapVariableToType, Map<String, String> mapVariableToTypeConso) throws IOException {
Map<String, ArrayList<String>> returned = new HashMap<>();
returned.put("type_sortie", new ArrayList<String>());
returned.put("type_consolidation", new ArrayList<String>());
try (BufferedReader br = new BufferedReader(new InputStreamReader(aFileUpload.getInputStream(), StandardCharsets.UTF_8));){
dao.setSeparator(";");
String line = br.readLine();
String someNames = line;
dao.setNames(someNames);
line = br.readLine();
String someTypes = line;
dao.setTypes(someTypes);
while ((line = br.readLine()) != null) {
RegleMappingEntity entity = dao.get(line);
listeRegle.add(entity);
for (String colName : entity.colNames()) {
if (!returned.containsKey(colName)) {
/*
* La colonne n'existe pas encore ? Je l'ajoute.
*/
returned.put(colName, new ArrayList<String>());
}
/*
* J'ajoute la valeur en fin de colonne.
*/
returned.get(colName).add(entity.get(colName));
}
returned.get("type_sortie").add(mapVariableToType.get(entity.getVariableSortie()));
returned.get("type_consolidation").add(mapVariableToTypeConso.get(entity.getVariableSortie()));
}
} catch (Exception ex) {
LoggerHelper.error(LOGGER, "error in calculerReglesAImporter", ex.getStackTrace());
}
return returned;
}
public boolean testerConsistanceRegleMapping(List<List<String>> data, String anEnvironnement,
String anIdFamille, StringBuilder aMessage) {
Set<String> variableRegleCharge = new HashSet<String>();
for (int i = 0; i < data.size(); i++) {
variableRegleCharge.add(data.get(i).get(INDEX_COLONNE_VARIABLE_TABLE_REGLE_MAPPING));
}
Set<String> variableTableModele = new HashSet<String>();
variableTableModele
.addAll(UtilitaireDao.get("arc").getList(null,
new StringBuilder("SELECT DISTINCT nom_variable_metier FROM " + anEnvironnement
+ "_mod_variable_metier WHERE id_famille='" + anIdFamille + "'"),
new ArrayList<String>()));
Set<String> variableToute = new HashSet<String>();
variableToute.addAll(variableRegleCharge);
variableToute.addAll(variableTableModele);
boolean ok = true;
loggerDispatcher.info("Les variables du modèle : " + variableTableModele, LOGGER);
loggerDispatcher.info("Les variables des règles chargées : " + variableRegleCharge, LOGGER);
for (String variable : variableToute) {
if (!variableRegleCharge.contains(variable)) {
ok = false;
aMessage.append("La variable " + variable + " n'est pas présente dans les règles chargées.\n");
}
if (!variableTableModele.contains(variable)) {
ok = false;
aMessage.append(variable + " ne correspond à aucune variable existant.\n");
}
}
if (!ok) {
aMessage.append("Les règles ne seront pas chargées.");
}
return ok;
}
/**
*
* @param returned
* @param index -1 : en fin de tableau<br/>
* [0..size[ : le premier élément est ajouté à l'emplacement
* {@code index}, les suivants, juste après
* @param args
* @return
*/
public List<List<String>> ajouterInformationTableau(List<List<String>> returned, int index, String... args) {
for (int i = 0; i < returned.size(); i++) {
for (int j = 0; j < args.length; j++) {
returned.get(i).add((index == -1 ? returned.get(i).size() : index + j), args[j]);
}
}
return returned;
}
/**
*
* @param vObjectToUpdate the vObject to update with file
* @param tableName the
*/
@SQLExecutor
public void uploadFileRule(VObject vObjectToUpdate, VObject viewRulesSet, MultipartFile theFileToUpload) {
// Check if there is file
if (theFileToUpload == null || theFileToUpload.isEmpty()) {
// No file -> ko
vObjectToUpdate.setMessage("Please select a file.");
} else {
// A file -> can process it
LoggerHelper.debug(LOGGER, " filesUpload : " + theFileToUpload);
// before inserting in the final table, the rules will be inserted in a table to
// test them
String nomTableImage = FormatSQL.temporaryTableName(vObjectToUpdate.getTable() + "_img" + 0);
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(theFileToUpload.getInputStream(), StandardCharsets.UTF_8));) {
// Get headers
List<String> listHeaders = getHeaderFromFile(bufferedReader);
/*
* Création d'une table temporaire (qui ne peut pas être TEMPORARY)
*/
PreparedStatementBuilder requete=new PreparedStatementBuilder();
requete.append("\n DROP TABLE IF EXISTS " + nomTableImage + " cascade;");
requete.append("\n CREATE TABLE " + nomTableImage + " AS SELECT "//
+ Format.untokenize(listHeaders, ", ") //
+ "\n\t FROM " //
+ vObjectToUpdate.getTable() //
+ "\n\t WHERE false");
UtilitaireDao.get("arc").executeRequest(null, requete);
// Throwing away the first line
bufferedReader.readLine();
// Importing the file in the database (COPY command)
UtilitaireDao.get("arc").importing(null, nomTableImage, bufferedReader, true, false,
IConstanteCaractere.semicolon);
} catch (Exception ex) {
vObjectToUpdate.setMessage("Error when uploading the file : " + ex.getMessage());
LoggerHelper.error(LOGGER, ex, "uploadOutils()", "\n");
// After the exception, the methode cant go further, so the better thing to do
// is to quit it
return;
}
LoggerHelper.debug(LOGGER, "Insert file in the " + nomTableImage + " table");
Map<String, ArrayList<String>> selection = viewRulesSet.mapContentSelected();
PreparedStatementBuilder requete=new PreparedStatementBuilder();
requete.append("\n UPDATE " + nomTableImage + " SET ");
requete.append("\n id_norme=" + requete.quoteText(selection.get("id_norme").get(0)));
requete.append("\n, periodicite=" + requete.quoteText(selection.get("periodicite").get(0)));
requete.append("\n, validite_inf=" + requete.quoteText(selection.get("validite_inf").get(0)) + "::date");
requete.append("\n, validite_sup=" + requete.quoteText(selection.get("validite_sup").get(0)) + "::date");
requete.append("\n, version=" + requete.quoteText(selection.get("version").get(0)));
requete.append("\n ; ");
requete.append("\n DELETE FROM " + vObjectToUpdate.getTable());
requete.append("\n WHERE ");
requete.append("\n id_norme=" + requete.quoteText(selection.get("id_norme").get(0)));
requete.append("\n AND periodicite=" + requete.quoteText(selection.get("periodicite").get(0)));
requete.append("\n AND validite_inf=" + requete.quoteText(selection.get("validite_inf").get(0)) + "::date");
requete.append("\n AND validite_sup=" + requete.quoteText(selection.get("validite_sup").get(0)) + "::date");
requete.append("\n AND version=" + requete.quoteText(selection.get("version").get(0)));
requete.append("\n ; ");
requete.append("\n INSERT INTO " + vObjectToUpdate.getTable() + " ");
requete.append("\n SELECT * FROM " + nomTableImage + " ;");
requete.append("\n DROP TABLE IF EXISTS " + nomTableImage + " cascade;");
try {
UtilitaireDao.get("arc").executeRequest(null, requete);
} catch (Exception ex) {
vObjectToUpdate.setMessage("Error when uploading the file : " + ex.getMessage());
LoggerHelper.error(LOGGER, ex, "uploadOutils()");
}
}
}
private static List<String> getHeaderFromFile(BufferedReader bufferedReader) throws IOException {
String listeColonnesAggregees = bufferedReader.readLine();
List<String> listeColonnes = Arrays.asList(listeColonnesAggregees.split(IConstanteCaractere.semicolon));
LoggerHelper.debug(LOGGER, "Columns list : ", Format.untokenize(listeColonnes, ", "));
return listeColonnes;
}
}
| 45.341435 | 358 | 0.710785 |
7fe18e6cb0f51193867d0376a437026a694b0591 | 5,863 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.appcompat.widget;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.CheckedTextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.appcompat.R;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.CheckedTextViewCompat;
/** @hide */
@RestrictTo(LIBRARY)
class AppCompatCheckedTextViewHelper {
@NonNull
private final CheckedTextView mView;
private ColorStateList mCheckMarkTintList = null;
private PorterDuff.Mode mCheckMarkTintMode = null;
private boolean mHasCheckMarkTint = false;
private boolean mHasCheckMarkTintMode = false;
private boolean mSkipNextApply;
AppCompatCheckedTextViewHelper(@NonNull CheckedTextView view) {
mView = view;
}
void loadFromAttributes(@Nullable AttributeSet attrs, int defStyleAttr) {
TintTypedArray a =
TintTypedArray.obtainStyledAttributes(mView.getContext(), attrs,
R.styleable.CheckedTextView, defStyleAttr, 0);
ViewCompat.saveAttributeDataForStyleable(mView, mView.getContext(),
R.styleable.CheckedTextView, attrs, a.getWrappedTypeArray(), defStyleAttr, 0);
try {
boolean checkMarkDrawableLoaded = false;
if (a.hasValue(R.styleable.CheckedTextView_checkMarkCompat)) {
final int resourceId = a.getResourceId(R.styleable.CheckedTextView_checkMarkCompat,
0);
if (resourceId != 0) {
try {
mView.setCheckMarkDrawable(
AppCompatResources.getDrawable(mView.getContext(), resourceId));
checkMarkDrawableLoaded = true;
} catch (Resources.NotFoundException ignore) {
// Animated checkMarkCompat relies on AAPT2 features. If not found then
// swallow this error and fall back to the regular drawable.
}
}
}
if (!checkMarkDrawableLoaded && a.hasValue(
R.styleable.CheckedTextView_android_checkMark)) {
final int resourceId = a.getResourceId(
R.styleable.CheckedTextView_android_checkMark, 0);
if (resourceId != 0) {
mView.setCheckMarkDrawable(
AppCompatResources.getDrawable(mView.getContext(), resourceId));
}
}
if (a.hasValue(R.styleable.CheckedTextView_checkMarkTint)) {
CheckedTextViewCompat.setCheckMarkTintList(mView,
a.getColorStateList(R.styleable.CheckedTextView_checkMarkTint));
}
if (a.hasValue(R.styleable.CheckedTextView_checkMarkTintMode)) {
CheckedTextViewCompat.setCheckMarkTintMode(mView,
DrawableUtils.parseTintMode(
a.getInt(R.styleable.CheckedTextView_checkMarkTintMode, -1),
null));
}
} finally {
a.recycle();
}
}
void setSupportCheckMarkTintList(ColorStateList tint) {
mCheckMarkTintList = tint;
mHasCheckMarkTint = true;
applyCheckMarkTint();
}
ColorStateList getSupportCheckMarkTintList() {
return mCheckMarkTintList;
}
void setSupportCheckMarkTintMode(@Nullable PorterDuff.Mode tintMode) {
mCheckMarkTintMode = tintMode;
mHasCheckMarkTintMode = true;
applyCheckMarkTint();
}
PorterDuff.Mode getSupportCheckMarkTintMode() {
return mCheckMarkTintMode;
}
void onSetCheckMarkDrawable() {
if (mSkipNextApply) {
mSkipNextApply = false;
return;
}
mSkipNextApply = true;
applyCheckMarkTint();
}
void applyCheckMarkTint() {
Drawable checkMarkDrawable = CheckedTextViewCompat.getCheckMarkDrawable(mView);
if (checkMarkDrawable != null && (mHasCheckMarkTint || mHasCheckMarkTintMode)) {
checkMarkDrawable = DrawableCompat.wrap(checkMarkDrawable);
checkMarkDrawable = checkMarkDrawable.mutate();
if (mHasCheckMarkTint) {
DrawableCompat.setTintList(checkMarkDrawable, mCheckMarkTintList);
}
if (mHasCheckMarkTintMode) {
DrawableCompat.setTintMode(checkMarkDrawable, mCheckMarkTintMode);
}
// The drawable (or one of its children) may not have been
// stateful before applying the tint, so let's try again.
if (checkMarkDrawable.isStateful()) {
checkMarkDrawable.setState(mView.getDrawableState());
}
mView.setCheckMarkDrawable(checkMarkDrawable);
}
}
}
| 38.320261 | 99 | 0.645574 |
98bbfb51bc188814efd376875d1494a90296cd28 | 2,151 | package ie.tudublin;
import java.util.ArrayList;
import processing.core.PApplet;
import processing.data.Table;
import processing.data.TableRow;
public class ScoreDisplay extends PApplet
{
public ArrayList<Note> convertStringToArrayList(String score)
{
ArrayList<Note> notes = new ArrayList<Note>();
}
private float leftBorder;
private float border;
String score = "DEFGABcd";
//String score = "D2E2F2G2A2B2c2d2";
//String score = "DEF2F2F2EFA2A2B2AFD2E2D2D2D2";
public void settings()
{
size(1000, 500);
// How to convert a character to a number
char c = '7'; // c holds the character 7 (55)
int i = c - '0'; // i holds the number 7 (55 - 48)
println(i);
}
public void printScores()
{
for(String sss:score.split(" "))
{
System.out.println(sss);
for(int i = score.length() - 1; i >= 0; i--)
{
if(duration = 1)
{
System.out.println("Quaver");
}
else
{
System.out.println("Crochet");
}
}
}
}
public void loadScore()
{
for(int i = score.length() - 1; i >= 0; i--)
{
notes.add(score.charAt(i));
}
}
public void setup()
{
loadScore();
printScores();
}
public void draw()
{
background(255);
drawNotes();
textAlign(CENTER, CENTER);
for(int i = 0; i <= 8; i++)
{
float x = map(i, 0, 8, leftBorder, width - border);
drawLine(10, 50, 200, 50);
text(i, x, border/2);
}
for(int i = 0; i <= score.size; i++)
{
float y = map(i, 0, score.size(), border + 50, height - border - 20);
Note t = score.get(i);
float x1 = map(t.getStart(), 1, 30, leftBorder, width - border);
float x2 = map(t.getEnd(), 1, 50, leftBorder, width - border);
int c = (int) map(i, 0, score.size(), 0, 50);
fill(c, 255, 255);
rect(x1, y - 20, x2 - x1, 40);
fill(255);
textAlign(CENTER, CENTER);
text(t.getTask(), 20, y);
}
}
void drawNotes()
{
for(int i = score.length() - 1; i >= 0; i--)
{
score.render(this)
}
}
}
| 20.485714 | 77 | 0.541144 |
4adbe2f8b96b27c0e552c05ca1c4d8b1684d7aea | 486 | package org.knowm.xchange.okcoin.v5.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.knowm.xchange.okcoin.v5.OkexResultV5;
import java.util.List;
public class AccountConfigResult extends OkexResultV5<List<AccountConfig>> {
public AccountConfigResult(
@JsonProperty("code") String code,
@JsonProperty("msg") String msg,
@JsonProperty("data") List<AccountConfig> result) {
super(code, msg, result);
}
} | 28.588235 | 76 | 0.707819 |
76c9243ef7a8b168286f4b39c7aec03ac5c2eab3 | 292 | package ar.com.zumma.sparrow.repositories;
import ar.com.zumma.sparrow.model.User;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<User, String> {
Optional<User> findByEmail(String email);
}
| 24.333333 | 70 | 0.808219 |
c033f1f930578951f49fc1ca21c88bfa1d573635 | 1,404 | package cn.jzvd.task;
import java.util.Timer;
import java.util.TimerTask;
import cn.jzvd.JZVideoPlayer;
public class DismissControlViewTimerTask extends TimerTask {
private static Timer DISMISS_CONTROL_VIEW_TIMER;
private static DismissControlViewTimerTask task;
private final JZVideoPlayer player;
public static void start(JZVideoPlayer player) {
finish();
DISMISS_CONTROL_VIEW_TIMER = new Timer();
task = new DismissControlViewTimerTask(player);
DISMISS_CONTROL_VIEW_TIMER.schedule(task, 2500);
}
private DismissControlViewTimerTask(JZVideoPlayer player) {
this.player = player;
}
public static void finish() {
if (DISMISS_CONTROL_VIEW_TIMER != null) {
DISMISS_CONTROL_VIEW_TIMER.cancel();
}
if (task != null) {
task.cancel();
}
}
@Override
public void run() {
if (!player.getStateMachine().currentStateNormal()
&& !player.getStateMachine().currentStateError()
&& !player.getStateMachine().currentStateAutoComplete()) {
player.post(new Runnable() {
@Override
public void run() {
player.dismissRegisteredPlugins();
}
});
}
}
public static void oneShot() {
if(task != null) { task.run(); }
}
}
| 26.490566 | 74 | 0.606125 |
1c2090981ef87df72bb0a95022aba691587bb626 | 1,160 | /**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class PopulatingNextRightPointersInEachNodeII {
public void connect(TreeLinkNode root) {
if (root == null) return;
Queue<TreeLinkNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size - 1; i++) {
TreeLinkNode prev = queue.poll();
if (prev.left != null) {
queue.offer(prev.left);
}
if (prev.right != null) {
queue.offer(prev.right);
}
TreeLinkNode node = queue.peek();
prev.next = node;
prev = node;
}
TreeLinkNode last = queue.poll();
if (last.left != null) {
queue.offer(last.left);
}
if (last.right != null) {
queue.offer(last.right);
}
}
}
} | 29.74359 | 55 | 0.461207 |
8f27a90d402e848e32857ef9ed8316a5780ae83f | 10,251 | /* Xholon Runtime Framework - executes event-driven & dynamic applications
* Copyright (C) 2014 Ken Webb
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.primordion.ef.other;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.RootPanel;
import java.util.Date;
import org.primordion.ef.AbstractXholon2ExternalFormat;
import org.primordion.xholon.base.IXholon;
import org.primordion.xholon.common.mechanism.CeStateMachineEntity;
import org.primordion.xholon.io.gwt.HtmlScriptHelper;
import org.primordion.xholon.service.ef.IXholon2ExternalFormat;
/**
* Export a Xholon model in Simplified Molecular Input Line Entry System (SMILES) format.
*
* Examples:
[one]2[two]([three][three]3[three])[four]2[five]3
*
* I haven't tested this example yet, need to remove whitespace:
* <pre>
[ExtraCellularSpace] (
[EukaryoticCell] (
[CellMembrane] (
[CellBilayer]%01%02
)
[Cytoplasm] (
[Hexokinase]%03%04.
[PhosphoGlucoIsomerase].
[PhosphoFructokinase].
[Aldolase].
[TriosePhosphateIsomerase].
[Glyceraldehyde_3_phosphateDehydrogenase].
[PhosphoGlycerokinase].
[PhosphoGlyceromutase].
[Enolase].
[PyruvateKinase]
[Cytosol] (
[Glucose]%01%03.
[Glucose_6_Phosphate]%04.
[Fructose_6_Phosphate].
[Fructose_1x6_Biphosphate].
[DihydroxyacetonePhosphate].
[Glyceraldehyde_3_Phosphate].
[X1x3_BisphosphoGlycerate].
[X3_PhosphoGlycerate].
[X2_PhosphoGlycerate].
[PhosphoEnolPyruvate].
[Pyruvate]
)
)
)
[ExtraCellularSolution] (
[Glucose]%02
)
)
* </pre>
*
* with whitespace removed, this is syntactically correct at depict site:
* <pre>
[ExtraCellularSpace]([EukaryoticCell]([CellMembrane]([CellBilayer]%01%02)[Cytoplasm]([Hexokinase]%03%04.[PhosphoGlucoIsomerase].[PhosphoFructokinase].[Aldolase].[TriosePhosphateIsomerase].[Glyceraldehyde_3_phosphateDehydrogenase].[PhosphoGlycerokinase].[PhosphoGlyceromutase].[Enolase].[PyruvateKinase][Cytosol]([Glucose]%01%03.[Glucose_6_Phosphate]%04.[Fructose_6_Phosphate].[Fructose_1x6_Biphosphate].[DihydroxyacetonePhosphate].[Glyceraldehyde_3_Phosphate].[X1x3_BisphosphoGlycerate].[X3_PhosphoGlycerate].[X2_PhosphoGlycerate].[PhosphoEnolPyruvate].[Pyruvate])))[ExtraCellularSolution]([Glucose]%02))
* </pre>
*
* The following are all valid syntax:
* <pre>
[HelloWorldSystem]([Hello][World])
[HelloWorldSystem](.[Hello][World])
[HelloWorldSystem]([Hello].[World])
[HelloWorldSystem](.[Hello].[World])
* </pre>
*
* @author <a href="mailto:[email protected]">Ken Webb</a>
* @see <a href="http://www.primordion.com/Xholon">Xholon Project website</a>
* @since 0.9.1 (Created on June 24, 2014)
* @see <a href="http://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system">wikipedia</a>
* @see <a href="http://www.daylight.com/dayhtml/doc/theory/theory.smiles.html">basic info</a>
* @see <a href="http://www.daylight.com/daycgi/depict">online SMILES to image</a>
* @see <a href="http://www.daylight.com/dayhtml/doc/theory/">theory</a>
* @see <a href="https://gist.github.com/kenwebb/6c71b62ab83af820939a">SMILES parser for Xholons</a>
* @see <a href="http://peter-ertl.com/jsme/">JSME Molecule Editor</a>
*/
@SuppressWarnings("serial")
public class Xholon2Smiles extends AbstractXholon2ExternalFormat implements IXholon2ExternalFormat {
private String outFileName;
private String outPath = "./ef/smiles/";
private String modelName;
private IXholon root;
private StringBuilder sb;
/** Current date and time. */
private Date timeNow;
private long timeStamp;
/** Whether or not to show state machine nodes. */
private boolean shouldShowStateMachineEntities = false;
/**
* Constructor.
*/
public Xholon2Smiles() {}
@Override
public String getVal_String() {
return sb.toString();
}
/*
* @see org.primordion.xholon.io.IXholon2ExternalFormat#initialize(java.lang.String, java.lang.String, org.primordion.xholon.base.IXholon)
*/
public boolean initialize(String smiFileName, String modelName, IXholon root) {
timeNow = new Date();
timeStamp = timeNow.getTime();
if (smiFileName == null) {
this.outFileName = outPath + root.getXhcName() + "_" + root.getId() + "_" + timeStamp + ".smi";
}
else {
this.outFileName = smiFileName;
}
this.modelName = modelName;
this.root = root;
if (isTryJsme()) {
loadJSME();
return true; // do not return false; that just causes an error message
}
return true;
}
/*
* @see org.primordion.xholon.io.IXholon2ExternalFormat#writeAll()
*/
public void writeAll() {
sb = new StringBuilder();
writeNode(root, 0); // root is level 0
writeToTarget(sb.toString(), outFileName, outPath, root);
}
/**
* Write one node, and its child nodes.
* @param node The current node in the Xholon hierarchy.
* @param level Current level in the hierarchy.
*/
protected void writeNode(IXholon node, int level) {
// only show state machine nodes if should show them, or if root is a StateMachineCE
if ((node.getXhcId() == CeStateMachineEntity.StateMachineCE)
&& (shouldShowStateMachineEntities == false)
&& (level > 0)) {
return;
}
sb.append(makeAtomOrBond(node));
// children
if (node.hasChildNodes()) {
sb.append("(");
IXholon childNode = node.getFirstChild();
boolean isFirstNode = true;
while (childNode != null) {
if (isFirstNode && isDotBeforeFirst()) {
sb.append(".");
}
else if (!isFirstNode && isDotBeforeNext()) {
sb.append(".");
}
writeNode(childNode, level+1);
childNode = childNode.getNextSibling();
isFirstNode = false;
}
sb.append(")");
}
}
/**
* Make a SMILES atom or bond.
* @param node
*/
protected String makeAtomOrBond(IXholon node) {
StringBuilder sbAtom = new StringBuilder();
String nodeName = node.getName(getNameTemplate());
switch (nodeName) {
// atoms
case "B":
case "Br":
case "C":
case "Cl":
case "N":
case "O":
case "S":
case "P":
case "F":
case "I":
case "b":
case "c":
case "n":
case "o":
case "s":
case "p":
sbAtom.append(nodeName);
break;
// bonds
case "Sngl": sbAtom.append("-"); break;
case "Dobl": sbAtom.append("="); break;
case "Trpl": sbAtom.append("#"); break;
case "Rmtc": sbAtom.append(":"); break;
// branch ()
case "Brch":
break;
default:
// this is a bracketed atom []
sbAtom.append("[");
if (nodeName.startsWith("_")) {
// these are chemical atoms, and are one or two characters long
sbAtom.append(nodeName.substring(1));
}
else {
// this is a non-chemical "atom" (any valid Xholon node)
sbAtom.append(nodeName);
}
sbAtom.append("]");
break;
}
return sbAtom.toString();
}
/**
* Load JSME library into a separate iframe.
* JSME is a GWT app, completely separate from the Xholon GWT app.
*/
protected void loadJSME() {
// Make a new frame.
Frame frame = new Frame("xholon/lib/JSME_minimal.html");
frame.setSize("430px", "390px");
// Add it to the root panel.
RootPanel.get().add(frame);
}
/**
* Make a JavaScript object with all the parameters for this external format.
*/
protected native void makeEfParams() /*-{
var p = {};
p.nameTemplate = "R^^^^^";
p.dotBeforeFirst = true;
p.dotBeforeNext = false;
p.tryJsme = false;
this.efParams = p;
}-*/;
public native String getNameTemplate() /*-{return this.efParams.nameTemplate;}-*/;
//public native void setNameTemplate(String nameTemplate) /*-{this.efParams.nameTemplate = nameTemplate;}-*/;
public native boolean isDotBeforeFirst() /*-{return this.efParams.dotBeforeFirst;}-*/;
//public native void setDotBeforeFirst(boolean dotBeforeFirst) /*-{this.efParams.dotBeforeFirst = dotBeforeFirst;}-*/;
public native boolean isDotBeforeNext() /*-{return this.efParams.dotBeforeNext;}-*/;
//public native void setDotBeforeNext(boolean dotBeforeNext) /*-{this.efParams.dotBeforeNext = dotBeforeNext;}-*/;
/**
* Try loading and using JSME, which is a GWT version of JME.
* This is basically a test of using a separate GWT library.
* JSME does NOT import the SMILES format, but it does export it.
*/
public native boolean isTryJsme() /*-{return this.efParams.tryJsme;}-*/;
//public native void setTryJsme(boolean tryJsme) /*-{this.efParams.tryJsme = tryJsme;}-*/;
public String getOutFileName() {
return outFileName;
}
public void setOutFileName(String outFileName) {
this.outFileName = outFileName;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public IXholon getRoot() {
return root;
}
public void setRoot(IXholon root) {
this.root = root;
}
public boolean isShouldShowStateMachineEntities() {
return shouldShowStateMachineEntities;
}
public void setShouldShowStateMachineEntities(
boolean shouldShowStateMachineEntities) {
this.shouldShowStateMachineEntities = shouldShowStateMachineEntities;
}
public String getOutPath() {
return outPath;
}
public void setOutPath(String outPath) {
this.outPath = outPath;
}
}
| 30.783784 | 604 | 0.671642 |
38784c24654e24481cf934b758196a4c521e499b | 512 | package server.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import server.entity.LinkEntity;
import server.service.LinkService;
@RestController
public class GetAllLinksController {
@Autowired
LinkService linkService;
@GetMapping("/loadLinks")
public List<LinkEntity> getAllLinks() {
return linkService.getAllLinks();
}
}
| 21.333333 | 62 | 0.810547 |
8f051d9d1349d35bf2d08039d0417ae2baed7a7d | 2,575 | /*
* Copyright 2012 The Netty Project
* Copyright 2013 Red Hat, Inc.
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.fusesource.hawtdispatch.netty;
import io.netty.channel.*;
import org.fusesource.hawtdispatch.DispatchQueue;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* {@link AbstractHawtEventLoopGroup} implementation which use pre-created shared serial {@link DispatchQueue}s
* between the registered {@link Channel}s.
*
* @author <a href="mailto:[email protected]">Norman Maurer</a>
*/
public class SharedHawtEventLoopGroup extends AbstractHawtEventLoopGroup {
private static final AtomicInteger poolId = new AtomicInteger();
private final EventLoop[] children;
private final AtomicInteger childIndex = new AtomicInteger();
/**
* Create a new instance
*
* @param queue the {@link DispatchQueue} from which the serial {@link DispatchQueue}s will be created.
* @param queueNumber the number of serial {@link DispatchQueue}s created from the given {@link DispatchQueue}
*/
public SharedHawtEventLoopGroup(DispatchQueue queue, int queueNumber) {
if (queueNumber < 1) {
throw new IllegalArgumentException("queueNumber must be >= 1");
}
if (queue == null) {
throw new NullPointerException("queue");
}
children = new EventLoop[queueNumber];
for (int i = 0; i < queueNumber; i++) {
children[i] = new HawtEventLoop(this, queue.createQueue(poolId.get() + "-" + i));
}
}
@Override
public EventLoop next() {
return children[Math.abs(childIndex.getAndIncrement() % children.length)];
}
@Override
protected Set<EventExecutor> children() {
Set<EventExecutor> children = Collections.newSetFromMap(new LinkedHashMap<EventExecutor, Boolean>());
Collections.addAll(children, this.children);
return children;
}
}
| 36.267606 | 116 | 0.699806 |
f97d89d6d5e92c5bac0df21804753304af29cc2c | 2,558 |
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
import org.junit.Test;
import controllers.AcceptController;
import controllers.PlayController;
import controllers.ResumeController;
import controllers.StartController;
public class LogicTest {
public LogicTest() {
}
@Test
public void givenLogicWhenStartNewGameThenControllerIsStartController() {
Logic logic = new Logic();
assertThat(logic.getController(), instanceOf(StartController.class));
}
@Test
public void givenLogicWhenGameIsCancelThenControllerIsResumeController() {
Logic logic = new Logic();
AcceptController controller = logic.getController();
assertThat(controller, instanceOf(StartController.class));
((StartController)controller).start();
controller = (PlayController)logic.getController();
assertThat(controller, instanceOf(PlayController.class));
((PlayController)controller).cancel();
assertThat(logic.getController(), instanceOf(ResumeController.class));
}
@Test
public void givenLogicWhenResumeGameIsNoTheControllerIsNull() {
Logic logic = new Logic();
AcceptController controller = logic.getController();
assertThat(controller, instanceOf(StartController.class));
((StartController)controller).start();
controller = logic.getController();
assertThat(controller, instanceOf(PlayController.class));
((PlayController)controller).cancel();
controller = logic.getController();
assertThat(controller, instanceOf(ResumeController.class));
((ResumeController)controller).resume(false);
assertNull(logic.getController());
}
@Test
public void givenLogicWhenResumeGameIsNoTheControllerPlayController() {
Logic logic = new Logic();
AcceptController controller = logic.getController();
assertThat(controller, instanceOf(StartController.class));
((StartController)controller).start();
controller = logic.getController();
assertThat(controller, instanceOf(PlayController.class));
((PlayController)controller).cancel();
controller = logic.getController();
assertThat(controller, instanceOf(ResumeController.class));
((ResumeController)controller).resume(true);
controller = logic.getController();
assertThat(controller, instanceOf(PlayController.class));
}
} | 34.106667 | 78 | 0.705238 |
e33258f99d1ad9f2293b3d033d58bec5f1c5f943 | 515 | package com.example.first.fragment.news;
/**
* @ClassName: News
* @Description: 描述
* @Author: 范琳琳
* @CreateDate: 2019/4/6 11:31
* @Version: 1.0
*/
public class News {
private String title;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| 16.612903 | 44 | 0.603883 |
96d9acbe558dad15030f9e3b55c71e4fb52a3ae2 | 1,586 | package net.avalara.avatax.rest.client.enums;
/*
* AvaTax Software Development Kit for Java JRE based environments
*
* (c) 2004-2018 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Dustin Welden <[email protected]>
* @copyright 2004-2018 Avalara, Inc.
* @license https://www.apache.org/licenses/LICENSE-2.0
* @link https://github.com/avadev/AvaTax-REST-V2-JRE-SDK
*/
/**
* Represents the type of service or subscription given to a user
*/
public enum ServiceTypeId {
/**
* None
*/
None,
/**
* AvaTaxST
*/
AvaTaxST,
/**
* AvaTaxPro
*/
AvaTaxPro,
/**
* AvaTaxGlobal
*/
AvaTaxGlobal,
/**
* AutoAddress
*/
AutoAddress,
/**
* AutoReturns
*/
AutoReturns,
/**
* TaxSolver
*/
TaxSolver,
/**
* AvaTaxCsp
*/
AvaTaxCsp,
/**
* Twe
*/
Twe,
/**
* Mrs
*/
Mrs,
/**
* AvaCert
*/
AvaCert,
/**
* AuthorizationPartner
*/
AuthorizationPartner,
/**
* CertCapture
*/
CertCapture,
/**
* AvaUpc
*/
AvaUpc,
/**
* AvaCUT
*/
AvaCUT,
/**
* AvaLandedCost
*/
AvaLandedCost,
/**
* AvaLodging
*/
AvaLodging,
/**
* AvaBottle
*/
AvaBottle,
/**
* MRSComplianceManager
*/
MRSComplianceManager,
}
| 13.555556 | 74 | 0.503783 |
f400be98c6742e24e00d4d04e6c8eb670801beff | 2,730 | package com.vaani.leetcode.graph;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* https://leetcode.com/problems/flower-planting-with-no-adjacent/
* <p>
* 1042. Flower Planting With No Adjacent
* Easy
* <p>
* You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
* <p>
* paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
* <p>
* Also, there is no garden that has more than 3 paths coming into or leaving it.
* <p>
* Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
* <p>
* Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.
* <p>
* <p>
* <p>
* Example 1:
* <p>
* Input: N = 3, paths = [[1,2],[2,3],[3,1]]
* Output: [1,2,3]
* <p>
* Example 2:
* <p>
* Input: N = 4, paths = [[1,2],[3,4]]
* Output: [1,2,1,2]
* <p>
* Example 3:
* <p>
* Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
* Output: [1,2,3,4]
* <p>
* <p>
* <p>
* Note:
* <p>
* 1 <= N <= 10000
* 0 <= paths.size <= 20000
* No garden has 4 or more paths coming into or leaving it.
* It is guaranteed an answer exists.
*/
public class FlowerPlantingWithNoAdjacent {
public int[] gardenNoAdj(int N, int[][] paths) {
// Build graph
Map<Integer, Set<Integer>> adj = new HashMap<>();
// Note 1 based graph, not 0 based index
for (int i = 1; i <= N; i++) {
adj.put(i, new HashSet<>());
}
for (int[] path : paths) {
int x = path[0];
int y = path[1];
adj.get(x).add(y);
adj.get(y).add(x);
}
int[] ans = new int[N]; // Note answer is 0 based
int numColors = 4;
//Just mark all the colors that have been used by the neighbours
//and then paint color which is not used by the neigbours.
//there will always be atleast one unused color.
for (int u = 1; u <= N; u++) {
boolean[] colorUsed = new boolean[numColors + 1]; //Use 5 instead of 4 so we can easily use 1-based indexing
for (int v : adj.get(u)) {
colorUsed[ans[v - 1]] = true;//Mark the color as used if neighbor has used it before.
}
for (int c = 1; c <= numColors; c++) {
if (!colorUsed[c]) {
ans[u - 1] = c;
break;//not necessary
}
}
}
return ans;
}
}
| 31.37931 | 198 | 0.553846 |
09d5a0c83d6deb684683cbe07447db10f0f0dff7 | 4,223 | /**
* Copyright 2004-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kpme.core.bo;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.kuali.kpme.core.cache.CacheUtils;
import org.kuali.kpme.core.util.TKUtils;
import org.kuali.rice.kns.service.KNSServiceLocator;
import org.kuali.rice.krad.maintenance.MaintainableImpl;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;
public abstract class HrDataObjectMaintainableImpl extends MaintainableImpl {
protected static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(HrDataObjectMaintainableImpl.class);
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void saveDataObject() {
HrBusinessObject hrObj = (HrBusinessObject) this.getDataObject();
if(hrObj.getId()!=null){
HrBusinessObject oldHrObj = this.getObjectById(hrObj.getId());
if(oldHrObj!= null){
//if the effective dates are the same do not create a new row just inactivate the old one
if(hrObj.getEffectiveDate().equals(oldHrObj.getEffectiveDate())){
oldHrObj.setActive(false);
oldHrObj.setTimestamp(TKUtils.subtractOneSecondFromTimestamp(new Timestamp(DateTime.now().getMillis())));
} else{
//if effective dates not the same add a new row that inactivates the old entry based on the new effective date
oldHrObj.setTimestamp(TKUtils.subtractOneSecondFromTimestamp(new Timestamp(DateTime.now().getMillis())));
oldHrObj.setEffectiveDate(hrObj.getEffectiveDate());
oldHrObj.setActive(false);
oldHrObj.setId(null);
customInactiveSaveLogicNewEffective(oldHrObj);
}
KRADServiceLocatorWeb.getLegacyDataAdapter().save(oldHrObj);
}
}
hrObj.setTimestamp(new Timestamp(System.currentTimeMillis()));
hrObj.setId(null);
customSaveLogic(hrObj);
KRADServiceLocatorWeb.getLegacyDataAdapter().save(hrObj);
//cache clearing?!?!
try {
List<String> cacheNames = (List<String>)hrObj.getClass().getDeclaredField("CACHE_FLUSH").get(hrObj);
CacheUtils.flushCaches(cacheNames);
} catch (NoSuchFieldException e) {
try {
String cacheName = (String)hrObj.getClass().getDeclaredField("CACHE_NAME").get(hrObj);
CacheUtils.flushCache(cacheName);
} catch (NoSuchFieldException ex) {
// no cache name found
LOG.warn("No cache name found for object: " + hrObj.getClass().getName());
} catch (IllegalAccessException ex) {
LOG.warn("No cache name found for object: " + hrObj.getClass().getName());
}
// no cache name found
//LOG.warn("No cache name found for object: " + hrObj.getClass().getName());
} catch (IllegalAccessException e) {
LOG.warn("No caches found for object: " + hrObj.getClass().getName());
}
}
public abstract HrBusinessObject getObjectById(String id);
public void customSaveLogic(HrBusinessObject hrObj){}
public void customInactiveSaveLogicNewEffective(HrBusinessObject oldHrObj) {}
@Override
public void prepareForSave() {
HrBusinessObject hrObj = (HrBusinessObject) this.getDataObject();
hrObj.setUserPrincipalId(GlobalVariables.getUserSession().getPrincipalId());
}
}
| 42.23 | 128 | 0.696661 |
313b38c6e0ef05175894f5df487ad74750b68e80 | 285 | package com.javahelps.smartagent.monitor;
/**
* Created by gobinath on 18/07/17.
*/
public interface Monitor {
void start();
void stop();
void addStateChangeListener(StateChangeListener listener);
void removeStateChangeListener(StateChangeListener listener);
}
| 16.764706 | 65 | 0.733333 |
246e86569750426a0a5cbf53785f83f957d58242 | 225 | package com.linkedin.jsf;
import java.io.Serializable;
public interface InventoryService extends Serializable {
public void createItem(Long catalogItemId, String name);
public Long getQuantity(Long catalogItemId);
}
| 18.75 | 57 | 0.8 |
25e105fb4a604b5ac88af86bb83c807061f7e4f6 | 3,661 | package eu.humanbrainproject.mip.algorithms.serializers.pfa;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.humanbrainproject.mip.algorithms.NullableInputAlgorithm;
import eu.humanbrainproject.mip.algorithms.SimpleAlgorithm;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisplayName("InputDescription should")
public class InputDescriptionTest {
private static final SimpleAlgorithm SIMPLE_ALGORITHM = new SimpleAlgorithm();
private static final NullableInputAlgorithm NULLABLE_INPUT_ALGORITHM = new NullableInputAlgorithm();
private static final ObjectMapper MAPPER = new ObjectMapper();
private StringWriter writer;
private JsonGenerator generator;
@BeforeEach
void setUp() throws Exception {
JsonFactory factory = new JsonFactory();
writer = new StringWriter();
generator = factory.createGenerator(writer);
generator.setCodec(new ObjectMapper());
}
@Test
@DisplayName("describe the query used during the training of the model")
public void testWriteQuery() throws Exception {
NumericalInputDescription inputDescription = new NumericalInputDescription(SIMPLE_ALGORITHM);
generator.writeStartObject();
inputDescription.writeQuery(generator);
generator.writeEndObject();
generator.close();
assertJsonEquals(writer.toString(), "input_query.fragment.json");
}
@Test
@DisplayName("indicate in the metadata that the predictive algorithm does not accepts missing values in the input data")
public void testWriteInputMetadataNoMissingValues() throws Exception {
InputDescription inputDescription = new NumericalInputDescription(SIMPLE_ALGORITHM);
generator.writeStartObject();
inputDescription.writeInputMetadata(generator);
generator.writeEndObject();
generator.close();
assertJsonEquals(writer.toString(), "does_not_accept_missing_values.fragment.json");
}
@Test
@DisplayName("indicate in the metadata that the predictive algorithm supports missing values in the input data")
public void testWriteInputMetadataSupportsMissingValues() throws Exception {
InputDescription inputDescription = new NullableInputDescription(NULLABLE_INPUT_ALGORITHM);
generator.writeStartObject();
inputDescription.writeInputMetadata(generator);
generator.writeEndObject();
generator.close();
assertJsonEquals(writer.toString(), "accepts_missing_values.fragment.json");
}
@Test
@DisplayName("describe the type of the output for single output values")
public void testWritePfaOutput() throws Exception {
InputDescription inputDescription = new NumericalInputDescription(SIMPLE_ALGORITHM);
generator.writeStartObject();
inputDescription.writePfaOutput(generator);
generator.writeEndObject();
generator.close();
assertJsonEquals(writer.toString(), "single_output.fragment.json");
}
private void assertJsonEquals(String jsonDocument, String pathToExpected) throws IOException {
final JsonNode jsonTest = MAPPER.readTree(jsonDocument);
final JsonNode jsonExpected = MAPPER.readTree(getClass().getResource(pathToExpected));
assertEquals(jsonExpected, jsonTest);
}
}
| 36.61 | 124 | 0.751707 |
97cd992398e0334b4b5518dca530a8c724486fc7 | 108 | package com.appjangle.opsunit;
public interface JobContext {
public JobListener getListener();
}
| 13.5 | 35 | 0.731481 |
5cef2ee90fb35aa2b669023c67f3a1295c52fc77 | 105 | package com.br.zupacademy.hugo.mercadolivre.compra;
public enum Status {
INICIADA,
FINALIZADA
}
| 15 | 51 | 0.742857 |
b38ca14d42e98d7a5b9a210139bcb52257ab2bbb | 1,019 | package hw;
import java.util.Scanner;
/*志明跟春嬌是班上的一對情侶,他們有寫交換日記來打發時間的習慣,為了防止他們 寫的內容被幫忙傳的同學,或者是不小心被老師沒收,而曝光了裡面寫的東西,他們 想到了一個辦法,就是把內容的所有字母都往後數幾次的字母替代,而往後數幾次的 數目就寫在內容的下一行。但是,問題來了,春嬌覺得每次寫完都要在數來數去的轉 化成”加密”格式,實在是太麻煩了。但又礙於不想被輕易的看到內容,於是她拜託你 寫個程式幫忙她可以直接把寫好的內容轉化成”加密”的型態。加密結果不會影響原字 母的大小寫,且數字部分亦作相同處理,但不處理符號及特殊字元及中文。(第一行為想輸入的內容,不超過 100 個字,第二行為打完你想輸入的內容之後,換 行輸入你想要往後替代的數目)
* Date: 2016/12/12
* Author: 105021038 傅琬鈞
*/
public class hw01 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
int n = scn.nextInt();
for (int i = 0; i < str.length(); i++) {
char a = str.charAt(i);
if (a >= 65 && a <= 90) {
if (a + n > 90) {
System.out.print((char) (a - 25 + n - 1));
} else {
System.out.print((char) (a + n));
}
} else if (a >= 97 && a <= 122) {
if (a + n > 122) {
System.out.print((char) (a - 25 + n - 1));
} else {
System.out.print((char) (a + n));
}
} else {
System.out.print((char) a);
}
}
}
}
| 29.970588 | 320 | 0.62316 |
c4c5363708acaa32dc480d9fce953baeb39908b4 | 15,967 | package com.seq.api;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.seq.exception.*;
import com.seq.http.*;
/**
* A transaction is an atomic update to the state of the ledger. Transactions
* can issue new flavor units, transfer flavor units from one account to
* another, and/or retire flavor units from an account.
*/
public class Transaction {
/**
* A unique ID.
*/
@Expose
public String id;
/**
* Time of transaction.
*/
@Expose
public Date timestamp;
/**
* Sequence number of the transaction.
*/
@SerializedName("sequence_number")
@Expose
public long sequenceNumber;
/**
* List of actions taken by the transaction.
*/
@Expose
public List<Action> actions;
/**
* User-specified key-value data embedded into the transaction.
*/
@Expose
public Map<String, Object> tags;
/**
* A single page of transactions returned from a query.
*/
public static class Page extends BasePage<Transaction> {}
/**
* Iterable interface for consuming individual transactions from a query.
*/
public static class ItemIterable extends BaseItemIterable<Transaction> {
public ItemIterable(Client client, String path, Query nextQuery) {
super(client, path, nextQuery, Page.class);
}
}
/**
* A builder class for listing transactions in the ledger.
*/
public static class ListBuilder extends BaseQueryBuilder<ListBuilder> {
/**
* Executes the query, returning a page of transactions.
* @param client ledger API connection object
* @return a page of transactions
* @throws ChainException
*/
public Page getPage(Client client) throws ChainException {
return client.request("list-transactions", this.next, Page.class);
}
/**
* Executes the query, returning a page of transactions that match the query
* beginning with provided cursor.
* @param client ledger API connection object
* @param cursor string representing encoded query object
* @return a page of transactions
* @throws ChainException
*/
public Page getPage(Client client, String cursor) throws ChainException {
Query next = new Query();
next.cursor = cursor;
return client.request("list-transactions", next, Page.class);
}
/**
* Executes the query, returning an iterable over transactions that match
* the query.
* @param client ledger API connection object
* @return an iterable over transactions
* @throws ChainException
*/
public ItemIterable getIterable(Client client) throws ChainException {
return new ItemIterable(client, "list-transactions", this.next);
}
}
/**
* An action taken by a transaction.
*/
public static class Action {
/**
* A unique ID.
*/
@Expose
public String id;
/**
* The type of the action. Possible values are "issue", "transfer" and "retire".
*/
@Expose
public String type;
/**
* The id of the action's flavor.
*/
@SerializedName("flavor_id")
@Expose
public String flavorId;
/**
* A copy of the associated tags (flavor, source account, destination
* account, action, and token) as they existed at the time of the
* transaction.
*/
@SerializedName("snapshot")
@Expose
public Snapshot snapshot;
/**
* The number of flavor units issued, transferred, or retired.
*/
@Expose
public long amount;
/**
* The ID of the account serving as the source of flavor units. Null for
* issuances.
*/
@SerializedName("source_account_id")
@Expose
public String sourceAccountId;
/**
* The ID of the account receiving the flavor units. Null for retirements.
*/
@SerializedName("destination_account_id")
@Expose
public String destinationAccountId;
/**
* User-specified, key-value data embedded into the action.
*/
@SerializedName("tags")
@Expose
public Map<String, Object> tags;
public static class Snapshot {
/**
* A snapshot of the actions's tags at the time of action creation
*/
@SerializedName("action_tags")
@Expose
public Map<String, Object> actionTags;
/**
* A snapshot of the flavor's tags at the time of action creation
*/
@SerializedName("flavor_tags")
@Expose
public Map<String, Object> flavorTags;
/**
* A snapshot of the source account's tags at the time of action creation
*/
@SerializedName("source_account_tags")
@Expose
public Map<String, Object> sourceAccountTags;
/**
* A snapshot of the destination account's tags at the time of action creation
*/
@SerializedName("destination_account_tags")
@Expose
public Map<String, Object> destinationAccountTags;
/**
* A snapshot of the tokens's tags at the time of action creation
*/
@SerializedName("token_tags")
@Expose
public Map<String, Object> tokenTags;
/**
* A snapshot of the transaction's tags at the time of action creation
*/
@SerializedName("transaction_tags")
@Expose
public Map<String, Object> transactionTags;
}
}
/**
* A configuration object for creating and submitting transactions.
*/
public static class Builder {
@Expose
protected List<Action> actions;
@SerializedName("transaction_tags")
@Expose
protected Map<String, Object> transactionTags;
/**
* Builds, signs, and submits a tranasaction.
* @param client ledger API connection object
* @return the submitted transaction object
* @throws ChainException
*/
public Transaction transact(Client client) throws ChainException {
return client.request("transact", this, Transaction.class);
}
public Builder() {
this.actions = new ArrayList<>();
this.transactionTags = new HashMap<>();
}
/**
* Adds an action to a transaction builder.
* @param action action to add
* @return updated builder
*/
public Builder addAction(Action action) {
this.actions.add(action);
return this;
}
/**
* Adds a key-value pair to the transaction's tags.
* @param key key of the tag field
* @param value value of tag field
* @return updated builder
*/
public Builder addTransactionTagsField(String key, Object value) {
this.transactionTags.put(key, value);
return this;
}
/**
* Base class representing actions that can be taken within a transaction.
*/
public static class Action extends HashMap<String, Object> {
public Action() {}
protected void addKeyValueField(String mapKey, String fieldKey, Object value) {
Map<String, Object> keyValueData = (Map<String, Object>) get(mapKey);
if (keyValueData == null) {
keyValueData = new HashMap<String, Object>();
put(mapKey, keyValueData);
}
keyValueData.put(fieldKey, value);
}
protected void addListItem(String mapKey, Object param) {
List<Object> filterParams = (ArrayList<Object>) get(mapKey);
if (filterParams == null) {
filterParams = new ArrayList<Object>();
put(mapKey, filterParams);
}
filterParams.add(param);
}
/**
* Issues new units of a flavor to a destination account.
*/
public static class Issue extends Action {
public Issue() {
put("type", "issue");
}
/**
* Specifies the flavor, identified by its ID, to be issued.
* @param id ID of a flavor
* @return updated action
*/
public Issue setFlavorId(String id) {
put("flavor_id", id);
return this;
}
/**
* Specifies the amount to be issued.
* @param amount number of flavor units
* @return updated action
*/
public Issue setAmount(long amount) {
put("amount", amount);
return this;
}
/**
* Specifies the destination account, identified by its ID. You must
* specify a destination account ID.
* @param id an account ID
* @return updated action
*/
public Issue setDestinationAccountId(String id) {
put("destination_account_id", id);
return this;
}
/**
* Specifies tags for the tokens output by the action.
* @param tokenTags arbitrary key-value data
* @return updated action
*/
public Issue setTokenTags(Map<String, Object> tokenTags) {
put("token_tags", tokenTags);
return this;
}
/**
* Adds a key-value pair to the tokens output by the action.
* @param key key of the token tag field
* @param value value of token tag field
* @return updated action
*/
public Issue addTokenTagsField(String key, Object value) {
addKeyValueField("token_tags", key, value);
return this;
}
/**
* Specifies tags for the action.
* @param actionTags arbitrary key-value data
* @return updated action
*/
public Issue setActionTags(Map<String, Object> actionTags) {
put("action_tags", actionTags);
return this;
}
/**
* Adds a key-value pair to the tags for the action.
* @param key key of the action tags field
* @param value value of action tags field
* @return updated action
*/
public Issue addActionTagsField(String key, Object value) {
addKeyValueField("action_tags", key, value);
return this;
}
}
/**
* Moves flavors from a source account to a destination account.
*/
public static class Transfer extends Action {
public Transfer() {
put("type", "transfer");
}
/**
* Specifies an account, identified by its ID, as the source of the
* flavor units to be transferred. You must specify a source account ID.
* @param id an account ID
* @return updated action
*/
public Transfer setSourceAccountId(String id) {
put("source_account_id", id);
return this;
}
/**
* Specifies the flavor, identified by its ID, to be transferred.
* @param id ID of a flavor
* @return updated action
*/
public Transfer setFlavorId(String id) {
put("flavor_id", id);
return this;
}
/**
* Specifies the amount to be transferred.
* @param amount number of flavor units
* @return updated action
*/
public Transfer setAmount(long amount) {
put("amount", amount);
return this;
}
/**
* Specifies the destination account, identified by its ID. You must
* specify a destination account ID.
* @param id an account ID
* @return updated action
*/
public Transfer setDestinationAccountId(String id) {
put("destination_account_id", id);
return this;
}
/**
* Specifies tags for the tokens output by the action.
* @param tokenTags arbitrary key-value data
* @return updated action
*/
public Transfer setTokenTags(Map<String, Object> tokenTags) {
put("token_tags", tokenTags);
return this;
}
/**
* Adds a key-value pair to the tokens output by the action.
* @param key key of the token tag field
* @param value value of token tag field
* @return updated action
*/
public Transfer addTokenTagsField(String key, Object value) {
addKeyValueField("token_tags", key, value);
return this;
}
/**
* Specifies tags for the action.
* @param actionTags arbitrary key-value data
* @return updated action
*/
public Transfer setActionTags(Map<String, Object> actionTags) {
put("action_tags", actionTags);
return this;
}
/**
* Adds a key-value pair to the tags for the action.
* @param key key of the action tags field
* @param value value of action tags field
* @return updated action
*/
public Transfer addActionTagsField(String key, Object value) {
addKeyValueField("action_tags", key, value);
return this;
}
/**
* Token filter string. See {https://dashboard.seq.com/docs/filters}.
* @param filter a filter expression
* @return updated action
*/
public Transfer setFilter(String filter) {
put("filter", filter);
return this;
}
/**
* A list of parameter values for filter string (if needed).
* @param param a filter parameter
* @return updated action
*/
public Transfer addFilterParameter(Object param) {
addListItem("filter_params", param);
return this;
}
}
/**
* Moves flavors from a source account to a destination account.
*/
public static class Retire extends Action {
public Retire() {
put("type", "retire");
}
/**
* Specifies an account, identified by its ID, as the source of the
* tokens to be retired. You must specify a source account ID.
* @param id an account ID
* @return updated action
*/
public Retire setSourceAccountId(String id) {
put("source_account_id", id);
return this;
}
/**
* Specifies the flavor, identified by its ID, to be retired.
* @param id ID of a flavor
* @return updated action
*/
public Retire setFlavorId(String id) {
put("flavor_id", id);
return this;
}
/**
* Specifies the amount to be retired.
* @param amount number of flavor units
* @return updated action
*/
public Retire setAmount(long amount) {
put("amount", amount);
return this;
}
/**
* Specifies tags for the action.
* @param actionTags arbitrary key-value data
* @return updated action
*/
public Retire setActionTags(Map<String, Object> actionTags) {
put("action_tags", actionTags);
return this;
}
/**
* Adds a key-value pair to the tags for the action.
* @param key key of the action tags field
* @param value value of action tags field
* @return updated action
*/
public Retire addActionTagsField(String key, Object value) {
addKeyValueField("action_tags", key, value);
return this;
}
/**
* Token filter string. See {https://dashboard.seq.com/docs/filters}.
* @param filter a filter expression
* @return updated action
*/
public Retire setFilter(String filter) {
put("filter", filter);
return this;
}
/**
* A list of parameter values for filter string (if needed).
* @param param a filter parameter
* @return updated action
*/
public Retire addFilterParameter(Object param) {
addListItem("filter_params", param);
return this;
}
}
}
}
}
| 28.461676 | 85 | 0.591533 |
7d7d321a5adc0003d090332bf5785c2f578bb57d | 179 | package io.renren.modules.app.entity;
import lombok.Data;
@Data
public class AccessToken {
private String token;
private Integer expiresIn;
private Long tokenTime;
} | 17.9 | 37 | 0.748603 |
cf63f9bfd1c6ece0b36f382690cd70e8a3716c9c | 1,117 | package com.ruisi.vdop.bean;
import java.util.UUID;
public class Summary
{
private String summary_id;
private String act_id;
private String act_bg;
private String act_exp;
private String act_creativity;
private String act_lesson;
public Summary()
{
this.summary_id = UUID.randomUUID().toString();
}
public String getSummary_id() {
return summary_id;
}
public void setSummary_id(String summary_id) {
this.summary_id = summary_id;
}
public String getAct_id() {
return act_id;
}
public void setAct_id(String act_id) {
this.act_id = act_id;
}
public String getAct_bg() {
return act_bg;
}
public void setAct_bg(String act_bg) {
this.act_bg = act_bg;
}
public String getAct_exp() {
return act_exp;
}
public void setAct_exp(String act_exp) {
this.act_exp = act_exp;
}
public String getAct_creativity() {
return act_creativity;
}
public void setAct_creativity(String act_creativity) {
this.act_creativity = act_creativity;
}
public String getAct_lesson() {
return act_lesson;
}
public void setAct_lesson(String act_lesson) {
this.act_lesson = act_lesson;
}
}
| 19.946429 | 55 | 0.735004 |
4c96d4b4049fc63734da065c3f5a06f7dfb5c62c | 3,971 | /***************************************************************************
* Copyright 2017 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.examples.userguide.ch3and4bookstore;
import java.io.File;
import java.util.concurrent.TimeUnit;
import kieker.analysis.AnalysisController;
import kieker.analysis.IAnalysisController;
import kieker.analysis.analysisComponent.AbstractAnalysisComponent;
import kieker.common.configuration.Configuration;
public final class Starter {
private Starter() {}
public static void main(final String[] args) throws Exception {
// Spawn a thread that performs asynchronous requests
// to a bookstore.
new Thread(new Runnable() {
@Override
public void run() {
final Bookstore bookstore = new Bookstore();
for (int i = 0; i < 5; i++) {
System.out.println("Bookstore.main: Starting request " + i);
bookstore.searchBook();
}
}
}).start();
// Create a new analysis controller for our response time analysis.
final IAnalysisController analysisController = new AnalysisController();
// Configure and register the reader
final Configuration readerConfig = new Configuration();
readerConfig.setProperty(MyPipeReader.CONFIG_PROPERTY_NAME_PIPE_NAME, "somePipe");
final MyPipeReader reader = new MyPipeReader(readerConfig, analysisController);
// Configure, register, and connect the response time filter
final Configuration filterConfig = new Configuration();
final long rtThresholdNanos =
TimeUnit.NANOSECONDS.convert(1900, TimeUnit.MICROSECONDS);
filterConfig.setProperty( // configure threshold of 1.9 milliseconds:
MyResponseTimeFilter.CONFIG_PROPERTY_NAME_TS_NANOS,
Long.toString(rtThresholdNanos));
final MyResponseTimeFilter filter = new MyResponseTimeFilter(filterConfig, analysisController);
analysisController.connect(reader, MyPipeReader.OUTPUT_PORT_NAME, filter, MyResponseTimeFilter.INPUT_PORT_NAME_RESPONSE_TIMES);
// Configure, register, and connect the filter printing *valid* response times
final Configuration validOutputConfig = new Configuration();
validOutputConfig.setProperty(MyResponseTimeOutputPrinter.CONFIG_PROPERTY_NAME_VALID_OUTPUT, Boolean.toString(true));
validOutputConfig.setProperty(AbstractAnalysisComponent.CONFIG_NAME, "Print valid");
final MyResponseTimeOutputPrinter validPrinter = new MyResponseTimeOutputPrinter(validOutputConfig, analysisController);
analysisController.connect(filter, MyResponseTimeFilter.OUTPUT_PORT_NAME_RT_VALID, validPrinter, MyResponseTimeOutputPrinter.INPUT_PORT_NAME_EVENTS);
// Configure, register, and connect the filter printing *invalid* response times
final Configuration invalidOutputConfig = new Configuration();
invalidOutputConfig.setProperty(MyResponseTimeOutputPrinter.CONFIG_PROPERTY_NAME_VALID_OUTPUT, Boolean.toString(false));
invalidOutputConfig.setProperty(AbstractAnalysisComponent.CONFIG_NAME, "Print invalid");
final MyResponseTimeOutputPrinter invalidPrinter = new MyResponseTimeOutputPrinter(invalidOutputConfig, analysisController);
analysisController.connect(filter, MyResponseTimeFilter.OUTPUT_PORT_NAME_RT_EXCEED, invalidPrinter, MyResponseTimeOutputPrinter.INPUT_PORT_NAME_EVENTS);
analysisController.saveToFile(new File("out.kax"));
// Start the analysis.
analysisController.run();
}
}
| 46.717647 | 154 | 0.768572 |
c8ca94c5271f6b5e1c606cefab3d12106a0d51ff | 4,604 | package info.u_team.u_team_core.screen;
import java.util.ArrayList;
import java.util.List;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import info.u_team.u_team_core.gui.renderer.FluidInventoryRenderer;
import info.u_team.u_team_core.intern.init.UCoreNetwork;
import info.u_team.u_team_core.intern.network.FluidClickContainerMessage;
import info.u_team.u_team_core.menu.FluidContainerMenu;
import info.u_team.u_team_core.menu.FluidSlot;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraftforge.registries.ForgeRegistries;
public abstract class FluidMenuContainerScreen<T extends AbstractContainerMenu> extends AbstractContainerScreen<T> {
private static final FluidInventoryRenderer FLUID_RENDERER = new FluidInventoryRenderer();
protected FluidInventoryRenderer fluidRenderer;
protected FluidSlot hoveredFluidSlot;
public FluidMenuContainerScreen(T container, Inventory playerInventory, Component title) {
super(container, playerInventory, title);
setFluidRenderer(FLUID_RENDERER);
}
protected void setFluidRenderer(FluidInventoryRenderer fluidRenderer) {
this.fluidRenderer = fluidRenderer;
}
@Override
protected void renderLabels(PoseStack matrixStack, int mouseX, int mouseY) {
if (menu instanceof FluidContainerMenu) {
hoveredFluidSlot = null;
final var fluidContainer = (FluidContainerMenu) menu;
for (var index = 0; index < fluidContainer.fluidSlots.size(); index++) {
final var fluidSlot = fluidContainer.fluidSlots.get(index);
if (fluidSlot.isEnabled()) {
drawFluidSlot(matrixStack, fluidSlot);
if (isFluidSlotSelected(fluidSlot, mouseX, mouseY)) {
hoveredFluidSlot = fluidSlot;
final var x = fluidSlot.getX();
final var y = fluidSlot.getY();
RenderSystem.disableDepthTest();
RenderSystem.colorMask(true, true, true, false);
final var slotColor = getFluidSlotColor(index);
fillGradient(matrixStack, x, y, x + 16, y + 16, slotColor, slotColor);
RenderSystem.colorMask(true, true, true, true);
RenderSystem.enableDepthTest();
}
}
}
}
}
@Override
protected void renderTooltip(PoseStack matrixStack, int mouseX, int mouseY) {
super.renderTooltip(matrixStack, mouseX, mouseY);
if (menu.getCarried().isEmpty() && hoveredFluidSlot != null && !hoveredFluidSlot.getStack().isEmpty()) {
renderComponentTooltip(matrixStack, getTooltipFromFluid(hoveredFluidSlot), mouseX, mouseY);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (button == 0) {
final var fluidSlot = getSelectedFluidSlot(mouseX, mouseY);
if (fluidSlot != null) {
if (!menu.getCarried().isEmpty()) {
UCoreNetwork.NETWORK.sendToServer(new FluidClickContainerMessage(menu.containerId, fluidSlot.index, hasShiftDown(), menu.getCarried()));
}
return true;
}
}
return super.mouseClicked(mouseX, mouseY, button);
}
protected void drawFluidSlot(PoseStack matrixStack, FluidSlot fluidSlot) {
fluidRenderer.drawFluid(matrixStack, fluidSlot.getX(), fluidSlot.getY(), fluidSlot.getStack());
}
protected boolean isFluidSlotSelected(FluidSlot fluidSlot, double mouseX, double mouseY) {
return isHovering(fluidSlot.getX(), fluidSlot.getY(), 16, 16, mouseX, mouseY);
}
public int getFluidSlotColor(int index) {
return super.getSlotColor(index);
}
public List<Component> getTooltipFromFluid(FluidSlot fluidSlot) {
final var stack = fluidSlot.getStack();
final List<Component> list = new ArrayList<>();
list.add(stack.getDisplayName());
list.add(new TextComponent(stack.getAmount() + " / " + fluidSlot.getSlotCapacity()).withStyle(ChatFormatting.GRAY));
if (minecraft.options.advancedItemTooltips) {
list.add((new TextComponent(ForgeRegistries.FLUIDS.getKey(stack.getFluid()).toString())).withStyle(ChatFormatting.DARK_GRAY));
}
return list;
}
private FluidSlot getSelectedFluidSlot(double mouseX, double mouseY) {
if (menu instanceof FluidContainerMenu) {
final var fluidContainer = (FluidContainerMenu) menu;
for (final FluidSlot fluidSlot : fluidContainer.fluidSlots) {
if (isFluidSlotSelected(fluidSlot, mouseX, mouseY) && fluidSlot.isEnabled()) {
return fluidSlot;
}
}
}
return null;
}
}
| 35.145038 | 141 | 0.754996 |
70e3f6374601181cd3b88fa628e5b92906f269e1 | 3,831 | //给你 k 枚相同的鸡蛋,并可以使用一栋从第 1 层到第 n 层共有 n 层楼的建筑。
//
// 已知存在楼层 f ,满足 0 <= f <= n ,任何从 高于 f 的楼层落下的鸡蛋都会碎,从 f 楼层或比它低的楼层落下的鸡蛋都不会破。
//
// 每次操作,你可以取一枚没有碎的鸡蛋并把它从任一楼层 x 扔下(满足 1 <= x <= n)。如果鸡蛋碎了,你就不能再次使用它。如果某枚鸡蛋扔下后没有摔碎
//,则可以在之后的操作中 重复使用 这枚鸡蛋。
//
// 请你计算并返回要确定 f 确切的值 的 最小操作次数 是多少?
//
//
// 示例 1:
//
//
//输入:k = 1, n = 2
//输出:2
//解释:
//鸡蛋从 1 楼掉落。如果它碎了,肯定能得出 f = 0 。
//否则,鸡蛋从 2 楼掉落。如果它碎了,肯定能得出 f = 1 。
//如果它没碎,那么肯定能得出 f = 2 。
//因此,在最坏的情况下我们需要移动 2 次以确定 f 是多少。
//
//
// 示例 2:
//
//
//输入:k = 2, n = 6
//输出:3
//
//
// 示例 3:
//
//
//输入:k = 3, n = 14
//输出:4
//
//
//
//
// 提示:
//
//
// 1 <= k <= 100
// 1 <= n <= 10⁴
//
// Related Topics 数学 二分查找 动态规划 👍 740 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.Map;
//java:鸡蛋掉落
class SuperEggDrop{
public static void main(String[] args){
Solution solution = new SuperEggDrop().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
/*
状态定义:dp[i][j] 使用 i 个鸡蛋,一共有 j 层楼梯(注意:这里 j 不表示高度,表示区间楼层数量)的情况下的最少实验的次数。
初始状态:
区间楼层数为0,不可能测出鸡蛋的个数 dp[0][j] = 0;
区间楼层数为1,0个鸡蛋,测不出,大于等于1个鸡蛋都只要扔一次
鸡蛋个数为0,测不出
鸡蛋个数为1,区间楼层数为几要测几次
状态转移方程:
在x层蛋碎了,得到dp[i][j]的结果的实验在x层下面做(先不管哪一层,就知道在下面,剩余层数k-1):dp[i][j] = dp[x-1][j-1]
在x层蛋没碎,得到dp[i][j]的结果的实验在x层下面做:dp[i][j] = dp[i][j-x]
求最坏情况下扔鸡蛋的最小次数,所以鸡蛋在第 i 层楼碎没碎,取决于哪种情况的结果更大,在该层又扔一次所以 +1
res = min(res, max(dp(K - 1, i - 1), dp(K, N - i)) + 1)
二分查找优化:
根据 dp(K,N)数组的定义(有K个鸡蛋面对N层楼,最少需要扔几次),K固定时,函数随着N的增加单调递增
注意 dp(K-1, i-1) 和 dp(K, N-i) 这两个函数
i是从 1 到 N 单增的,固定 K 和 N,把这两个函数看做关于 i 的函数,“碎了”随着 i 的增加单调递增的,“不碎”随着 i 的增加单调递减的
这时求 min(res, max(dp(K - 1, i - 1), dp(K, N - i)) + 1),就是求两条函数直线的交点
使用二分查找找“山谷”的
*/
// 构造备忘录
Map<Integer, Integer> memo = new HashMap<>();
public int superEggDrop(int K, int N) {
if (N == 0) {
return 0;
} else if (K == 1) {
return N;
}
// 构造 key,保证key唯一,K <= 100,所以N*1000
Integer key = N * 1000 + K;
if (memo.containsKey(key)) {
return memo.get(key);
}
// 用二分搜索代替线性搜索
int low = 1, high = N;
int res = Integer.MAX_VALUE;
while (low <= high) {
int mid = (low + high) / 2;
int broken = superEggDrop(K - 1, mid - 1);
int notBroken = superEggDrop(K, N - mid);
// 当碎了比不碎大,往小了找
if (broken > notBroken) {
high = mid - 1;
res = Math.min(res, broken + 1);
} else {
low = mid + 1;
res = Math.min(res, notBroken + 1);
}
}
memo.put(key, res);
return res;
}
// dp解法
public int _superEggDrop(int K, int N) {
int[][] dp = new int[K + 1][N + 1];
for (int i = 1; i <= N; i++) {
dp[1][i] = i; // only one egg
dp[0][i] = 0; // no egg
}
for (int i = 1; i <= K; i++) {
dp[i][0] = 0; // zero floor
}
for (int k = 2; k <= K; k++) { // start from two egg
for (int n = 1; n <= N; n++) {
int tMinDrop = Integer.MAX_VALUE;
for (int x = 1; x <= n; x++) {
tMinDrop = Math.min(tMinDrop, 1 + Math.max(dp[k - 1][x - 1], dp[k][n - x]));
}
dp[k][n] = tMinDrop;
}
}
return dp[K][N];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| 28.377778 | 100 | 0.453667 |
75537ded12764562c7e2858101676010346dcc85 | 1,018 | package de.mpicbg.knime.knutils;
import org.knime.core.data.*;
import java.util.HashSet;
import java.util.Set;
/**
* An atttribute implementation that allows for an automatic creation of a proper attribute domain.
*
* @author Holger Brandl
*/
public class DomainCacheAttribute extends Attribute {
private Set<DataCell> domain = new HashSet<DataCell>();
public DomainCacheAttribute(String attributeName, DataType type) {
super(attributeName, type);
}
public DataColumnSpec getColumnSpec() {
DataColumnSpecCreator columnSpecCreator = new DataColumnSpecCreator(getName(), getType());
if (!domain.isEmpty()) {
DataColumnDomain dataColumnDomain = new DataColumnDomainCreator(domain).createDomain();
columnSpecCreator.setDomain(dataColumnDomain);
}
return columnSpecCreator.createSpec();
}
@Override
protected DataCell postProcessCreatedCell(DataCell cell) {
domain.add(cell);
return cell;
}
}
| 23.674419 | 99 | 0.699411 |
0b1841e2be0597afda07d4d99819d124f731583d | 3,150 | package br.com.apssystem.algafood.api.controller;
import br.com.apssystem.algafood.api.controller.openapi.controller.CozinhaControllerOpenApi;
import br.com.apssystem.algafood.api.mapper.CozinhaMapper;
import br.com.apssystem.algafood.api.model.CozinhaModel;
import br.com.apssystem.algafood.api.model.input.CozinhaInput;
import br.com.apssystem.algafood.core.utils.ResourceUriHelper;
import br.com.apssystem.algafood.domain.model.Cozinha;
import br.com.apssystem.algafood.domain.service.CozinhaService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(path = "/cozinhas", produces = MediaType.APPLICATION_JSON_VALUE)
@AllArgsConstructor
public class CozinhaController implements CozinhaControllerOpenApi {
private CozinhaService serivce;
private CozinhaMapper mapper;
private PagedResourcesAssembler<Cozinha> pagedResourcesAssembler;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CozinhaModel salvar(@Valid @RequestBody CozinhaInput cozinhaInput) {
Cozinha cozinha = mapper.toDomainObject(cozinhaInput);
ResourceUriHelper.addUriInResponseHeader(cozinha.getId());
return mapper.toModel(serivce.salvar(cozinha));
}
@PutMapping("/{id}")
public CozinhaModel atualizar(@Valid @RequestBody CozinhaInput cozinhaInput, @PathVariable Long id) {
Cozinha cozinha = serivce.buscarPorId(id);
return mapper.toModel(serivce.atualizar(cozinha));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> excluir(@PathVariable Long id) {
serivce.excluir(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/{id}")
public CozinhaModel buscarPorId(@PathVariable Long id) {
return mapper.toModel(serivce.buscarPorId(id));
}
@GetMapping("/porNome/{nome}")
public PagedModel<CozinhaModel> buscarPorNome(@PageableDefault(size = 10) Pageable pageable,
@PathVariable String nome) {
Page<Cozinha> cozinhasPage = serivce.buscarPorNome(pageable, nome.toUpperCase());
PagedModel<CozinhaModel> cozinhaModelPageModel = pagedResourcesAssembler
.toModel(cozinhasPage,mapper);
return cozinhaModelPageModel;
}
@GetMapping
public PagedModel<CozinhaModel> listarTodos(@PageableDefault(size = 10) Pageable pageable) {
Page<Cozinha> cozinhasPage = serivce.listarTodos(pageable);
PagedModel<CozinhaModel> cozinhaModelPageModel= pagedResourcesAssembler
.toModel(cozinhasPage, mapper);
return cozinhaModelPageModel;
}
}
| 40.909091 | 105 | 0.756508 |
4d57aa065127b3f6dfa7eb2214c5a9f7f7643faa | 319 | package com.company;
public class ShopManager {
public void addToProduct(Products products){
System.out.println(products.productName+" adlı ürün eklendi");
}
public void createCustomer(Customer customer){
System.out.println(customer.customerName+" adlı müşteri eklendi");
}
}
| 29 | 75 | 0.69279 |
b3b1339dec3c2e29d15b82e34b0d8a668d541d7c | 607 | package ru.job4j.streamapi.algorithms;
public class Sort {
public static void main(String[] args) {
int[] arr = new int[]{9,2,5,3,9,8};
int[] result = new int[arr.length];
for (int i = 0; i < result.length; i++) {
int counter = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[j] > result[i]) {
counter = j;
result[i] = arr[j];
}
}
arr[counter] = 0;
}
for (int counter : result) {
System.out.print(counter);
}
}
}
| 24.28 | 50 | 0.420099 |
a88615ffbddafb8cc371647403851014bd34b130 | 4,364 | /*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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 the following location:
*
* 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.jasig.cas.services.web;
//import org.jasig.cas.authentication.principal.Service;
//import org.jasig.cas.services.RegisteredService;
//import org.jasig.cas.services.ServicesManager;
//import org.jasig.cas.web.support.ArgumentExtractor;
//import org.jasig.cas.web.support.WebUtils;
//import org.springframework.util.StringUtils;
//import org.springframework.web.servlet.theme.AbstractThemeResolver;
//import javax.servlet.http.HttpRequest;
//import javax.servlet.http.HttpResponse;
//import java.util.*;
//import java.util.regex.Pattern;
/**
* ThemeResolver to determine the theme for CAS based on the service provided.
* The theme resolver will extract the service parameter from the Request object
* and attempt to match the URL provided to a Service Id. If the service is
* found, the theme associated with it will be used. If not, these is associated
* with the service or the service was not found, a default theme will be used.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0
*/
public class ServiceThemeResolver : AbstractThemeResolver {
/** The ServiceRegistry to look up the service. */
private ServicesManager servicesManager;
private List<ArgumentExtractor> argumentExtractors;
private Map<Pattern,string> overrides = new HashMap<Pattern,string>();
public string resolveThemeName( HttpRequest request) {
if (this.servicesManager == null) {
return getDefaultThemeName();
}
Service service = WebUtils.getService(this.argumentExtractors, request);
RegisteredService rService = this.servicesManager.findServiceBy(service);
// retrieve the user agent string from the request
string userAgent = request.getHeader("User-Agent");
if (userAgent == null) {
return getDefaultThemeName();
}
for ( Map.Entry<Pattern,string> entry : this.overrides.entrySet()) {
if (entry.getKey().matcher(userAgent).matches()) {
request.setAttribute("isMobile","true");
request.setAttribute("browserType", entry.getValue());
break;
}
}
return service != null && rService != null && StringUtils.hasText(rService.getTheme()) ? rService.getTheme() : getDefaultThemeName();
}
public void setThemeName( HttpRequest request, HttpResponse response, string themeName) {
// nothing to do here
}
public void setServicesManager( ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
public void setArgumentExtractors( List<ArgumentExtractor> argumentExtractors) {
this.argumentExtractors = argumentExtractors;
}
/**
* Sets the map of mobile browsers. This sets a flag on the request called "isMobile" and also
* provides the custom flag called browserType which can be mapped into the theme.
* <p>
* Themes that understand isMobile should provide an alternative stylesheet.
*
* @param mobileOverrides the list of mobile browsers.
*/
public void setMobileBrowsers( Map<string,string> mobileOverrides) {
// initialize the overrides variable to an empty map
this.overrides = new HashMap<Pattern,string>();
for ( Map.Entry<string,string> entry : mobileOverrides.entrySet()) {
this.overrides.put(Pattern.compile(entry.getKey()), entry.getValue());
}
}
}
| 39.672727 | 142 | 0.688588 |
93733b3e59a57bb38426961411d440b6d9494c8a | 767 | package net.minidev.ovh.api.email.domain;
/**
* Account List
*/
public class OvhAccountDelegated {
/**
* List of allowed sizes for this account in bytes
*
* canBeNull && readOnly
*/
public Long[] allowedAccountSize;
/**
* Size of your account in bytes
*
* canBeNull && readOnly
*/
public Long size;
/**
* Name of account
*
* canBeNull && readOnly
*/
public String accountName;
/**
* Name of domain
*
* canBeNull && readOnly
*/
public String domain;
/**
* If true your account is blocked
*
* canBeNull && readOnly
*/
public Boolean isBlocked;
/**
* Account description
*
* canBeNull && readOnly
*/
public String description;
/**
* Email
*
* canBeNull && readOnly
*/
public String email;
}
| 13.696429 | 51 | 0.6206 |
0b535e8c2fefefc352709e9695369d2760fa338a | 8,935 | /*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.bootstrap;
import com.navercorp.pinpoint.ProductInfo;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.bootstrap.util.IdValidateUtils;
import com.navercorp.pinpoint.common.PinpointConstants;
import com.navercorp.pinpoint.common.util.BytesUtils;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author emeroad
* @author netspider
*/
public class PinpointBootStrap {
private static final Logger logger = Logger.getLogger(PinpointBootStrap.class.getName());
public static final String BOOT_CLASS = "com.navercorp.pinpoint.profiler.DefaultAgent";
private static final boolean STATE_NONE = false;
private static final boolean STATE_STARTED = true;
private static final AtomicBoolean LOAD_STATE = new AtomicBoolean(STATE_NONE);
public static void premain(String agentArgs, Instrumentation instrumentation) {
if (agentArgs != null) {
logger.info(ProductInfo.CAMEL_NAME + " agentArgs:" + agentArgs);
}
final boolean duplicated = checkDuplicateLoadState();
if (duplicated) {
logPinpointAgentLoadFail();
return;
}
// 1st find boot-strap.jar
final ClassPathResolver classPathResolver = new ClassPathResolver();
boolean agentJarNotFound = classPathResolver.findAgentJar();
if (!agentJarNotFound) {
logger.severe("pinpoint-bootstrap-x.x.x(-SNAPSHOT).jar not found.");
logPinpointAgentLoadFail();
return;
}
// 2st find boot-strap-core.jar
final String bootStrapCoreJar = classPathResolver.getBootStrapCoreJar();
if (bootStrapCoreJar == null) {
logger.severe("pinpoint-bootstrap-core-x.x.x(-SNAPSHOT).jar not found");
logPinpointAgentLoadFail();
return;
}
JarFile bootStrapCoreJarFile = getBootStrapJarFile(bootStrapCoreJar);
if (bootStrapCoreJarFile == null) {
logger.severe("pinpoint-bootstrap-core-x.x.x(-SNAPSHOT).jar not found");
logPinpointAgentLoadFail();
return;
}
logger.info("load pinpoint-bootstrap-core-x.x.x(-SNAPSHOT).jar :" + bootStrapCoreJar);
instrumentation.appendToBootstrapClassLoaderSearch(bootStrapCoreJarFile);
if (!isValidId("pinpoint.agentId", PinpointConstants.AGENT_NAME_MAX_LEN)) {
logPinpointAgentLoadFail();
return;
}
if (!isValidId("pinpoint.applicationName", PinpointConstants.APPLICATION_NAME_MAX_LEN)) {
logPinpointAgentLoadFail();
return;
}
String configPath = getConfigPath(classPathResolver);
if (configPath == null) {
logPinpointAgentLoadFail();
return;
}
// set the path of log file as a system property
saveLogFilePath(classPathResolver);
try {
// Is it right to load the configuration in the bootstrap?
ProfilerConfig profilerConfig = ProfilerConfig.load(configPath);
// this is the library list that must be loaded
List<URL> libUrlList = resolveLib(classPathResolver);
AgentClassLoader agentClassLoader = new AgentClassLoader(libUrlList.toArray(new URL[libUrlList.size()]));
agentClassLoader.setBootClass(BOOT_CLASS);
logger.info("pinpoint agent starting...");
agentClassLoader.boot(classPathResolver.getAgentDirPath(), agentArgs, instrumentation, profilerConfig);
logger.info("pinpoint agent started normally.");
} catch (Exception e) {
// unexpected exception that did not be checked above
logger.log(Level.SEVERE, ProductInfo.CAMEL_NAME + " start failed. Error:" + e.getMessage(), e);
logPinpointAgentLoadFail();
}
}
private static JarFile getBootStrapJarFile(String bootStrapCoreJar) {
try {
return new JarFile(bootStrapCoreJar);
} catch (IOException ioe) {
logger.log(Level.SEVERE, bootStrapCoreJar + " file not found.", ioe);
return null;
}
}
private static void logPinpointAgentLoadFail() {
final String errorLog =
"*****************************************************************************\n" +
"* Pinpoint Agent load failure\n" +
"*****************************************************************************";
System.err.println(errorLog);
}
// for test
static boolean getLoadState() {
return LOAD_STATE.get();
}
private static boolean checkDuplicateLoadState() {
final boolean startSuccess = LOAD_STATE.compareAndSet(STATE_NONE, STATE_STARTED);
if (startSuccess) {
return false;
} else {
if (logger.isLoggable(Level.SEVERE)) {
logger.severe("pinpoint-bootstrap already started. skipping agent loading.");
}
return true;
}
}
private static boolean isValidId(String propertyName, int maxSize) {
logger.info("check -D" + propertyName);
String value = System.getProperty(propertyName);
if (value == null){
logger.severe("-D" + propertyName + " is null. value:null");
return false;
}
// blanks not permitted around value
value = value.trim();
if (value.isEmpty()) {
logger.severe("-D" + propertyName + " is empty. value:''");
return false;
}
if (!IdValidateUtils.validateId(value, maxSize)) {
logger.severe("invalid Id. " + propertyName + " can only contain [a-zA-Z0-9], '.', '-', '_'. maxLength:" + maxSize + " value:" + value);
return false;
}
if (logger.isLoggable(Level.INFO)) {
logger.info("check success. -D" + propertyName + ":" + value + " length:" + getLength(value));
}
return true;
}
private static int getLength(String value) {
final byte[] bytes = BytesUtils.toBytes(value);
if (bytes == null) {
return 0;
} else {
return bytes.length;
}
}
private static void saveLogFilePath(ClassPathResolver classPathResolver) {
String agentLogFilePath = classPathResolver.getAgentLogFilePath();
logger.info("logPath:" + agentLogFilePath);
System.setProperty(ProductInfo.NAME + ".log", agentLogFilePath);
}
private static String getConfigPath(ClassPathResolver classPathResolver) {
final String configName = ProductInfo.NAME + ".config";
String pinpointConfigFormSystemProperty = System.getProperty(configName);
if (pinpointConfigFormSystemProperty != null) {
logger.info(configName + " systemProperty found. " + pinpointConfigFormSystemProperty);
return pinpointConfigFormSystemProperty;
}
String classPathAgentConfigPath = classPathResolver.getAgentConfigPath();
if (classPathAgentConfigPath != null) {
logger.info("classpath " + configName + " found. " + classPathAgentConfigPath);
return classPathAgentConfigPath;
}
logger.severe(configName + " file not found.");
return null;
}
private static List<URL> resolveLib(ClassPathResolver classPathResolver) {
// this method may handle only absolute path, need to handle relative path (./..agentlib/lib)
String agentJarFullPath = classPathResolver.getAgentJarFullPath();
String agentLibPath = classPathResolver.getAgentLibPath();
List<URL> urlList = classPathResolver.resolveLib();
String agentConfigPath = classPathResolver.getAgentConfigPath();
if (logger.isLoggable(Level.INFO)) {
logger.info("agentJarPath:" + agentJarFullPath);
logger.info("agentLibPath:" + agentLibPath);
logger.info("agent lib list:" + urlList);
logger.info("agent config:" + agentConfigPath);
}
return urlList;
}
}
| 38.512931 | 148 | 0.63671 |
c9a3d5a7d313166a2a51e0d9c48ca39f70a432db | 6,369 | /**
* Copyright © 2018 The Lambico Datatest Team ([email protected])
*
* This file is part of lambico-datatest-jpa.
*
* 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.datatest.junit;
import lombok.Builder;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.lambico.datatest.DataAggregator;
import org.lambico.datatest.DatasetLoader;
import org.lambico.datatest.DatasetLoaderFactory;
import org.lambico.datatest.annotation.JpaTest;
import org.lambico.datatest.annotation.Property;
import org.lambico.datatest.annotation.TestData;
import org.lambico.datatest.jpa.EntityManagerFactoryCreator;
import org.lambico.datatest.jpa.EntityManagerFactoryCreator.EntityManagerFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import java.util.Collection;
public class Dataset implements TestRule {
private static final Logger log = LoggerFactory.getLogger(Dataset.class);
private DatasetLoader datasetLoader;
private DataAggregator dataAggregator;
private EntityManagerFactory entityManagerFactory;
private Class<?>[] loadEntities;
Integer flushWindowSize;
boolean useMerge;
@Builder
private Dataset(DatasetLoader datasetLoader, EntityManagerFactory entityManagerFactory, Class<?>[] loadEntities,
Integer flushWindowSize, boolean useMerge) {
this.datasetLoader = datasetLoader;
this.entityManagerFactory = entityManagerFactory;
this.loadEntities = loadEntities;
if (flushWindowSize != null) {
this.flushWindowSize = flushWindowSize;
}
this.useMerge = useMerge;
}
@Override
public Statement apply(Statement base, Description description) {
completeWithAnnotations(description);
return statement(base, description);
}
private void completeWithAnnotations(Description description) {
if (this.datasetLoader == null) {
TestData testData = description.getAnnotation(TestData.class);
this.datasetLoader = DatasetLoaderFactory.create(testData);
}
JpaTest jpaTest = description.getAnnotation(JpaTest.class);
if (jpaTest != null) {
if (jpaTest.loadEntities().length > 0) {
this.loadEntities = jpaTest.loadEntities();
}
if (jpaTest.flushWindowSize() > 0) {
this.flushWindowSize = jpaTest.flushWindowSize();
}
this.useMerge = jpaTest.useMerge();
if (this.entityManagerFactory == null) {
EntityManagerFactoryBuilder builder = EntityManagerFactoryCreator.builder();
if (jpaTest.entities().length > 0) {
for (Class<?> entity : jpaTest.entities()) {
builder.entity(entity);
}
} else {
for (Class<?> entity : jpaTest.loadEntities()) {
builder.entity(entity);
}
}
for (Property prop : jpaTest.properties()) {
builder.jpaProperty(prop.name(), prop.value());
}
this.entityManagerFactory = builder.build();
}
}
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before(description);
try {
base.evaluate();
} finally {
after(description);
}
}
};
}
private void before(Description description) {
this.dataAggregator = this.datasetLoader.load();
if (this.entityManagerFactory != null) {
this.populateTestDatabase();
}
}
private void after(Description description) {
if (this.entityManagerFactory != null) {
this.entityManagerFactory.close();
}
}
/**
* @return the dataAggregator
*/
public DataAggregator getDataAggregator() {
return dataAggregator;
}
/**
* @return the entityManagerFactory
*/
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
private void populateTestDatabase() {
EntityManager em = this.entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Query disableReferentialIntegrity = em.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE;");
disableReferentialIntegrity.executeUpdate();
Class<?>[] entities = this.loadEntities;
if (entities == null) {
entities = this.dataAggregator.getTypes().toArray(new Class<?>[0]);
}
int i = 1;
for (Class<?> currentEntity : entities) {
Collection<?> entityList = this.dataAggregator.getObjects().get(currentEntity.getName());
for (Object entity : entityList) {
log.debug("({}) Persisting entity {}", i, entity);
if (this.useMerge) {
em.merge(entity);
} else {
em.persist(entity);
}
if (this.flushWindowSize != null && i % this.flushWindowSize == 0) {
em.flush();
em.clear();
}
i++;
}
}
Query enableReferentialIntegrity = em.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE;");
enableReferentialIntegrity.executeUpdate();
em.getTransaction().commit();
em.close();
}
}
| 36.394286 | 116 | 0.625687 |
036a7963c3ee46ae3f50cb7f0cf1e28aa4c83133 | 5,342 | /*
* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.
*/
package com.supermap.gaf.cache;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.util.StringUtils;
import java.time.Duration;
/**
* @author:yj
* @date:2021/3/25 redis缓存配置
*/
@ConditionalOnProperty(name = "gaf.redis.enable", havingValue = "true")
@EnableConfigurationProperties({RedisConfigInfo.class})
@Configuration
public class RedisCacheConfig {
@Autowired
private RedisConfigInfo redisConfigInfo;
@Bean
@Primary
public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10));
return RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter(lettuceConnectionFactory))
.cacheDefaults(defaultCacheConfig)
.build();
}
@Bean
public LettuceConnectionFactory lettuceConnectionFactory(RedisStandaloneConfiguration redisConfig, GenericObjectPoolConfig redisPoolConfig) {
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofMillis(200))
.poolConfig(redisPoolConfig)
.build();
return new LettuceConnectionFactory(redisConfig, clientConfig);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(StringRedisTemplate stringRedisTemplate, LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
redisTemplate.setKeySerializer(stringRedisTemplate.getKeySerializer());
redisTemplate.setHashKeySerializer(stringRedisTemplate.getHashKeySerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public GenericObjectPoolConfig redisPoolConfig() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
if (!StringUtils.isEmpty(redisConfigInfo.getMaxActive())) {
config.setMaxTotal(redisConfigInfo.getMaxActive());
}
if (!StringUtils.isEmpty(redisConfigInfo.getMaxIdle())) {
config.setMaxIdle(redisConfigInfo.getMaxIdle());
}
if (!StringUtils.isEmpty(redisConfigInfo.getMinIdle())) {
config.setMinIdle(redisConfigInfo.getMinIdle());
}
if (!StringUtils.isEmpty(redisConfigInfo.getMaxWait())) {
config.setMaxWaitMillis(redisConfigInfo.getMaxWait());
}
return config;
}
@Bean
public RedisStandaloneConfiguration redisConfig() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName(redisConfigInfo.getHost());
config.setPassword(StringUtils.isEmpty(redisConfigInfo.getPassword()) ? RedisPassword.none() : RedisPassword.of(redisConfigInfo.getPassword()));
config.setPort(redisConfigInfo.getPort());
config.setDatabase(redisConfigInfo.getDatabase());
return config;
}
}
| 46.452174 | 152 | 0.774242 |
9d909c107eea77b1751fc5c0dad102f890b5fcde | 6,080 | /*
* Copyright (c) 2015 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.settings.device;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
public class CMActionsService extends IntentService implements ScreenStateNotifier {
private static final String TAG = "CMActions";
private static final String GESTURE_IR_WAKE_KEY = "gesture_ir_wake";
private static final String GESTURE_IR_SILENCE_KEY = "gesture_ir_silence";
private static final String GESTURE_CAMERA_KEY = "gesture_camera";
private State mState;
private SensorHelper mSensorHelper;
private ScreenReceiver mScreenReceiver;
private CameraActivationAction mCameraActivationAction;
private DozePulseAction mDozePulseAction;
private SilenceAction mSilenceAction;
private CameraActivationSensor mCameraActivationSensor;
private FlatUpSensor mFlatUpSensor;
private IrGestureSensor mIrGestureSensor;
private StowSensor mStowSensor;
private Context mContext;
private boolean mGestureIrWakeEnabled;
private boolean mGestureIrSilenceEnabled;
private boolean mGestureCameraEnabled;
public CMActionsService(Context context) {
super("CMActionService");
mContext = context;
Log.d(TAG, "Starting");
mState = new State(context);
mSensorHelper = new SensorHelper(context);
mScreenReceiver = new ScreenReceiver(context, this);
mCameraActivationAction = new CameraActivationAction(context);
mDozePulseAction = new DozePulseAction(context, mState);
mSilenceAction = new SilenceAction(context);
mCameraActivationSensor = new CameraActivationSensor(mSensorHelper, mCameraActivationAction);
mFlatUpSensor = new FlatUpSensor(mSensorHelper, mState, mDozePulseAction);
mIrGestureSensor = new IrGestureSensor(mSensorHelper, mDozePulseAction, mSilenceAction);
mStowSensor = new StowSensor(mSensorHelper, mState, mDozePulseAction);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
loadPreferences(sharedPrefs);
sharedPrefs.registerOnSharedPreferenceChangeListener(mPrefListener);
if (mGestureCameraEnabled) {
mCameraActivationSensor.enable();
}
if (mGestureIrWakeEnabled) {
mIrGestureSensor.enable(IrGestureSensor.IR_GESTURE_WAKE_ENABLED);
}
if (mGestureIrSilenceEnabled) {
mIrGestureSensor.enable(IrGestureSensor.IR_GESTURE_SILENCE_ENABLED);
}
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (powerManager.isInteractive()) {
screenTurnedOn();
} else {
screenTurnedOff();
}
}
@Override
protected void onHandleIntent(Intent intent) {
}
@Override
public void screenTurnedOn() {
mState.setScreenIsOn(true);
mFlatUpSensor.disable();
mStowSensor.disable();
mIrGestureSensor.setScreenOn(true);
}
@Override
public void screenTurnedOff() {
mState.setScreenIsOn(false);
if (isDozeEnabled()) {
mFlatUpSensor.enable();
mStowSensor.enable();
mIrGestureSensor.setScreenOn(false);
}
}
private boolean isDozeEnabled() {
return Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.DOZE_ENABLED, 1) != 0;
}
private void loadPreferences(SharedPreferences sharedPreferences) {
mGestureIrWakeEnabled = sharedPreferences.getBoolean(GESTURE_IR_WAKE_KEY, true);
mGestureIrSilenceEnabled = sharedPreferences.getBoolean(GESTURE_IR_SILENCE_KEY, true);
mGestureCameraEnabled = sharedPreferences.getBoolean(GESTURE_CAMERA_KEY, true);
}
private SharedPreferences.OnSharedPreferenceChangeListener mPrefListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (GESTURE_IR_WAKE_KEY.equals(key)) {
mGestureIrWakeEnabled = sharedPreferences.getBoolean(GESTURE_IR_WAKE_KEY, true);
if (mGestureIrWakeEnabled) {
mIrGestureSensor.enable(IrGestureSensor.IR_GESTURE_WAKE_ENABLED);
} else {
mIrGestureSensor.disable(IrGestureSensor.IR_GESTURE_WAKE_ENABLED);
}
} else if (GESTURE_IR_SILENCE_KEY.equals(key)) {
mGestureIrSilenceEnabled = sharedPreferences.getBoolean(GESTURE_IR_SILENCE_KEY, true);
if (mGestureIrSilenceEnabled) {
mIrGestureSensor.enable(IrGestureSensor.IR_GESTURE_SILENCE_ENABLED);
} else {
mIrGestureSensor.disable(IrGestureSensor.IR_GESTURE_SILENCE_ENABLED);
}
} else if (GESTURE_CAMERA_KEY.equals(key)) {
mGestureCameraEnabled = sharedPreferences.getBoolean(GESTURE_CAMERA_KEY, true);
if (mGestureCameraEnabled) {
mCameraActivationSensor.enable();
} else {
mCameraActivationSensor.disable();
}
}
}
};
}
| 38.726115 | 102 | 0.699507 |
55c8a1145c252865fcf92be18587cda94e9811a2 | 1,056 | package com.alibaba.datax.plugin.writer.odpswriter.model;
import java.io.Serializable;
import java.util.List;
public class UserDefinedFunction implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String expression;
private String inputColumn;
private List<UserDefinedFunctionRule> variableRule;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public String getInputColumn() {
return inputColumn;
}
public void setInputColumn(String inputColumn) {
this.inputColumn = inputColumn;
}
public List<UserDefinedFunctionRule> getVariableRule() {
return variableRule;
}
public void setVariableRule(List<UserDefinedFunctionRule> variableRule) {
this.variableRule = variableRule;
}
}
| 23.466667 | 77 | 0.694129 |
1ea214734bf250ce114cbad029b5d53629960e62 | 964 | package org.jenkinsci.plugins.lambdatestrunner.jenkins.request;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
public class RequestMapperTest {
@Test
public void testAsString() {
Request rawRequest = new Request();
rawRequest.setRepoUri("https://github.com/jenkinsci/lambda-test-runner-plugin.git");
rawRequest.setBranch("develop");
rawRequest.setCommand("./mvnw clean test -Dtest=SmokeTest -Dmaven.repo.local=${MAVEN_USER_HOME}");
rawRequest.setStoreToS3(Collections.singletonList("target/surefire-reports"));
String mappedRequest = RequestMapper.asString(rawRequest);
assertEquals(mappedRequest, "{\"repoUri\":\"https://github.com/jenkinsci/lambda-test-runner-plugin.git\",\"branch\":\"develop\",\"command\":\"./mvnw clean test -Dtest=SmokeTest -Dmaven.repo.local=${MAVEN_USER_HOME}\",\"storeToS3\":[\"target/surefire-reports\"]}");
}
}
| 41.913043 | 272 | 0.71888 |
f58ee9069cceb3ce475832e27a345f4d3373fb3b | 2,822 | package se.l4.otter.model.internal;
import java.util.HashMap;
import java.util.Map;
import se.l4.otter.EventHelper;
import se.l4.otter.lock.CloseableLock;
import se.l4.otter.model.SharedMap;
import se.l4.otter.model.spi.AbstractSharedObject;
import se.l4.otter.model.spi.DataValues;
import se.l4.otter.model.spi.SharedObjectEditor;
import se.l4.otter.operations.Operation;
import se.l4.otter.operations.map.MapDelta;
import se.l4.otter.operations.map.MapHandler;
public class SharedMapImpl
extends AbstractSharedObject<Operation<MapHandler>>
implements SharedMap
{
private final Map<String, Object> values;
private final MapHandler handler;
private final EventHelper<Listener> changeListeners;
public SharedMapImpl(SharedObjectEditor<Operation<MapHandler>> editor)
{
super(editor);
values = new HashMap<>();
changeListeners = new EventHelper<>();
handler = createHandler();
editor.getCurrent().apply(handler);
editor.setOperationHandler(this::apply);
}
private MapHandler createHandler()
{
return new MapHandler()
{
@Override
public void remove(String key, Object oldValue)
{
Object old = values.remove(key);
editor.queueEvent(() -> changeListeners.trigger(l ->
l.valueRemoved(key, old)
));
}
@Override
public void put(String key, Object oldValue, Object newValue)
{
Object value = DataValues.fromData(editor, newValue);
Object old = values.put(key, value);
editor.queueEvent(() ->
changeListeners.trigger(l ->
l.valueChanged(key, old, value)
)
);
}
};
}
private void apply(Operation<MapHandler> op, boolean local)
{
op.apply(handler);
}
@Override
public String getObjectId()
{
return editor.getId();
}
@Override
public String getObjectType()
{
return editor.getType();
}
@Override
public boolean containsKey(String key)
{
return values.containsKey(key);
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(String key)
{
return (T) values.get(key);
}
@Override
public void remove(String key)
{
try(CloseableLock lock = editor.lock())
{
Object value = values.get(key);
editor.apply(MapDelta.builder()
.set(key, DataValues.toData(value), null)
.done()
);
}
}
@Override
public void set(String key, Object value)
{
if(value == null)
{
throw new IllegalArgumentException("null values are currently not supported");
}
try(CloseableLock lock = editor.lock())
{
Object old = values.get(key);
editor.apply(MapDelta.builder()
.set(key, DataValues.toData(old), DataValues.toData(value))
.done()
);
}
}
@Override
public void addChangeListener(Listener listener)
{
changeListeners.add(listener);
}
@Override
public void removeChangeListener(Listener listener)
{
changeListeners.remove(listener);
}
}
| 20.449275 | 81 | 0.708009 |
fa8f714758c9b0a966a444c9e3d48b0b65b55174 | 10,165 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
/**
* <p>
* AWS CodeArtifact is a fully managed artifact repository compatible with language-native package managers and build
* tools such as npm, Apache Maven, and pip. You can use CodeArtifact to share packages with development teams and pull
* packages. Packages can be pulled from both public and CodeArtifact repositories. You can also create an upstream
* relationship between a CodeArtifact repository and another repository, which effectively merges their contents from
* the point of view of a package manager client.
* </p>
* <p>
* <b>AWS CodeArtifact Components</b>
* </p>
* <p>
* Use the information in this guide to help you work with the following CodeArtifact components:
* </p>
* <ul>
* <li>
* <p>
* <b>Repository</b>: A CodeArtifact repository contains a set of <a
* href="https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html#welcome-concepts-package-version">package
* versions</a>, each of which maps to a set of assets, or files. Repositories are polyglot, so a single repository can
* contain packages of any supported type. Each repository exposes endpoints for fetching and publishing packages using
* tools like the <b> <code>npm</code> </b> CLI, the Maven CLI (<b> <code>mvn</code> </b>), and <b> <code>pip</code>
* </b>.
* </p>
* </li>
* <li>
* <p>
* <b>Domain</b>: Repositories are aggregated into a higher-level entity known as a <i>domain</i>. All package assets
* and metadata are stored in the domain, but are consumed through repositories. A given package asset, such as a Maven
* JAR file, is stored once per domain, no matter how many repositories it's present in. All of the assets and metadata
* in a domain are encrypted with the same customer master key (CMK) stored in AWS Key Management Service (AWS KMS).
* </p>
* <p>
* Each repository is a member of a single domain and can't be moved to a different domain.
* </p>
* <p>
* The domain allows organizational policy to be applied across multiple repositories, such as which accounts can access
* repositories in the domain, and which public repositories can be used as sources of packages.
* </p>
* <p>
* Although an organization can have multiple domains, we recommend a single production domain that contains all
* published artifacts so that teams can find and share packages across their organization.
* </p>
* </li>
* <li>
* <p>
* <b>Package</b>: A <i>package</i> is a bundle of software and the metadata required to resolve dependencies and
* install the software. CodeArtifact supports <a
* href="https://docs.aws.amazon.com/codeartifact/latest/ug/using-npm.html">npm</a>, <a
* href="https://docs.aws.amazon.com/codeartifact/latest/ug/using-python.html">PyPI</a>, and <a
* href="https://docs.aws.amazon.com/codeartifact/latest/ug/using-maven">Maven</a> package formats.
* </p>
* <p>
* In CodeArtifact, a package consists of:
* </p>
* <ul>
* <li>
* <p>
* A <i>name</i> (for example, <code>webpack</code> is the name of a popular npm package)
* </p>
* </li>
* <li>
* <p>
* An optional namespace (for example, <code>@types</code> in <code>@types/node</code>)
* </p>
* </li>
* <li>
* <p>
* A set of versions (for example, <code>1.0.0</code>, <code>1.0.1</code>, <code>1.0.2</code>, etc.)
* </p>
* </li>
* <li>
* <p>
* Package-level metadata (for example, npm tags)
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* <b>Package version</b>: A version of a package, such as <code>@types/node 12.6.9</code>. The version number format
* and semantics vary for different package formats. For example, npm package versions must conform to the <a
* href="https://semver.org/">Semantic Versioning specification</a>. In CodeArtifact, a package version consists of the
* version identifier, metadata at the package version level, and a set of assets.
* </p>
* </li>
* <li>
* <p>
* <b>Upstream repository</b>: One repository is <i>upstream</i> of another when the package versions in it can be
* accessed from the repository endpoint of the downstream repository, effectively merging the contents of the two
* repositories from the point of view of a client. CodeArtifact allows creating an upstream relationship between two
* repositories.
* </p>
* </li>
* <li>
* <p>
* <b>Asset</b>: An individual file stored in CodeArtifact associated with a package version, such as an npm
* <code>.tgz</code> file or Maven POM and JAR files.
* </p>
* </li>
* </ul>
* <p>
* CodeArtifact supports these operations:
* </p>
* <ul>
* <li>
* <p>
* <code>AssociateExternalConnection</code>: Adds an existing external connection to a repository.
* </p>
* </li>
* <li>
* <p>
* <code>CopyPackageVersions</code>: Copies package versions from one repository to another repository in the same
* domain.
* </p>
* </li>
* <li>
* <p>
* <code>CreateDomain</code>: Creates a domain
* </p>
* </li>
* <li>
* <p>
* <code>CreateRepository</code>: Creates a CodeArtifact repository in a domain.
* </p>
* </li>
* <li>
* <p>
* <code>DeleteDomain</code>: Deletes a domain. You cannot delete a domain that contains repositories.
* </p>
* </li>
* <li>
* <p>
* <code>DeleteDomainPermissionsPolicy</code>: Deletes the resource policy that is set on a domain.
* </p>
* </li>
* <li>
* <p>
* <code>DeletePackageVersions</code>: Deletes versions of a package. After a package has been deleted, it can be
* republished, but its assets and metadata cannot be restored because they have been permanently removed from storage.
* </p>
* </li>
* <li>
* <p>
* <code>DeleteRepository</code>: Deletes a repository.
* </p>
* </li>
* <li>
* <p>
* <code>DeleteRepositoryPermissionsPolicy</code>: Deletes the resource policy that is set on a repository.
* </p>
* </li>
* <li>
* <p>
* <code>DescribeDomain</code>: Returns a <code>DomainDescription</code> object that contains information about the
* requested domain.
* </p>
* </li>
* <li>
* <p>
* <code>DescribePackageVersion</code>: Returns a <a
* href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionDescription.html"
* >PackageVersionDescription</a> object that contains details about a package version.
* </p>
* </li>
* <li>
* <p>
* <code>DescribeRepository</code>: Returns a <code>RepositoryDescription</code> object that contains detailed
* information about the requested repository.
* </p>
* </li>
* <li>
* <p>
* <code>DisposePackageVersions</code>: Disposes versions of a package. A package version with the status
* <code>Disposed</code> cannot be restored because they have been permanently removed from storage.
* </p>
* </li>
* <li>
* <p>
* <code>DisassociateExternalConnection</code>: Removes an existing external connection from a repository.
* </p>
* </li>
* <li>
* <p>
* <code>GetAuthorizationToken</code>: Generates a temporary authorization token for accessing repositories in the
* domain. The token expires the authorization period has passed. The default authorization period is 12 hours and can
* be customized to any length with a maximum of 12 hours.
* </p>
* </li>
* <li>
* <p>
* <code>GetDomainPermissionsPolicy</code>: Returns the policy of a resource that is attached to the specified domain.
* </p>
* </li>
* <li>
* <p>
* <code>GetPackageVersionAsset</code>: Returns the contents of an asset that is in a package version.
* </p>
* </li>
* <li>
* <p>
* <code>GetPackageVersionReadme</code>: Gets the readme file or descriptive text for a package version.
* </p>
* </li>
* <li>
* <p>
* <code>GetRepositoryEndpoint</code>: Returns the endpoint of a repository for a specific package format. A repository
* has one endpoint for each package format:
* </p>
* <ul>
* <li>
* <p>
* <code>npm</code>
* </p>
* </li>
* <li>
* <p>
* <code>pypi</code>
* </p>
* </li>
* <li>
* <p>
* <code>maven</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* <code>GetRepositoryPermissionsPolicy</code>: Returns the resource policy that is set on a repository.
* </p>
* </li>
* <li>
* <p>
* <code>ListDomains</code>: Returns a list of <code>DomainSummary</code> objects. Each returned
* <code>DomainSummary</code> object contains information about a domain.
* </p>
* </li>
* <li>
* <p>
* <code>ListPackages</code>: Lists the packages in a repository.
* </p>
* </li>
* <li>
* <p>
* <code>ListPackageVersionAssets</code>: Lists the assets for a given package version.
* </p>
* </li>
* <li>
* <p>
* <code>ListPackageVersionDependencies</code>: Returns a list of the direct dependencies for a package version.
* </p>
* </li>
* <li>
* <p>
* <code>ListPackageVersions</code>: Returns a list of package versions for a specified package in a repository.
* </p>
* </li>
* <li>
* <p>
* <code>ListRepositories</code>: Returns a list of repositories owned by the AWS account that called this method.
* </p>
* </li>
* <li>
* <p>
* <code>ListRepositoriesInDomain</code>: Returns a list of the repositories in a domain.
* </p>
* </li>
* <li>
* <p>
* <code>PutDomainPermissionsPolicy</code>: Attaches a resource policy to a domain.
* </p>
* </li>
* <li>
* <p>
* <code>PutRepositoryPermissionsPolicy</code>: Sets the resource policy on a repository that specifies permissions to
* access it.
* </p>
* </li>
* <li>
* <p>
* <code>UpdatePackageVersionsStatus</code>: Updates the status of one or more versions of a package.
* </p>
* </li>
* <li>
* <p>
* <code>UpdateRepository</code>: Updates the properties of a repository.
* </p>
* </li>
* </ul>
*/
package com.amazonaws.services.codeartifact;
| 33.110749 | 120 | 0.678406 |
df58bb560c3e8707b4d692a7959501153d4e160a | 732 | package box.star.bin.sh.promise;
import box.star.bin.sh.SharedMap;
import box.star.bin.sh.Streams;
import box.star.contract.Nullable;
import java.io.Closeable;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public interface StreamCatalog<Host> {
Host writeErrorTo(@Nullable OutputStream os);
Host writeOutputTo(@Nullable OutputStream os);
Host readInputFrom(@Nullable InputStream is);
Host remove(Integer key);
Host resetStreams();
Host applyStreams(@Nullable Streams overlay);
Host set(Integer key, @Nullable Closeable stream);
<ANY> ANY get(Integer key);
List<Integer> streams();
boolean haveStream(Integer key);
SharedMap<Integer, Closeable> exportStreams();
}
| 20.914286 | 52 | 0.759563 |
ab462e61240362dee40a9588cfae3508b97b9c75 | 7,815 | /*
* Copyright © 2018 HarborIO, 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 io.hrbr.beacon;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* A singleton for sending requests to the Harbor Beacon service.
*
* <p>Calling {@link #log(String, JSONObject)} will enqueue the given Request for dispatch,
* resolving from either cache or network on a worker thread, and then delivering a parsed
* response on the main thread.
*/
public class BeaconSingleton {
protected static final String TAG = "BeaconSingleton";
protected static final long AUTO_TIMESTAMP = -1;
private static BeaconSingleton mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;
private String mApiKey;
private String mAppVersionId;
private String mBeaconVersionId;
private String mBeaconInstanceId;
private BeaconSingleton(Context context, String apiKey, String appVersionId, String beaconVersionId, String beaconInstanceId) {
mCtx = context;
mApiKey = apiKey;
mAppVersionId = appVersionId;
mBeaconVersionId = beaconVersionId;
mBeaconInstanceId = beaconInstanceId;
mRequestQueue = getRequestQueue();
}
/**
* Create or return the static instance of the BeaconSingleton.
*
* @param context
* @param apiKey
* @param appVersionId
* @param beaconVersionId
* @param beaconInstanceId
* @return The Beacon Singleton
*/
public static synchronized BeaconSingleton getInstance(Context context, String apiKey, String appVersionId, String beaconVersionId, String beaconInstanceId) {
if (mInstance == null) {
mInstance = new BeaconSingleton(context, apiKey, appVersionId, beaconVersionId, beaconInstanceId);
}
return mInstance;
}
/**
* Create or return the static instance of the RequestQueue.
*
* @return The request dispatch queue
*/
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
/**
*
* @param req The Request
* @param <T>
*/
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
/**
* Queue a request for sending.
*
* @param msgType
* @param json
* @param timestamp
* @param listener
* @param errorListener
*/
public void log(final String msgType, JSONObject json, long timestamp, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
BeaconRequest request = new BeaconRequest(
mApiKey,
mAppVersionId,
mBeaconVersionId,
mBeaconInstanceId,
timestamp,
msgType,
json,
listener, errorListener);
addToRequestQueue(request);
}
/**
* Queue a request for sending.
*
* @param msgType
* @param json
* @param timestamp
*/
public void log(final String msgType, JSONObject json, long timestamp) {
log(msgType, json, timestamp, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v(TAG, msgType + " message OK");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.e(TAG, msgType + " message ERR: " + error.toString());
}
});
}
/**
* Queue a request for sending.
*
* @param msgType
* @param json
*/
public void log(final String msgType, JSONObject json) {
log(msgType, json, AUTO_TIMESTAMP);
}
/**
* Queue a request for sending.
*
* @param msgType
*/
public void log(final String msgType) {
log(msgType, null);
}
private class BeaconRequest extends JsonObjectRequest {
protected static final String BASE_URL = "https://harbor-stream.hrbr.io/beacon";
private String mApiKey;
private String mAppVersionId;
private String mBeaconVersionId;
private String mBeaconInstanceId;
private long mTimestamp;
private final String mBeaconMessageType;
public BeaconRequest(
String apiKey, String appVersionId, String beaconVersionId, String beaconInstanceId,
long timestamp,
String beaconMessageType, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(
BASE_URL,
jsonRequest == null ? new JSONObject() : jsonRequest,
listener,
errorListener);
mApiKey = apiKey;
mAppVersionId = appVersionId;
mBeaconVersionId = beaconVersionId;
mBeaconInstanceId = beaconInstanceId;
mTimestamp = (timestamp == AUTO_TIMESTAMP) ? System.currentTimeMillis() : timestamp;
mBeaconMessageType = beaconMessageType;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Accept", "application/json");
params.put("apikey", mApiKey);
params.put("appVersionId", mAppVersionId);
params.put("beaconVersionId", mBeaconVersionId);
params.put("dataTimestamp", "" + mTimestamp);
params.put("beaconinstanceid", mBeaconInstanceId);
params.put("beaconMessageType", mBeaconMessageType);
return params;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = "{}";
return Response.success(
new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
//} catch (UnsupportedEncodingException e) {
// return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
}
| 31.897959 | 162 | 0.628279 |
33738f539cd7fe597a55ad9c4fabf7478090f8b7 | 208 | package com.soracasus.survivegame.tiles;
import com.soracasus.survivegame.gfx.Assets;
public class DirtTile extends Tile {
public DirtTile(int id) {
super(Assets.INSTANCE.getTexture("dirt"), id);
}
}
| 17.333333 | 48 | 0.754808 |
1e8f9976ea98cda9fab63c3a6ee4ef17e2f381a8 | 3,689 | package io.github.strikerrocker.vt.content.items;
import io.github.strikerrocker.vt.VanillaTweaks;
import io.github.strikerrocker.vt.base.Feature;
import io.github.strikerrocker.vt.content.blocks.Blocks;
import io.github.strikerrocker.vt.content.items.craftingpad.CraftingPadItem;
import io.github.strikerrocker.vt.content.items.dynamite.DynamiteEntity;
import io.github.strikerrocker.vt.content.items.dynamite.DynamiteItem;
import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder;
import net.minecraft.block.DispenserBlock;
import net.minecraft.block.dispenser.ProjectileDispenserBehavior;
import net.minecraft.entity.EntityDimensions;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.SpawnGroup;
import net.minecraft.entity.projectile.ProjectileEntity;
import net.minecraft.item.*;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.Position;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import static io.github.strikerrocker.vt.VanillaTweaks.MOD_ID;
public class Items extends Feature {
public static final EntityType<DynamiteEntity> DYNAMITE_TYPE = Registry.register(Registry.ENTITY_TYPE,
new Identifier(MOD_ID, "dynamite"),
FabricEntityTypeBuilder.create(SpawnGroup.MISC, DynamiteEntity::new).dimensions(EntityDimensions.fixed(0, 0))
.trackRangeBlocks(4).trackedUpdateRate(10)
.build()
);
public static final Item CRAFTING_PAD = new CraftingPadItem();
public static final Item DYNAMITE = new DynamiteItem();
public static final Item SLIME_BUCKET = new SlimeBucketItem();
private static final Item FRIED_EGG = new Item(new Item.Settings().food((new FoodComponent.Builder()).hunger(5).saturationModifier(0.6f).build()).group(ItemGroup.FOOD));
/**
* Register ItemBlocks and Items
*/
@Override
public void initialize() {
if (VanillaTweaks.config.content.enableFriedEgg)
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "fried_egg"), FRIED_EGG);
if (VanillaTweaks.config.content.enableCraftingPad)
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "crafting_pad"), CRAFTING_PAD);
if (VanillaTweaks.config.content.enableDynamite) {
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "dynamite"), DYNAMITE);
DispenserBlock.registerBehavior(DYNAMITE, new ProjectileDispenserBehavior() {
@Override
protected ProjectileEntity createProjectile(World world, Position position, ItemStack stack) {
return new DynamiteEntity(DYNAMITE_TYPE, world);
}
});
}
if (VanillaTweaks.config.content.enableSlimeBucket)
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "slime_bucket"), SLIME_BUCKET);
if (VanillaTweaks.config.content.enableStorageBlocks) {
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "charcoal_block"), new BlockItem(Blocks.CHARCOAL_BLOCK, new Item.Settings().group(ItemGroup.MISC)));
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "sugar_block"), new BlockItem(Blocks.SUGAR_BLOCK, new Item.Settings().group(ItemGroup.MISC)));
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "flint_block"), new BlockItem(Blocks.FLINT_BLOCK, new Item.Settings().group(ItemGroup.MISC)));
}
if (VanillaTweaks.config.content.enablePedestal)
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "pedestal"), new BlockItem(Blocks.PEDESTAL_BLOCK, new Item.Settings().group(ItemGroup.MISC)));
}
} | 57.640625 | 173 | 0.73814 |
8b1008a62752f8312402f6b11a69223effab11c9 | 4,633 | /*******************************************************************************
* Copyright 2016-2018 Research group REMEX, Hochschule der Medien (Stuttgart, Germany)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.hdm.helpers.test;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import de.hdm.helpers.GregorianCalendarHelper;
public class TestGregorianCalendarHelper {
public static void main(String[] args){
String date = "2010-10-31";
String time = "23:54:50";
String timezone = "+01:00";
String dateTimeTimezone = date + "T" + time + timezone;
String regexDate = "[0-9]{4}-([1-9]|0[1-9]|1[0-2])-([1-9]|0[1-9]|(1[0-9]|2[0-9]|3[0-1]))";
String regexTime = "([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|[1-5][0-9]):([0-9]|0[0-9]|[1-5][0-9])";
String regexTimezone = "(Z|(\\+|-)((([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|[1-5][0-9]))|([0-9]|0[0-9]|1[0-9]|2[0-3])))";
System.out.println(date.matches(regexDate));
System.out.println(time.matches(regexTime));
System.out.println(timezone.matches(regexTimezone));
System.out.println(dateTimeTimezone.matches(regexDate+"T"+regexTime+regexTimezone));
String date1 = "2010-10-01T23:30:44:009";
GregorianCalendar g1 = GregorianCalendarHelper.convertDateTimeStringToGregorianCalendar(date1, "-", "T", ":", null);
System.out.println(GregorianCalendarHelper.convertDateAndTimeToString(g1, "-", "T", ":"));
String date2 = "2010-10-01T23:30";
GregorianCalendar g2 = GregorianCalendarHelper.convertDateTimeStringToGregorianCalendar(date2, "-", "T", ":", null);
System.out.println(GregorianCalendarHelper.convertDateAndTimeToString(g2, "-", "T", ":"));
/*String date3 = "2010-10-01T23:30:00+01:30";
GregorianCalendar g3 = GregorianCalendarHelper.convertDateTimeStringFromRequestToGregorianCalendar(date3);
System.out.println(GregorianCalendarHelper.convertDateAndTimeToString(g3, "-", "T", ":"));
String date4 = "2010-10-01T23:30:00+01";
GregorianCalendar g4 = GregorianCalendarHelper.convertDateTimeStringFromRequestToGregorianCalendar(date4);
System.out.println(GregorianCalendarHelper.convertDateAndTimeToString(g4, "-", "T", ":"));
String date5 = "2010-10-01T23:30:00-01:00";
GregorianCalendar g5 = GregorianCalendarHelper.convertDateTimeStringFromRequestToGregorianCalendar(date5);
System.out.println(GregorianCalendarHelper.convertDateAndTimeToString(g5, "-", "T", ":"));
String date6 = "2010-10-01T23:30:00Z";
GregorianCalendar g6 = GregorianCalendarHelper.convertDateTimeStringFromRequestToGregorianCalendar(date6);
System.out.println(GregorianCalendarHelper.convertDateAndTimeToString(g6, "-", "T", ":"));
*/
GregorianCalendar g7 = new GregorianCalendar();
g7.setTimeInMillis(System.currentTimeMillis());
System.out.println("System.currentTimeMillis()=" + System.currentTimeMillis());
System.out.println("g7.getTimeInMillis()=" + g7.getTimeInMillis());
GregorianCalendar g8 = GregorianCalendarHelper.convertDateTimeStringFromDatabaseToGregorianCalendar("2017-04-25 16:34:08.260");
System.out.println("g8.getTimeInMillis()=" + g8.getTimeInMillis());
GregorianCalendar g9 = new GregorianCalendar(2017, 3, 25, 18, 0, 0);
//System.out.println("g9.getTimeInMillis()=" + g9.getTimeInMillis());
g9.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("g9.getTimeInMillis()=" + g9.getTimeInMillis());
//String tmp = GregorianCalendarHelper.convertGregorianCalendarToStringForJsonResponse(g7);
//System.out.println(GregorianCalendarHelper.convertGregorianCalendarToStringForJsonResponse(g7));
//System.out.println(System.currentTimeMillis());
//System.out.println(GregorianCalendarHelper.convertGregorianCalendarToStringForJsonResponse(GregorianCalendarHelper.convertDateTimeStringFromRequestToGregorianCalendar("2017-03-29T19:38:54")));
GregorianCalendar gt = new GregorianCalendar();
System.out.println(gt.getTimeZone().getID());
}
}
| 52.05618 | 197 | 0.696957 |
e1c368fe1ce621e2bb0aa8e4e40ac7a407001b4b | 4,991 | //package reco.serenade.dataio;
//
//import com.google.api.core.ApiFuture;
//import com.google.cloud.bigtable.admin.v2.BigtableTableAdminClient;
//import com.google.cloud.bigtable.admin.v2.BigtableTableAdminSettings;
//import com.google.cloud.bigtable.admin.v2.models.CreateTableRequest;
//import com.google.cloud.bigtable.admin.v2.models.GCRules;
//import com.google.cloud.bigtable.data.v2.BigtableDataClient;
//import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
//import com.google.cloud.bigtable.data.v2.models.Row;
//import com.google.cloud.bigtable.data.v2.models.RowMutation;
//import com.google.cloud.bigtable.emulator.v2.BigtableEmulatorRule;
//import com.google.cloud.bigtable.emulator.v2.BigtableEmulatorRuleFactory;
//import com.google.protobuf.ByteString;
//import org.springframework.util.SerializationUtils;
//
//import java.io.IOException;
//import java.util.List;
//import java.util.Set;
//import java.util.concurrent.ExecutionException;
//import java.util.concurrent.TimeUnit;
//
//import static com.google.cloud.bigtable.admin.v2.models.GCRules.GCRULES;
//
//public class SessionHistoryDao {
// private static final String TABLE_ID = "evolving_sessions";
// private static final String FAMILY_ID = "payload";
// private static final String GCP_PROJECT_ID = "someProjectId";
// private static final String GCP_INSTANCE_ID = "someInstanceId";
//
// // Clients that will be connected to the emulator
// private BigtableTableAdminClient tableAdminClient;
// private BigtableDataClient dataClient;
//
// public SessionHistoryDao() throws Throwable {
// BigtableEmulatorRuleFactory ruleFactory = new BigtableEmulatorRuleFactory();
// BigtableEmulatorRule bigtableEmulator = ruleFactory.getBigtableEmulator();
// int port = bigtableEmulator.getPort();
// BigtableTableAdminSettings.Builder tableAdminSettings = BigtableTableAdminSettings.newBuilderForEmulator(port);
// tableAdminSettings.setProjectId(GCP_PROJECT_ID);
// tableAdminSettings.setInstanceId(GCP_INSTANCE_ID);
// tableAdminClient = BigtableTableAdminClient.create(tableAdminSettings.build());
//
// BigtableDataSettings.Builder dataSettings = BigtableDataSettings.newBuilderForEmulator(port);
// dataSettings.setProjectId(GCP_PROJECT_ID);
// dataSettings.setInstanceId(GCP_INSTANCE_ID);
// dataClient = BigtableDataClient.create(dataSettings.build());
//
// GCRules.VersionRule versionRule = GCRULES.maxVersions(1);
// GCRules.DurationRule maxAgeRule = GCRULES.maxAge(15, TimeUnit.MINUTES);
// // Drop cells that are either older than the xxx recent versions
// // IntersectionRule: remove all data matching any of a set of given rules
// // Drop cells that are older than xxx TimeUnit
// GCRules.IntersectionRule cleanupPolicy = GCRULES.intersection().rule(maxAgeRule).rule(versionRule);
//
// tableAdminClient.createTable(
// CreateTableRequest.of(TABLE_ID)
// .addFamily(FAMILY_ID, cleanupPolicy)
// );
// }
//
// public List<Long> getRowFor(String sessionId) throws IOException, ClassNotFoundException {
// Row row = dataClient.readRow(TABLE_ID, sessionId);
// ByteString payload = row.getCells(FAMILY_ID, ByteString.copyFromUtf8("payload")).get(0).getValue();
// List<Long> result = (List<Long>) SessionHistoryDao.deserialize(payload.toByteArray());
// // https://cloud.google.com/bigtable/docs/writing-data
// return result;
// }
//
// public void storeIntoDb(String sessionId, List<Long> evolvingSessionItemIds, Set<Integer> candidateSessionIds) throws IOException {
//// MutablePair<List<Long>, Set<Integer>> payload = new MutablePair<>(evolvingSessionItemIds, candidateSessionIds);
//
// byte[] asBytes= SessionHistoryDao.serialize(evolvingSessionItemIds);
// dataClient.mutateRow(RowMutation.create(TABLE_ID, sessionId)
// .setCell(FAMILY_ID, ByteString.copyFromUtf8("payload"), ByteString.copyFrom(asBytes))
// );
// }
//
// public void writeAsync(String sessionId) throws ExecutionException, InterruptedException {
// String rowKey = "sessionAbc1233";
// ApiFuture<Void> mutateFuture = dataClient.mutateRowAsync(
// RowMutation.create(TABLE_ID, sessionId)
// .setCell(FAMILY_ID, "e_sessions", "value")
// );
//
// mutateFuture.get();
//
// ApiFuture<Row> rowFuture = dataClient.readRowAsync(TABLE_ID, sessionId);
//
// System.out.println(rowFuture.get().getCells().get(0).getValue().toStringUtf8());
//
// }
//
// private static byte[] serialize(Object input) throws IOException {
// return SerializationUtils.serialize(input);
// }
//
// private static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
// return SerializationUtils.deserialize(bytes);
// }
//
//}
| 48.456311 | 137 | 0.718093 |
5292f26be2237414d2ab3c99f1b8057dff8e69a2 | 5,346 | /*
* Copyright (c) 2013 The CCP project authors. All Rights Reserved.
*
* Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
* that can be found in the LICENSE file in the root of the web site.
*
* http://www.yuntongxun.com
*
* An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package com.darly.im.ui.plugin;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.darly.dlclent.R;
import com.darly.im.common.utils.CnToCharUntil;
import com.darly.im.common.utils.FileUtils;
import com.darly.im.common.utils.LogUtil;
/**
* @author Jorstin Chan@容联•云通讯
* @date 2014-12-30
* @version 4.0
*/
public class FileListAdapter extends BaseAdapter {
private static final String TAG = "ECDemo.FileListAdapter";
private Context mContext;
/**上一级目录*/
private File mParentFile;
/**当前浏览目录*/
private File mCurrentFile;
/**文件浏览根目录*/
private String mRootDirectory;
/**文件列表数据*/
private File[] mFiles;
public FileListAdapter(Context ctx) {
mContext = ctx;
}
public void setPath(String path) {
mRootDirectory = path;
}
/**
* 设置浏览目录
* @param parent
* @param sub
*/
public void setFiles(File parent ,File sub) {
mParentFile = parent;
if(sub.getAbsolutePath().equalsIgnoreCase(mRootDirectory)){
// 如果是根目录,则不显示返回上一级按钮
mParentFile = null;
}
mCurrentFile = sub;
if(mCurrentFile.canRead()) {
mFiles = mCurrentFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.isHidden();
}
});
}
if(mFiles.length > 0) {
ArrayList<FileItem> spellDirectoty = new ArrayList<FileItem>();
ArrayList<FileItem> spellFile = new ArrayList<FileItem>();
for(int i = 0 ; i < mFiles.length ; i++) {
File file = mFiles[i];
FileItem fileItem = new FileItem();
fileItem.file = file;
fileItem.spell = CnToCharUntil.getSpell(file.getName().toUpperCase(), false);
if(file.isDirectory()) {
spellDirectoty.add(fileItem);
} else {
spellFile.add(fileItem);
}
}
Collections.sort(spellDirectoty, new Comparator<FileItem>() {
@Override
public int compare(FileItem lhs, FileItem rhs) {
return lhs.spell.compareTo(rhs.spell);
}
});
Collections.sort(spellFile, new Comparator<FileItem>() {
@Override
public int compare(FileItem lhs, FileItem rhs) {
return lhs.spell.compareTo(rhs.spell);
}
});
int index = 0;
for(FileItem f : spellDirectoty) {
mFiles[index] = f.file;
index ++;
}
for(FileItem f : spellFile) {
mFiles[index] = f.file;
index ++;
}
}
}
@Override
public int getCount() {
if(mFiles == null) {
return 0;
}
int length = mFiles.length;
File f = mParentFile;
if(f != null) {
length += 1;
}
return length;
}
@Override
public Object getItem(int position) {
if(mParentFile != null && position == 0) {
// 如果第一个 返回上一级目录Item
return mParentFile;
}
LogUtil.d(TAG, "pos:" + position + ", subFile length:" + mFiles.length);
if(mParentFile != null) {
--position;
}
return mFiles[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ViewHolder mViewHolder = null;
if(convertView == null || convertView.getTag() == null) {
view = View.inflate(mContext, R.layout.file_explorer_item, null);
mViewHolder = new ViewHolder();
mViewHolder.mFileIcon = (ImageView) view.findViewById(R.id.file_icon_iv);
mViewHolder.mFileName = (TextView) view.findViewById(R.id.file_name_tv);
mViewHolder.mFileSummary = (TextView) view.findViewById(R.id.file_summary_tv);
view.setTag(mViewHolder);
} else {
view = convertView;
mViewHolder = (ViewHolder) view.getTag();
}
File file = (File) getItem(position);
if(file == mParentFile) {
mViewHolder.mFileIcon.setImageResource(R.drawable.im_attach_back);
} else {
if(file.isDirectory()) {
mViewHolder.mFileIcon.setImageResource(R.drawable.file_attach_folder);
} else {
mViewHolder.mFileIcon.setImageResource(FileUtils.getFileIcon(file.getName()));
}
}
mViewHolder.mFileName.setText(file.getName());
StringBuilder sb = new StringBuilder().append(DateFormat.format(
"yyyy-MM-dd hh:mm:ss", file.lastModified()).toString());
if(!file.isDirectory()) {
sb.append(" " + FileUtils.formatFileLength(file.length()));
}
mViewHolder.mFileSummary.setText(sb.toString());
return view;
}
public File getCurrentFile() {
return mCurrentFile;
}
/**
* @return the mParentFile
*/
public File getParentFile() {
return mParentFile;
}
class ViewHolder {
/**文件图标*/
ImageView mFileIcon;
/**文件名称*/
TextView mFileName;
/**文件概要*/
TextView mFileSummary;
}
public class FileItem {
File file;
String spell;
}
}
| 23.654867 | 101 | 0.684811 |
c7e02b53a6b2b3447625059b5a6a81b5d37615b2 | 1,013 | package cn.code.chameleon.utils;
import java.io.File;
/**
* @author liumingyu
* @create 2018-04-11 下午7:34
*/
public class FilePersistent {
protected String path;
public static String PATH_SPLIT = "/";
static {
String property = System.getProperty("file.separator");
PATH_SPLIT = property;
}
public void setPath(String path) {
if (!path.endsWith(PATH_SPLIT)) {
path += PATH_SPLIT;
}
this.path = path;
}
public String getPath() {
return path;
}
public File getFile(String fullName) {
checkAndMakeParentDirectory(fullName);
return new File(fullName);
}
public void checkAndMakeParentDirectory(String fullName) {
int index = fullName.lastIndexOf(PATH_SPLIT);
if (index > 0) {
String path = fullName.substring(0, index);
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
}
}
| 21.553191 | 63 | 0.572557 |
0df9aa0ea853632dbe39667889ca00a1c76e12f1 | 325 | package com.cgy.weixin.ui.view;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by cgy
* 2018/5/29 9:18
*/
public interface IRegisterView {
EditText getEtNickName();
EditText getEtPhone();
EditText getEtPwd();
EditText getEtVerifyCode();
Button getBtnSendCode();
}
| 14.130435 | 32 | 0.692308 |
1725f0d285e50fd7aadafc444ba957239101657c | 7,560 |
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import spark.ModelAndView;
import spark.template.velocity.VelocityTemplateEngine;
import static spark.Spark.*;
public class App {
public static void main(String[] args){
staticFileLocation("/public");
String layout = "templates/layout.vtl";
ProcessBuilder process = new ProcessBuilder();
Integer port;
if (process.environment().get("PORT") != null) {
port = Integer.parseInt(process.environment().get("PORT"));
} else {
port = 4567;
}
port(port);
get("/", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
model.put("animals", Animals.all());
model.put("endangeredAnimals", EndangeredAnimal.all());
model.put("sightings", Sighting.all());
model.put("template", "templates/index.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
//route when user clicks "Post Sighting"
get("/sighting", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
model.put("animals", Animals.all());
model.put("endangeredAnimals", EndangeredAnimal.all());
model.put("template", "templates/sighting.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
//route for adding an endangeredAnimal sighting
post("/endangered_sighting", (request, response) -> {
Map<String, Object> model = new HashMap<>();
String ranger = request.queryParams("ranger");
String location = request.queryParams("location");
String health = request.queryParams("health");
String age = request.queryParams("age");
int animalId = Integer.parseInt(request.queryParams("endangeredAnimalSelected"));
Sighting sighting = new Sighting(ranger, location, animalId,health,age);
sighting.save();
model.put("sighting", sighting);
model.put("animals", EndangeredAnimal.all());
String animal = EndangeredAnimal.find(animalId).getName();
model.put("animal", animal);
model.put("template", "templates/success.vtl");
return new ModelAndView(model, layout);
},new VelocityTemplateEngine());
// route for adding non-endangered animal sighting
post("/sighting ", (request, response) -> {
Map<String, Object> model = new HashMap<>();
String ranger = request.queryParams("ranger");
String location = request.queryParams("location");
String health = request.queryParams("health");
String age = request.queryParams("age");
int animalId = Integer.parseInt(request.queryParams("endangeredAnimalSelected"));
Sighting sighting = new Sighting(ranger, location, animalId,health, age);
sighting.save();
model.put("sighting", sighting);
model.put("animals", EndangeredAnimal.all());
String animal = EndangeredAnimal.find(animalId).getName();
model.put("animal", animal);
model.put("template", "templates/success.vtl");
return new ModelAndView(model, layout);
},new VelocityTemplateEngine());
// route when clicking on "Add Animal to System"
get("/animal/new", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
model.put("template", "templates/animal_form.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
// route for adding new animal form
post("/animal/new", (request, response) -> {
boolean endangered = request.queryParams("endangered")!=null;
if (endangered) {
String name = request.queryParams("name");
String health = request.queryParams("health");
String age = request.queryParams("age");
EndangeredAnimal animal = new EndangeredAnimal(name,health,age);
animal.save();
} else {
String name = request.queryParams("name");
Animals animal = new Animals(name);
animal.save();
}
response.redirect("/");
return null;
});
//route when user clicks "All Animals" or "View Animals"
get("/animals", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
model.put("animals", Animals.all());
model.put("endangeredAnimals", EndangeredAnimal.all());
model.put("sightings", Sighting.all());
model.put("template", "templates/animals.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
//route when you click on an endangeredAnimal
get("/endangered_animal/:id", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
EndangeredAnimal endangeredAnimal = EndangeredAnimal.find(Integer.parseInt(request.params("id")));
model.put("endangeredAnimal", endangeredAnimal);
model.put("template", "templates/endangered_animal.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
//route when you click on a non-endangered animal
get("/animal/:id", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
Animals animal = Animals.find(Integer.parseInt(request.params("id")));
model.put("animal", animal);
model.put("template", "templates/animal.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
get("/error", (request, response) -> {
Map<String, Object> model = new HashMap<String, Object>();
model.put("template", "templates/error.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
// post("/endangered_sighting", (request, response) -> {
// Map<String, Object> model = new HashMap<String, Object>();
// int animalId = Integer.parseInt(request.queryParams("endangeredAnimalSelected"));
// String health = request.queryParams("health");
// String age = request.queryParams("age");
// String location = request.queryParams("location");
// String ranger = request.queryParams("ranger");
// Sighting sighting = new Sighting(ranger, location, animalId);
// sighting.save();
// // model.put("sighting", sighting);
// // model.put("animals", EndangeredAnimal.all());
// String animal = EndangeredAnimal.find(animalId).getName();
// int selectAnimalId = Integer.parseInt(request.queryParams("endangeredAnimalSelected"));
// EndangeredAnimal updatedAnimal = EndangeredAnimal.find(animalId);
// updatedAnimal.update(health, age);
// model.put("animal", animal);
// model.put("template", "templates/success.vtl");
// return new ModelAndView(model, layout);
// }, new VelocityTemplateEngine());
}
}
| 41.086957 | 110 | 0.594312 |
b1b11b30d676cd36f205b81770d158f93359ffb7 | 461 | package TEST;
import java.io.IOException;
public class zd {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Runtime.getRuntime().exec("sudo chmod 755 /usr/local/apache-tomcat-9.0.0.M11/bin/*.sh");
Runtime.getRuntime().exec("cd /usr/local/apache-tomcat-9.0.0.M11");
Runtime.getRuntime().exec("shutdown.sh");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 21.952381 | 91 | 0.67462 |
e4f4a29cfa605393728f99afe8ce2ec3befaa56b | 2,512 | package com.stevengiblin.spring.taleemdb.util;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.stevengiblin.spring.taleemdb.dto.UserDetailsImpl;
import com.stevengiblin.spring.taleemdb.entities.Usr;
@Component
public class MyUtil {
@Autowired
public MyUtil(MessageSource messageSource) {
MyUtil.messageSource = messageSource;
}
public static void flash(RedirectAttributes redirectAttributes, String kind, String messageKey) {
redirectAttributes.addFlashAttribute("flashKind", kind);
redirectAttributes.addFlashAttribute("flashMessage", MyUtil.getMessage(messageKey));
}
private static String activeProfiles;
@Value("${spring.profiles.active}")
public void setActiveProfile(String activeProfiles) {
MyUtil.activeProfiles = activeProfiles;
}
public static boolean isDev() {
return activeProfiles.equals("dev");
}
private static String hostAndPort;
@Value("${hostAndPort}")
public void setHostAndPort(String hostAndPort) {
MyUtil.hostAndPort = hostAndPort;
}
public static String hostUrl() {
return (isDev() ? "http://" : "https://") + hostAndPort;
}
private static MessageSource messageSource;
public static String getMessage(String messageKey, Object... args) {
return messageSource.getMessage(messageKey, args, Locale.getDefault());
}
public static void validate(boolean valid, String msgContent, Object... args) {
if (!valid) {
throw new RuntimeException(getMessage(msgContent, args));
}
}
public static Usr getSessionUser() {
UserDetailsImpl auth = getAuth();
return auth == null ? null : auth.getUser();
}
public static UserDetailsImpl getAuth() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof UserDetailsImpl) {
return (UserDetailsImpl) principal;
}
}
return null;
}
public static boolean checkUserIdValid(long userId) {
return (userId == getSessionUserId());
}
public static long getSessionUserId() {
Usr user = MyUtil.getSessionUser();
return user.getId();
}
}
| 28.224719 | 98 | 0.762739 |
dd20c376cf60c95e56aa1d6cea8834ff20b8e925 | 607 | package ejb;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import facade.AbstractFacade;
import facade.PartidoMetricaFacade;
import model.PartidoMetrica;
@Stateless
public class PartidoMetricaFacadeEJB extends AbstractFacade<PartidoMetrica> implements PartidoMetricaFacade {
@PersistenceContext(unitName = "politweetsPU")
private EntityManager em;
public PartidoMetricaFacadeEJB() {
super(PartidoMetrica.class);
}
@Override
protected EntityManager getEntityManager() {
return this.em;
}
}
| 22.481481 | 109 | 0.7743 |
10661fefdff3e462f7d8c3159e3ae6e664d118cf | 2,926 | package breadth_first_search;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
*
* @author minchoba
* 백준 13565번: 침투
*
* @see https://www.acmicpc.net/problem/13565/
*
*/
public class Boj13565 {
private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
private static final int ROW = 0;
private static final int COL = 1;
private static final int CURRENT = 0;
private static final int FIBER = 2;
private static int[][] map = null;
private static Point[] finish = null;
public static void main(String[] args) throws Exception{
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
Point[] start = new Point[M];
finish = new Point[M];
int sidx = 0, fidx = 0;
map = new int[N][M];
for(int i = 0; i < N; i++) {
String line = br.readLine();
for(int j = 0; j < M; j++) {
map[i][j] = line.charAt(j) - '0';
if(i == 0 && map[i][j] == CURRENT) { // 시작 지점 저장
start[sidx++] = new Point(i, j);
}
if(i == N - 1 && map[i][j] == CURRENT) { // 종료 지점 저장
finish[fidx++] = new Point(i, j);
}
}
}
System.out.println(bfs(N, M, start)); // 너비 우선 탐색 메소드를 통한 결과 출력
}
/**
* 정점 이너 클래스
* @author minchoba
*
*/
private static class Point{
int row;
int col;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
}
/**
* 너비 우선 탐색 메소드
*
*/
private static String bfs(int n, int m, Point[] start) {
boolean[][] isVisited = new boolean[n][m];
for(Point s: start) {
if(s == null) continue;
if(isVisited[s.row][s.col]) continue;
Queue<Point> q = new LinkedList<>();
q.offer(new Point(s.row, s.col));
isVisited[s.row][s.col] = true;
map[s.row][s.col] = FIBER;
while(!q.isEmpty()) {
Point current = q.poll();
for(final int[] DIRECTION: DIRECTIONS) {
int nextRow = DIRECTION[ROW] + current.row;
int nextCol = DIRECTION[COL] + current.col;
if(nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < m) {
if(!isVisited[nextRow][nextCol] && map[nextRow][nextCol] == CURRENT) {
isVisited[nextRow][nextCol] = true; // 섬유 물질이 흐를 수 있는 곳은 섬유 물질로 채워줌
map[nextRow][nextCol] = FIBER;
q.offer(new Point(nextRow, nextCol));
}
}
}
}
}
return isPercolate(n, m) ? "YES" : "NO"; // 침투가 완료되었으면 YES, 아니면 NO를 반환
}
/**
* 침투 결과 메소드
*
*/
private static boolean isPercolate(int n, int m) {
for(Point f: finish) {
if(f == null) continue;
if(map[f.row][f.col] == FIBER) return true; // 끝 점에 섬유 물질이 존재 할 경우 참
}
return false; // 끝 점을 모두 방문 했는데도 물질이 없는 경우 거짓
}
}
| 23.596774 | 78 | 0.580998 |
26eb2bcf82a961d598a9a51838f1681c0fb388b5 | 1,595 | package com.edu.service.classctr;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.fh.dao.DaoSupport;
import com.fh.entity.Page;
import com.fh.util.PageData;
@Service("classattendanceService")
public class ClassAttendanceService {
@Resource(name = "daoSupport")
private DaoSupport dao;
/*
* 新增
*/
public void save(PageData pd)throws Exception{
dao.save("ClassAttendanceMapper.save", pd);
}
/*
* 删除
*/
public void delete(PageData pd)throws Exception{
dao.delete("ClassAttendanceMapper.delete", pd);
}
/*
* 修改
*/
public void edit(PageData pd)throws Exception{
dao.update("ClassAttendanceMapper.edit", pd);
}
/*
*列表
*/
public List<PageData> list(Page page)throws Exception{
return (List<PageData>)dao.findForList("ClassAttendanceMapper.datalistPage", page);
}
/*
*列表(全部)
*/
public List<PageData> listAll(PageData pd)throws Exception{
return (List<PageData>)dao.findForList("ClassAttendanceMapper.listAll", pd);
}
/*
* 通过id获取数据
*/
public PageData findById(PageData pd)throws Exception{
return (PageData)dao.findForObject("ClassAttendanceMapper.findById", pd);
}
/*
* 批量删除
*/
public void deleteAll(String[] ArrayDATA_IDS)throws Exception{
dao.delete("ClassAttendanceMapper.deleteAll", ArrayDATA_IDS);
}
/*
* 通过CLASS_ID获得CLASS_NUMBER
*/
public PageData getClassId(PageData pd)throws Exception{
return (PageData)dao.findForObject("ClassAttendanceMapper.getClassId", pd);
}
}
| 20.448718 | 86 | 0.698433 |
0974efc5003ed2e25fc0db2e5b7ede3d7df0d6b1 | 471 | package java;
import Servlet.LanguageTranslationServlet;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class LangTest{
private LanguageTranslationServlet lang;
@Before
public void initializelangath(){
lang = new LanguageTranslationServlet();
}
@Test(timeout=1000)
public void inputShouldReturnCorrectTranslation() {
assertEquals("'Hello' should be 'Hola' ", "Hola", lang.test());
}
}
| 20.478261 | 65 | 0.740977 |
67c877699c48c4ac0c35b59dc8cce9e41f47c359 | 1,659 | package nil.ed.livechat.common.enums;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Created at 2019-12-12
*
* @author lidelin
*/
public enum NginxNotificationType {
/**
* All notification type of nginx_rtmp
*/
PUBLISH("publish", "notify when video is published"),
PUBLISH_DONE("publish_done", "notify when publish terminate"),
PLAY("play", "notify when video is played by client"),
PLAY_DONE("play_done", "notify when client play terminate"),
RECORD_DONE("record_done", "notify when video record completed"),
DONE("done", "notify when play or publish terminate"),
/**
* The following two are concrete type of update event
*/
UPDATE_PUBLISH("update_publish", "notify when video file is refreshed"),
UPDATE_PLAY("update_play", "notify when play is updated(default with the interval 30s)"),
CONNECT("connect", "client connect event");
private static Map<String, NginxNotificationType> indexMapper = new HashMap<>(8, 1);
static {
Arrays.stream(NginxNotificationType.values())
.forEach(type -> indexMapper.put(type.callText, type));
}
private final String callText;
private final String description;
NginxNotificationType(String callText, String description) {
this.callText = callText;
this.description = description;
}
public String getCallText() {
return callText;
}
public String getDescription() {
return description;
}
public static NginxNotificationType getTypeByCallText(String callText) {
return indexMapper.get(callText);
}
}
| 28.603448 | 93 | 0.68053 |
ed85f0a296e0b7618a7fa3dced87a1346cb8dd59 | 7,829 | /*
* Copyright 2008-2009 MOSPA(Ministry of Security and Public Administration).
*
* 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 egovframework.dev.imp.codegen.template.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import net.sf.abstractplugin.core.EclipseProjectUtils;
import net.sf.abstractplugin.util.ThreadUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.eclipsework.core.EclipseWorkFactoryManager;
import org.eclipse.eclipsework.core.interfaces.IEWUtils;
import org.eclipse.eclipsework.core.jdom.element.wizard.WizardModelElement;
import org.eclipse.eclipsework.core.wizard.IEWWizard;
import org.eclipse.eclipsework.core.wizard.IEWWizardPage;
import org.eclipse.eclipsework.core.wizard.WizardHelper;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import egovframework.dev.imp.codegen.template.CodeGenLog;
import egovframework.dev.imp.codegen.template.util.LogUtil;
import egovframework.dev.imp.codegen.template.util.TemplateUtil;
/**
*
* 코드 생성 마법사 클래스
* <p><b>NOTE:</b> 코드 생성을 위한 데이터를 사용자로부터 입력 받기 위한 마법사 클래스
*
* @author 개발환경 개발팀 이흥주
* @since 2009.08.03
* @version 1.0
* @see
*
* <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.08.03 이흥주 최초 생성
*
* </pre>
*/
@SuppressWarnings("restriction")
public class CodeGenWizard extends Wizard implements IEWWizard
, egovframework.dev.imp.codegen.template.wizards.Wizard
, BusinessLayerSkeletonGeneration
, PresentationLayerSkeletonGeneration{
/** 로거 */
protected final Logger log = Logger.getLogger(CodeGenWizard.class);
/**
*
* 생성자
*
*/
public CodeGenWizard(){
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
}
/**
*
* 페이지 추가
*
* @param iewwizardpage
*/
public void addPage(IEWWizardPage iewwizardpage) {
addPage((IWizardPage) iewwizardpage);
}
/**
*
* 페이지 추가
*
*/
public void addPages() {
if (WizardHelper.invalidXMLWizard) {
return;
}
super.addPages();
WizardModelElement xmlModelPage = WizardHelper.wizards.getWizardModelPage();
if (xmlModelPage != null) {
addWizardModelPage(xmlModelPage, WizardHelper.mode);
}
WizardHelper.addComponentPages();
}
/**
*
* 마법사 페이지 가져오기
*
* @return
*/
public IEWWizardPage[] getWizardPages() {
IWizardPage[] eclipsePages = getPages();
IEWWizardPage[] pages = new IEWWizardPage[getPageCount()];
for (int i = 0; i < pages.length; i++) {
pages[i] = (IEWWizardPage) eclipsePages[i];
}
return pages;
}
/**
*
* VelocityContext 값 넣기
*
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, TemplateUtil> putValuesToVelocityContext() {
Map<String, TemplateUtil> map = WizardHelper.putVariablesToVelocityContext();
IProject project = EclipseProjectUtils.getSelectedProject();
TemplateUtil templateUtil = new TemplateUtil(project);
map.put("templateUtil", templateUtil);
return map;
}
/**
*
* 시작
*
*/
public void start() {
WizardDialog dialog = new WizardDialog(getShell(), this);
dialog.create();
dialog.open();
}
/**
*
* 페이지 검증
*
* @return
*/
public boolean validatePages() {
return WizardHelper.validatePages();
}
/**
*
* 다음 페이지 가져오기
*
* @param page
* @return
*/
public IWizardPage getNextPage(IWizardPage page) {
return super.getNextPage(page);
}
/**
*
* 마법사 종료
*
* @return
*/
@Override
public boolean performFinish() {
try {
LogUtil.consoleClear();
log.info("====================================================================================");
log.info("eGovFrame Code Generation ...");
log.info("====================================================================================");
doFinish();
log.info("====================================================================================");
log.info("Code Generation has finished.");
log.info("You need to Check above logs");
log.info("====================================================================================");
return true;
} catch (Exception e) {
log.error(e, e);
EclipseWorkFactoryManager.getUtils().logMessage(this, IEWUtils.ERROR_MESSAGE);
log.error("Some Error Occured in Code Generation.");
return false;
} finally {
// Always clear the temporary Map
WizardHelper.getAuxiliarMap().clear();
}
}
/**
*
* 마법사 종료시 실행
*
*/
private void doFinish() {
try {
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(final IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
monitor.beginTask("eGovFrame code generation. ", 100);
ThreadUtils.start(getShell(), new Runnable() {
public void run() {
WizardHelper.finish(null);
}
});
monitor.done();
}
};
new ProgressMonitorDialog(getShell()).run(true, true, op);
// log.info("Code Generation has Finished.");
} catch (Exception e) {
CodeGenLog.logError(e);
}
}
/**
*
* 모델 마법사 페이지 추가(테이블 선택 페이지)
*
* @param xmlModelPage
* @param mode
*/
private void addWizardModelPage(WizardModelElement xmlModelPage, int mode) {
CodeGenTableWizardPage tableWizardPage = new CodeGenTableWizardPage(xmlModelPage.getDescription()
, xmlModelPage.isRequired()
, xmlModelPage.getImage());
if (mode >= 0) {
addPage((IWizardPage)tableWizardPage);
}
}
/*
* 비즈니스 로직 코드 생성
*
* (non-Javadoc)
* @see egovframework.dev.imp.codegen.template.wizards.BusinessLayerSkeletonGeneration#businessCodeGen()
*/
public void businessCodeGen() {
doFinish();
}
/*
* 프리젠테이션 로직 코드 생성
*
* (non-Javadoc)
* @see egovframework.dev.imp.codegen.template.wizards.PresentationLayerSkeletonGeneration#presentationCodeGen()
*/
public void presentationCodeGen() {
doFinish();
}
}
| 28.060932 | 116 | 0.567761 |
d3777434b56d71122e17fc688d20dac6b1828c54 | 2,151 | package com.bluebox.security.authenticationserver.persistence.repository;
import com.bluebox.security.authenticationserver.util.CustomDBUnitExtension;
import com.github.database.rider.core.api.configuration.DBUnit;
import com.github.database.rider.core.api.dataset.DataSet;
import com.github.database.rider.junit5.DBUnitExtension;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
/**
* @author by kamran ghiasvand
*/
@SpringBootTest(properties = {"spring.aop.auto=false"})
@ExtendWith({SpringExtension.class, CustomDBUnitExtension.class})
@DataSet(value = "permissions.yml",cleanBefore = true,useSequenceFiltering = false)
@DBUnit(schema = "wedding_auth_server_test")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Transactional
public class PermissionRepositoryTest {
@Autowired
private PermissionRepository repository;
@Test
@Order(1)
public void findById() {
final var actual = repository.findById(1L);
Assertions.assertNotNull(actual);
Assertions.assertFalse(actual.isEmpty());
final var entity = actual.get();
Assertions.assertEquals("POST /api/test", entity.getName());
}
@Test
@Order(2)
public void findAll() {
final var actual = repository.findAll();
Assertions.assertNotNull(actual);
Assertions.assertEquals(2, actual.size());
final var first = actual.stream().filter(m -> m.getId() == 1).findFirst();
Assertions.assertNotNull(first);
Assertions.assertFalse(first.isEmpty());
Assertions.assertEquals("POST /api/test", first.get().getName());
final var second = actual.stream().filter(m -> m.getId() == 2).findFirst();
Assertions.assertNotNull(second);
Assertions.assertFalse(second.isEmpty());
Assertions.assertEquals("GET /api/test", second.get().getName());
}
}
| 39.109091 | 83 | 0.733612 |
0171a88f4a69b6fb5959b8e57da52d05a5be75fa | 2,628 | /*
* Copyright 2010-2012 Amazon Technologies, 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://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Load Balancing section of the human-readable environment config editor.
*/
public class LoadBalancingConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("LoadBalancerHTTPPort", "HTTP Port");
humanReadableNames.put("LoadBalancerHTTPSPort", "HTTPS Port");
humanReadableNames.put("SSLCertificateId", "SSL Certificate Id");
}
private static final String[] fieldOrder = new String[] { "LoadBalancerHTTPPort", "LoadBalancerHTTPSPort",
"SSLCertificateId" };
public LoadBalancingConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Load Balancing";
}
@Override
protected String getSectionDescription() {
return "These settings allow you to control the behavior of your environment's load balancer.";
}
@Override
protected Section getSection(Composite parent) {
return toolkit.createSection(parent, Section.EXPANDED | Section.DESCRIPTION | Section.NO_TITLE);
}
}
| 36.5 | 182 | 0.723744 |
ba387fc215ea4948bb525de5ca7d43092160bf3c | 1,940 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ratis.metrics;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.jvm.ClassLoadingGaugeSet;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
public class JVMMetrics {
static MetricRegistryInfo info = new MetricRegistryInfo("jvm", "ratis_jvm", "jvm", "jvm metrics");
static RatisMetricRegistry registry = MetricRegistries.global().create(info);
static {
registry.registerAll("gc", new GarbageCollectorMetricSet());
registry.registerAll("memory", new MemoryUsageGaugeSet());
registry.registerAll("threads", new ThreadStatesGaugeSet());
registry.registerAll("classLoading", new ClassLoadingGaugeSet());
}
public static RatisMetricRegistry getRegistry() {
return registry;
}
public static void startJVMReporting(long period, TimeUnit unit,
MetricsReporting.MetricReporterType... reporting){
MetricsReporting metricsReporting = new MetricsReporting(period,unit);
metricsReporting.startMetricsReporter(getRegistry(), reporting);
}
}
| 41.276596 | 100 | 0.770619 |
82ac28cd460961a320e051a5954960f6aa327074 | 488 | package org.rioproject.resolver;
import java.net.HttpURLConnection;
import java.net.URL;
class ConnectionCheck {
static boolean connected() {
boolean online = true;
try {
URL url = new URL("http://www.rio-project.org/maven2");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.getResponseCode();
} catch(Exception e) {
online = false;
}
return online;
}
}
| 25.684211 | 84 | 0.610656 |
a82f1b7ad8a39a96a0909952c1dfa551ef332c3a | 149 | package envoriment;
public class EnvironmentInfo {
public static boolean isRunningOnCI() {
return System.getenv("CI") != null;
}
}
| 16.555556 | 43 | 0.66443 |
dcaec8452ce9f834b6587099825c6c9772ef891b | 1,185 | package at.meinedomain.CheckIt.Pieces;
import at.meinedomain.CheckIt.Assets;
import at.meinedomain.CheckIt.Board;
import at.meinedomain.CheckIt.Color;
import at.meinedomain.CheckIt.MoveType;
import at.meinedomain.CheckIt.Point;
public class Knight extends AbstractPiece {
public Knight(Board b, Color c, Point pt){
super(b, c, pt, "KNIGHT");
if(c == Color.WHITE){
pixmap = Assets.wn;
} else{
pixmap = Assets.bn;
}
}
@Override
protected MoveType canMove(Point to) {
if(board.leavesInCheck(color, location, to)){
return MoveType.ILLEGAL;
}
if(attacks(to)) {
if(isEmpty(to)){
return MoveType.NORMAL;
}
if(isOccupiedByOpponent(to)){
return MoveType.CAPTURE;
}
}
return MoveType.ILLEGAL;
}
@Override
public boolean attacks(Point tile, Point not, Point instead){
int distX = horizontalDist(tile);
int distY = verticalDist(tile);
if(Math.max(distX, distY) == 2 &&
Math.min(distX, distY) == 1 ){
return true;
}
return false;
}
// // tryToMove() not needed. super-implementation sufices.
// @Override
// public void tryToMove(Point pt) {
// // TODO Auto-generated method stub
//
// }
}
| 19.112903 | 62 | 0.670042 |
f489b3e61bc25663d6eed85ed15f261dcedb86de | 1,519 | package fr.insee.rmes.model.structures;
import fr.insee.rmes.exceptions.RmesException;
public class ComponentDefinition {
private String id;
private String created;
private String modified;
private String order;
private String[] attachment = new String[0];
private Boolean required = false;
private MutualizedComponent component;
public ComponentDefinition() throws RmesException {
//nothing to do
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String[] getAttachment() {
return attachment;
}
public void setAttachment(String[] attachment) {
this.attachment = attachment;
}
public MutualizedComponent getComponent() {
return component;
}
public void setComponent(MutualizedComponent component) {
this.component = component;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
}
| 19.986842 | 61 | 0.63002 |
907c14329373a22fb2dd8e8a8d1a488929ef12f2 | 3,647 | package com.example.davinci.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.davinci.R;
import com.example.davinci.SelectionSpec;
import com.example.davinci.engine.ImageEngine;
import com.example.davinci.util.ImageLoader;
import java.util.List;
import java.util.Map;
/**
* 预览界面缩略图的横向RecyclerView适配器
*/
public class PreviewThumbnailAdapter extends RecyclerView.Adapter<PreviewThumbnailAdapter.ViewHolder> {
private int mNewPosition;
private int mLastPosition;
private ImageEngine mEngine;
private ImageView mImageView;
private List<String> mSelectedImg;
private PreviewThumbnailAdapter.OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener{
void onClick(int position);
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
View thumbnailFrame;
ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.id_preview_thumbnail);
thumbnailFrame = itemView.findViewById(R.id.id_preview_thumbnail_frame);
}
}
public PreviewThumbnailAdapter(List<String> imgList) {
mEngine = SelectionSpec.getInstance().imageEngine;
mSelectedImg = imgList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@SuppressLint("InflateParams") View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.preview_recyclerview_item, null, false);
return new ViewHolder(view);
}
@SuppressLint("ResourceType")
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") final int position) {
String path = mSelectedImg.get(position);
ImageView iv = holder.imageView;
mEngine.loadThumbnail(ImageLoader.Type.LIFO, path, iv, 60);
if (position == mNewPosition) {
holder.thumbnailFrame.setVisibility(View.VISIBLE);
mImageView = holder.imageView;
} else {
holder.thumbnailFrame.setVisibility(View.GONE);
}
if(mOnItemClickListener != null){
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mOnItemClickListener.onClick(position );
}
});
}
}
@Override
public int getItemCount() {
return mSelectedImg.size();
}
/**
* 传入当前页面的position
* @param position 当前页的位置
*/
public void setCurrentPosition(int position) {
Log.e("position", ""+position );
mNewPosition = position;
notifyItemChanged(mNewPosition);
notifyItemChanged(mLastPosition);
mLastPosition = mNewPosition;
}
/**
* 返回当前缩略图实例
* @return 当前缩略图实例
*/
public ImageView getImageView(){
return mImageView;
}
/**
* 获取接口的实例化
* @param onItemClickListener 接口的实例化
*/
public void setOnItemClickListener(PreviewThumbnailAdapter.OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
}
| 31.439655 | 150 | 0.664656 |
1df47d4695e65a5353f1df9c2401dfe0f0341cbe | 1,175 | package com.hotpot.domain;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Optional;
@Slf4j
@AllArgsConstructor
public class ServiceObjectiveEvaluator {
private final ServiceDataSourcePicker serviceDataSourcePicker;
public Optional<ServiceObjectiveResult> runOnService(ServiceObjective objective, Service service) {
if (!objective.getIsApplicableTo().test(service)) {
return Optional.empty();
}
boolean success = objective.getCriteria()
.stream()
.allMatch(criterion -> checkForService(criterion, service.getId()));
return Optional.of(
new ServiceObjectiveResult(
service.getId(),
objective.getId(),
ServiceObjectiveResult.Status.fromBoolean(success)
)
);
}
private <T> boolean checkForService(Criterion<T> criterion, ServiceId serviceId) {
ServiceMetric<T> metric = criterion.getMetric();
return criterion.getCondition().test(
serviceDataSourcePicker.getDataProvider(metric.getId()).getForService(metric, serviceId)
);
}
}
| 28.658537 | 103 | 0.666383 |
27e960d914c13550dee35e73ce28f5252368039d | 816 | public class LongestPalindromicSubstring {
private LongestPalindromicSubstring() {
}
public static String findLongestPalindrome(String string) {
int length = 0;
int beginIndex = 0;
boolean event = string.length() % 2 == 0;
for (int i = 1; i < string.length() - 1; i++) {
int left = i, right = event ? i + 1 : i;
while (left > 0 && right < string.length() - 1 && string.charAt(left - 1) == string.charAt(right + 1)) {
left--;
right++;
}
int currentLength = right - left;
if (length < currentLength) {
length = currentLength;
beginIndex = left;
}
}
return string.substring(beginIndex, beginIndex + length + 1);
}
}
| 31.384615 | 116 | 0.509804 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.