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
|
---|---|---|---|---|---|
63cc32bcf44101ece88843fd3d0d1c398d3f5174 | 1,675 | package com.example.forum_4_stupid.unit.service;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.example.forum_4_stupid.exceptions.AccountDoesNotExistException;
import com.example.forum_4_stupid.model.Users;
import com.example.forum_4_stupid.repository.UsersRepository;
import com.example.forum_4_stupid.service.UserService;
@ExtendWith(value = SpringExtension.class)
public class UserServiceTest {
@Mock
private UsersRepository repo;
private UserService userService;
@BeforeEach
public void setUp() {
userService = new UserService(repo);
}
@org.junit.jupiter.api.Test
public void shouldCallFindByIdFromUserRepo() {
Optional<Users> user = Optional.of(new Users(1,
"test", LocalDateTime.now(),
"testpassword", true,
null, null));
when(repo.findById(1)).thenReturn(user);
userService.findUserById(1);
verify(repo, times(1)).findById(1);
}
@org.junit.jupiter.api.Test
public void shouldThrowAccountDoesNotExistException() {
Optional<Users> user = Optional.of(new Users(1,
"test", LocalDateTime.now(),
"testpassword", true,
null, null));
when(repo.findById(1)).thenReturn(user);
assertThrows(AccountDoesNotExistException.class,
() -> userService.findUserById(2));
verify(repo, times(1)).findById(2);
}
}
| 28.389831 | 74 | 0.768358 |
2917f5eb4b527b1d6f6896e5b636797b033ee71a | 365 | package io.sapl.grammar.sapl.impl;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class CombiningAlgorithmImplCustomTest {
@Test
void cannotBeCalled() {
var combiner = new CombiningAlgorithmImplCustom();
assertThrows(UnsupportedOperationException.class, () -> combiner.combineDecisions(null, true));
}
}
| 22.8125 | 97 | 0.786301 |
c463c68a3f8d303236be73750111e515d5c94b74 | 3,839 | package org.camunda.bpm.extension.reactor.fn;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.delegate.DelegateCaseExecution;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.repository.CaseDefinition;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class GetProcessDefinitionKeyTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule
public final MockitoRule mockito = MockitoJUnit.rule();
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private DelegateTask task;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private DelegateCaseExecution caseExecution;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private DelegateExecution execution;
@Mock
private RepositoryService repositoryService;
@Before
public void setUp() throws Exception {
when(task.getProcessEngineServices().getRepositoryService()).thenReturn(repositoryService);
when(caseExecution.getProcessEngineServices().getRepositoryService()).thenReturn(repositoryService);
when(execution.getProcessEngineServices().getRepositoryService()).thenReturn(repositoryService);
}
@Test
public void get_from_task_via_process() throws Exception {
processDefinition("1", "proc");
when(task.getProcessDefinitionId()).thenReturn("1");
assertThat(GetProcessDefinitionKey.from(task)).isEqualTo("proc");
}
@Test
public void get_from_task_via_case() throws Exception {
caseDefinition("1", "case");
when(task.getCaseDefinitionId()).thenReturn("1");
assertThat(GetProcessDefinitionKey.from(task)).isEqualTo("case");
}
@Test
public void cannot_load_process_for_task() throws Exception {
when(task.getProcessDefinitionId()).thenReturn("not there!");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("bpmn/not there!");
GetProcessDefinitionKey.from(task);
}
@Test
public void cannot_load_case_for_task() throws Exception {
when(task.getCaseDefinitionId()).thenReturn("not there!");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("cmmn/not there!");
GetProcessDefinitionKey.from(task);
}
@Test
public void get_from_caseExecution() throws Exception {
caseDefinition("1", "case");
when(caseExecution.getCaseDefinitionId()).thenReturn("1");
assertThat(GetProcessDefinitionKey.from(caseExecution)).isEqualTo("case");
}
@Test
public void get_from_execution() throws Exception {
processDefinition("1", "proc");
when(execution.getProcessDefinitionId()).thenReturn("1");
assertThat(GetProcessDefinitionKey.from(execution)).isEqualTo("proc");
}
private CaseDefinition caseDefinition(String id, String key) {
CaseDefinition caseDefinition = mock(CaseDefinition.class);
when(caseDefinition.getId()).thenReturn(id);
when(caseDefinition.getKey()).thenReturn(key);
when(repositoryService.getCaseDefinition(id)).thenReturn(caseDefinition);
return caseDefinition;
}
private ProcessDefinition processDefinition(String id, String key) {
ProcessDefinition processDefinition = mock(ProcessDefinition.class);
when(processDefinition.getId()).thenReturn(id);
when(processDefinition.getKey()).thenReturn(key);
when(repositoryService.getProcessDefinition(id)).thenReturn(processDefinition);
return processDefinition;
}
}
| 32.533898 | 104 | 0.772076 |
608d846facf863919e8b9f50feb2ec9dd8fc33ef | 1,658 | package act.util;
import act.Destroyable;
import act.app.App;
import act.app.AppByteCodeScanner;
import act.app.AppCodeScannerManager;
import act.app.AppSourceCodeScanner;
import org.osgl.logging.L;
import org.osgl.logging.Logger;
import org.osgl.util.C;
import javax.enterprise.context.ApplicationScoped;
import java.util.Map;
public class AppCodeScannerPluginManager extends DestroyableBase {
private static final Logger logger = L.get(AppCodeScannerPluginManager.class);
private Map<Class<? extends AppCodeScannerPluginBase>, AppCodeScannerPluginBase> registry = C.newMap();
public void register(AppCodeScannerPluginBase plugin) {
Class<? extends AppCodeScannerPluginBase> clz = plugin.getClass();
if (registry.containsKey(clz)) {
logger.warn("%s has already been registered", clz);
return;
}
registry.put(clz, plugin);
}
public void initApp(App app) {
AppCodeScannerManager manager = app.scannerManager();
for (AppCodeScannerPluginBase plugin : registry.values()) {
AppSourceCodeScanner sourceCodeScanner = plugin.createAppSourceCodeScanner(app);
if (null != sourceCodeScanner) {
manager.register(sourceCodeScanner);
}
AppByteCodeScanner byteCodeScanner = plugin.createAppByteCodeScanner(app);
if (null != byteCodeScanner) {
manager.register(byteCodeScanner);
}
}
}
@Override
protected void releaseResources() {
Destroyable.Util.tryDestroyAll(registry.values(), ApplicationScoped.class);
registry.clear();
}
}
| 33.16 | 107 | 0.689988 |
b3054507a9d581423e55e98ef94c0609b18cc152 | 725 | class Solution {
public int[] distributeCandies(int candies, int num_people) {
int[] distrCand = new int[num_people];
int iteration = 0;
while(true)
{
for(int i = 0; i < num_people; i++)
{
candies -= (i+1+iteration);
distrCand[i] += (i+1+iteration);
if(candies < 0)
{
distrCand[i] += candies;
break;
}
}
if(candies <= 0)
break;
iteration += num_people;
}
return distrCand;
}
}
| 22.65625 | 65 | 0.347586 |
99ae5eb43e6d6da7f407db776ad07df8909593e2 | 1,668 | package org.atlasapi.content.v2.model.udt;
import com.datastax.driver.mapping.annotations.Field;
import com.datastax.driver.mapping.annotations.UDT;
import org.joda.time.Instant;
import java.util.Objects;
/** This doesn't hold the actual ID and publisher because those are the strict PK of
* any resource ref. These objects are usually stored as a CQL {@code map<Ref, PartialItemRef>} and
* serialised accordingly. If you need to store a full {@code PartialItemRef} as a field, you'll need a
* to make a different UDT.
*
* @see Ref
* @see SeriesRef
*/
@UDT(name = "itemref")
public class PartialItemRef {
@Field(name = "sort_key") private String sortKey;
@Field(name = "updated") private Instant updated;
@Field(name = "type") private String type;
public PartialItemRef() {}
public String getSortKey() {
return sortKey;
}
public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}
public Instant getUpdated() {
return updated;
}
public void setUpdated(Instant updated) {
this.updated = updated;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
PartialItemRef that = (PartialItemRef) object;
return Objects.equals(sortKey, that.sortKey) &&
Objects.equals(type, that.type);
}
@Override
public int hashCode() {
return Objects.hash(sortKey, type);
}
}
| 26.0625 | 103 | 0.652878 |
00b33693d4dcd7a7a145ac29e83946e235add501 | 2,323 | package com.mikescamell.sharedelementtransitions.picasso_fragment_to_fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.mikescamell.sharedelementtransitions.R;
import com.squareup.picasso.Picasso;
public class PicassoFragmentA extends Fragment {
public static final String TAG = PicassoFragmentA.class.getSimpleName();
public static String GIRAFFE_PIC_URL = "http://ichef.bbci.co.uk/naturelibrary/images/ic/credit/640x395/g/gi/giraffe/giraffe_1.jpg";
public PicassoFragmentA() {
// Required empty public constructor
}
public static PicassoFragmentA newInstance() {
return new PicassoFragmentA();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.picasso_fragment_a, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageView imageView = view.findViewById(R.id.picasso_fragment_a_imageView);
Picasso.with(getContext())
.load(GIRAFFE_PIC_URL)
.fit()
.centerCrop()
.into(imageView);
Button button = view.findViewById(R.id.picasso_fragment_a_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PicassoFragmentB simpleFragmentB = PicassoFragmentB.newInstance();
getFragmentManager()
.beginTransaction()
.addSharedElement(imageView, ViewCompat.getTransitionName(imageView))
.addToBackStack(TAG)
.replace(R.id.content, simpleFragmentB)
.commit();
}
});
}
} | 35.738462 | 135 | 0.671115 |
87e7f52188916708aad210f6b1858f9d5ee94177 | 1,148 | package Leetcode.Tree.BinarySearchTree;
import java.util.ArrayList;
// Inorder traversal gives ascending order!
public class FindModeInBinarySearchTree_501 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
private ArrayList<Integer> modes = new ArrayList<>();
private TreeNode prev;
private int max_mode, curr;
public int[] findMode(TreeNode root) {
traverse(root);
int[] res = new int[modes.size()];
for (int i = 0; i < modes.size(); i++){
res[i] = modes.get(i);
}
return res;
}
public void traverse(TreeNode root){
if (root == null)
return;
traverse(root.left);
if (prev != null && prev.val == root.val){
curr ++;
}
else {
curr = 1;
}
if (curr > max_mode){
modes.clear();
modes.add(root.val);
max_mode = curr;
} else if (curr == max_mode){
modes.add(root.val);
}
prev = root;
traverse(root.right);
}
}
| 23.916667 | 57 | 0.515679 |
53ee4151fa84b350af9f22442d272d81117dfbc5 | 1,892 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.acme.multinode.grid;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
/**
* TestUtils
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
public class TestUtils {
public static Integer readInt(URL url) throws Exception {
return readInt(url.openStream());
}
public static Integer readInt(InputStream is) throws Exception {
return Integer.parseInt(readAllAndClose(is));
}
public static String readAllAndClose(URL url) throws Exception {
return readAllAndClose(url.openStream());
}
public static String readAllAndClose(InputStream is) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
int read;
while ((read = is.read()) != -1) {
out.write(read);
}
} finally {
try {
is.close();
} catch (Exception e) {
}
}
return out.toString();
}
}
| 32.067797 | 75 | 0.667019 |
413f1d054eaa36a781356ccabc3e93e88e889c0f | 1,050 | package org.enricogiurin.codingchallenges.codeforces.old.c1247;
import java.io.PrintWriter;
import java.util.Scanner;
public class ForgettingThingsA extends PrintWriter {
//this trick improves performances
ForgettingThingsA() {
super(System.out);
}
public static void main(String[] $) {
ForgettingThingsA o = new ForgettingThingsA();
o.main();
o.flush();
}
void main() {
Scanner sc = new Scanner(System.in);
// int count = sc.nextInt();
//use this if just a single test
int count = 1;
while (count-- > 0) {
final int da = sc.nextInt();
final int db = sc.nextInt();
if (da == db) {
println(10 * da + " " + ((db * 10) + 1));
} else if (db == da + 1) {
println(10 * da + 9 + " " + 10 * db);
} else if (da == 9 && db == 1) {
println("99 100");
} else {
println(-1);
}
}
sc.close();
}
}
| 26.923077 | 63 | 0.482857 |
ae91fa8d105ccc63af75cd00431fcbef97fb75c3 | 933 | /**
* Multiple Devices
*
* Copyright 2016 by Tim Dünte <[email protected]>
* Copyright 2016 by Max Pfeiffer <[email protected]>
*
* Licensed under "The MIT License (MIT) – military use of this product is forbidden – V 0.2".
* Some rights reserved. See LICENSE.
*
* @license "The MIT License (MIT) – military use of this product is forbidden – V 0.2"
* <https://bitbucket.org/MaxPfeiffer/letyourbodymove/wiki/Home/License>
*/
package com.example.emsdesigntool.commands;
import java.util.ArrayList;
import java.util.Observer;
public interface IEMSBluetoothLEService {
public boolean isConnected();
public EMSGattCallback connectTo(String deviceName);
public void disconnect(String deviceName);
public ArrayList<String> getListOfFoundEMSDevices();
public void findDevices();
public void stopFindingDevices();
public void addObserver(Observer observer);
}
| 26.657143 | 95 | 0.736334 |
0be4ca566c97700a6a9844a8f422bd395e26a5a4 | 1,032 | public abstract class TableHeader {
String type;
public TableHeader() {
}
public String toString() {
return type;
}
public abstract TableData createTableData();
}
class TableHeaderInt extends TableHeader {
public TableHeaderInt() {
type = "INT";
}
@Override
public TableData createTableData() {
return new TableDataInt();
}
}
class TableHeaderDouble extends TableHeader {
public TableHeaderDouble() {
type = "DOUBLE";
}
@Override
public TableData createTableData() {
return new TableDataDouble();
}
}
class TableHeaderChar extends TableHeader {
public TableHeaderChar() {
type = "CHAR";
}
@Override
public TableData createTableData() {
return new TableDataChar();
}
}
class TableHeaderBoolean extends TableHeader {
public TableHeaderBoolean() {
type = "BOOLEAN";
}
@Override
public TableData createTableData() {
return new TableDataBoolean();
}
}
| 18.428571 | 48 | 0.628876 |
349b9e81035f3ce6bf01334a9cbd770829031e63 | 3,753 | package cn.xr.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
@Configuration
@Data
public class AppealConfig extends WebMvcConfigurationSupport {
/**
* 跨域处理
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
//表示所有的请求路径都经过跨域处理
registry.addMapping("/**")
.allowedOrigins("*")
/*.allowedMethods("*")
.allowedHeaders("*")*/
.allowedMethods("POST", "GET", "DELETE", "OPTIONS", "PUT")
.allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Content-Length", "remember-me",
"auth", "Cookie", "Authorization", "AppId")
//允许在请求头里存放信息,后端通过请求头来获取前端传来的信息
.exposedHeaders("Authorization", "AppId")
//设置是否允许跨域传cookie
.allowCredentials(true)
.maxAge(3600);
super.addCorsMappings(registry);
}
/**
* 对静态资源的配置
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/*")
.addResourceLocations("classpath:/static/");
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* json返回中文乱码处理
*
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.serializationInclusion(JsonInclude.Include.NON_NULL);
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
return new ByteArrayHttpMessageConverter();
}
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
return new StringHttpMessageConverter();
}
@Bean
public ResourceHttpMessageConverter resourceHttpMessageConverter() {
return new ResourceHttpMessageConverter();
}
// @Bean
// public FilterRegistrationBean zhjfWebApplicationFilter() {
// FilterRegistrationBean frBean = new FilterRegistrationBean();
//// frBean.setFilter(new ZhjfWebApplicationFilter());
// frBean.addUrlPatterns("/*");
// frBean.addInitParameter("excludePaths","/css/**,/js/**,/druid/**,/swagger-resources,/v2/api-docs,/v2/api-docs-ext,/doc.html,/webjars/**");
// return frBean;
// }
}
| 37.53 | 148 | 0.687983 |
719fbf0bd2298573fad04203ee2925b0eb0420b3 | 513 | package unsch;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import unsch.Autor;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Autor autor = (Autor) applicationContext.getBean("autor");
autor.Imprimir();
((ClassPathXmlApplicationContext)applicationContext).close();
System.out.println(autor);
}
}
| 24.428571 | 91 | 0.779727 |
dce63a109b038b1c60ed70c8452d33ad10537674 | 798 | //,temp,ExpiredMessagesTest.java,378,385,temp,ExpiredMessagesTest.java,293,304
//,3
public class xxx {
@Override
public boolean isSatisified() throws Exception {
DestinationStatistics view = getDestinationStatistics(broker, destination);
LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: "
+ view.getEnqueues().getCount() + ", dequeues: "
+ view.getDequeues().getCount() + ", dispatched: "
+ view.getDispatched().getCount() + ", inflight: "
+ view.getInflight().getCount() + ", expiries: "
+ view.getExpired().getCount());
return view.getMessages().getCount() == 0;
}
}; | 46.941176 | 91 | 0.528822 |
a06f632e1fc53ff5e7b1b6beb67b5481a257b1e2 | 3,825 | /*
* Copyright 2017 FBK/CREATE-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 org.createnet.raptor.tree;
import org.createnet.raptor.common.dispatcher.RaptorMessageHandler;
import org.createnet.raptor.models.objects.Device;
import org.createnet.raptor.models.payload.ActionPayload;
import org.createnet.raptor.models.payload.DevicePayload;
import org.createnet.raptor.models.payload.DispatcherPayload;
import org.createnet.raptor.models.payload.StreamPayload;
import org.createnet.raptor.models.tree.TreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
/**
*
* @author Luca Capra <[email protected]>
*/
@Component
public class TreeMessageHandler implements RaptorMessageHandler {
final Logger log = LoggerFactory.getLogger(TreeMessageHandler.class);
@Autowired
TreeService treeService;
@Autowired
private TreeNodeEventPublisher treeNodePublisher;
@Override
public void handle(DispatcherPayload dispatcherPayload, MessageHeaders headers) {
switch (dispatcherPayload.getType()) {
// case tree:
// handleTreeNode((TreeNodePayload) dispatcherPayload);
// break;
case device:
handleDevice((DevicePayload) dispatcherPayload);
break;
case action:
handleAction((ActionPayload) dispatcherPayload);
break;
case stream:
handleStream((StreamPayload) dispatcherPayload);
break;
}
}
protected void handleAction(ActionPayload payload) {
Device device = payload.getDevice();
TreeNode node = treeService.get(device.getId());
if (node != null) {
notifyParent(node, payload);
}
}
protected void handleStream(StreamPayload payload) {
Device device = payload.getDevice();
TreeNode node = treeService.get(device.getId());
if (node != null) {
notifyParent(node, payload);
}
}
protected void handleDevice(DevicePayload payload) {
TreeNode node = treeService.get(payload.device.id());
if (node == null) {
log.debug("Cannot load node {}", payload.device.id());
return;
}
switch (payload.op) {
case delete:
log.debug("Drop node {}", payload.device.id());
treeService.delete(payload.device.id());
break;
case update:
log.debug("Update node {}", payload.device.id());
node.name(payload.device.name());
node = treeService.save(node);
break;
}
notifyParent(node, payload);
}
protected void notifyParent(TreeNode node, DispatcherPayload payload) {
TreeNode parents = treeService.parents(node);
TreeNode parent = parents.getParent();
while (parent != null) {
log.debug("Notifiyng {} ({})", parent.getId(), parent.path());
treeNodePublisher.notify(parent, payload);
parent = parent.getParent();
}
}
}
| 32.415254 | 85 | 0.644183 |
d17ca459936f51c864c67ba437203f09084864c1 | 2,659 | package com.sununiq.scaffold.controller;
import com.sununiq.scaffold.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @program: springboot-mybatis-scaffold
*
* @description: 请求参数绑定的几种方式
*
* spring对应请求方法参数的处理、响应返回值的处理对应两个接口分别是:
* HandlerMethodArgumentResolver和HandlerMethodReturnValueHandler
*
* 其中处理@RequestParam注解的是:{@link RequestParamMethodArgumentResolver}
* 处理对象作为请求参数的类是:{@link ServletModelAttributeMethodProcessor}
*
* @author: sununiq
*
* @create: 2018-08-25 21:18
**/
@Slf4j
@RestController
public class RequestParamDemo {
/**
* 请求url:/ssm/testRequestParam?name=tom&age=18
*/
@GetMapping("/testRequestParam")
public User testRequestParam(@RequestParam String name, @RequestParam Integer age,
@RequestParam(required = false, defaultValue = "unkonown") String desc) {
log.info("testRequestParam, name is:{}, age is:{}, desc is:{}", name, age, desc);
return User.builder().name(name).age(age).build();
}
/**
* 请求url:/ssm/testRequestParam?name=tom&age=18
* 与上面的区别是,无法对请求参数做个性化定制,比如如果没有传值可以设定默认值, 这种方式需要在controller自己去适配
* 这种方式的优点在于,多余3个请求参数的时候,会非常有用,提高代码的封装性和可维护性
*/
@GetMapping("/testRequestParamObject")
public User testRequestParamObject(User user) {
log.info("RequestParamObject test, {}", user);
return user;
}
/**
* 请求体,如果不注明请求的content-type,则需要在注解里面指明告诉框架怎么解析
* 响应也是同理
*/
@PostMapping("/requestBody")
public User testRequestBody(@RequestBody User user) {
log.info("RequestBody test, {}", user.toString());
return user;
}
/**
* 请求url:/ssm/testDate?2018-08-25
* 通过注解的方式指定date的格式
*/
@GetMapping("testDate")
public Date testDate(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
log.info("Request param self-defined date is:{}", date);
return date;
}
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
}
/**
* 请求的url:/ssm/testSelfDefined?2018-08-25
* 通过指定绑定的解析参数关系来解析
*/
@GetMapping("testSelfDefined")
public Date testDate2(Date date) {
log.info("Request param self-defined date is:{}", date);
return date;
}
}
| 28.902174 | 98 | 0.754795 |
c53adcb8f9f9960390b28804d074e3891b5b3b75 | 164 | import java.util.Arrays;
class A {
public void test() {
System.out.println(Arrays.asList("frst", <selection>"scnd", "third"</selection>, "4th"));
}
} | 23.428571 | 95 | 0.621951 |
b479432029f7fc623e7ea04ee89b03e1c7dca0f3 | 262 | package com.fangdd.doclet.test.service;
import com.fangdd.doclet.test.dto.User;
/**
* @author xuwenzhen
* @date 19/1/4
*/
public interface UserService {
/**
* 通过ID获取用户基本信息
*
* @param id 用户ID
* @return
*/
User get(int id);
}
| 14.555556 | 39 | 0.591603 |
2ffbfc2ecc327bafaf7be36433f27b642d888ff3 | 4,895 | package or.kosta.andro1218;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
public class Notidication extends AppCompatActivity {
private Button nofication_Start_Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notidication);
nofication_Start_Btn = (Button) findViewById(R.id.btn1);
nofication_Start_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Notification 알람은 반드시 알람창에 아이콘을 등록해야함
int n_icon = R.drawable.macclient;
// tickText 를 등록 : 알림창에 보여지는 메세지
CharSequence tikerText ="새로운 세일이 진행되었습니다";
// 알림창의 본문 내용
Context context = getApplicationContext();
CharSequence contentTitle = "빅세일 이벤트";
CharSequence contentText = "세일 이벤트가 있습니다. 연결해주세요";
// 인텐트 객체 생성
Intent intent = new Intent(context,Next_Page.class);
// 어떤 이벤트가 부여 되기 까지 기다려 주는 이벤트
// (백그라운드에서 대기)
// Notification이 실행이되고 내용을 사용자가
// Click했을 때 그때 실행 되는 인텐트 ******
//PendingIntent contentIntent =
// PendingIntent.getActivity(context, 0, intent, 0);
/*
* NotificationCompat.Builder
* Notification.Builder 는 안드로이드 3.0(API Level 11) 부터 추가가 되었다.
*이전 버전의 호환성을 제공하기 위해 support v4 내 NotificationCompat.Builder 를 사용한다.
* Notification 객체를 생성하기 위한 클래스.
* Notification 의 Layout 설정을 돕고 모든 flags 를 쉽게 제어할 수 있도록 한다.
* */
android.support.v4.app.NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(Notidication.this)
.setSmallIcon(R.drawable.macclient)
.setContentTitle("My Notification")
.setContentText("Hello World!");
/*
* TaskStackBuilder
* Cross-task navigation 을 위한 합성 back stack 을 생성하기 위한 유틸리티 클래스이다.
* 안드로이드 버전 3.0(허니콤, API Level 11) 부터 Back Key를 통한 App navigation 정책 변경 되었다.
* Back Key 동작은 현재 타스크 내에서만 동작하고, 다른 Task 를 가로지를 수 없다. task 들을 가로지르고
* 이전 타스크로 가기 위해서는 "Recents"를 통해야 한다.
* cross-task navigation 을 사용하기 위해서는 startActivities() 혹은 TaskStackBuilder.getPendingIntent() 를 통해 구현할 수 있다.
* Intent 를 생성한 뒤 TaskStackBuilder 객체에 추가한 후 이를 바탕으로 TaskStackPendingIntent 객체를 완성한다.
* Methods
- addNextIntent() : Add a new intent to the task stack (backstack 에 activity 들이 쌓임)
- addParentStack() : Add the activity parent chain as specified by manifest <meta-data> element to the task stack builder
(xml 에 명시된 parent activity 들이 찾아가면 chain 형식처럼 parent activity 가 없는 activity 를 만날때까지 추가 된다)
* Notification 을 클릭하여 특정 Activity 로 진입 한 후 Back Key 를 누를 경우 Home 화면으로 전환이 된다.
* 이때, Home 화면이 아닌 back stack 이 존재 하였던 것과 같이 동작을 원할 때 사용된다.
* Example : NotiResultActivity, NotiResultActivity1, NotiResultActivity2 가 존재하고 Noti 선택 시 NotiResultActivity2가 보여지고,
* Back Key 를 누를 때마다 NotiResultActivity1 -> NotiResultActivity -> Home 순으로 표현이 되길 원할 경우.
* 즉, Noti 를 클릭 하였을 때 NotiResultActivity -> NotiResultActivity1 -> NotiResultActivity2 순으로 backstack 이 구성되어진 경우.
* */
TaskStackBuilder stackBuilder = TaskStackBuilder.create(Notidication.this);
stackBuilder.addParentStack(Next_Page.class);
stackBuilder.addNextIntent(intent);
//Notification notification = new Notification(n_icon, tickerText, System.currentTimeMillis());
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(1, mBuilder.build());
}
});
}
}
| 48.95 | 140 | 0.59857 |
e31da5bacd0e84ce285ebc4de1fba0e5fde60777 | 19,392 | /*
* Copyright (c) 2017 NCIC, Institute of Computing Technology, Chinese Academy of Sciences
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.ncic.bioinfo.sparkseq.algorithms.walker.printreads;
import org.ncic.bioinfo.sparkseq.algorithms.utils.EventType;
import org.ncic.bioinfo.sparkseq.algorithms.utils.QualityUtils;
import org.ncic.bioinfo.sparkseq.algorithms.utils.RecalUtils;
import org.ncic.bioinfo.sparkseq.algorithms.data.basic.NestedIntegerArray;
import org.ncic.bioinfo.sparkseq.algorithms.data.basic.Pair;
import org.ncic.bioinfo.sparkseq.algorithms.utils.reports.GATKReport;
import org.ncic.bioinfo.sparkseq.algorithms.utils.reports.GATKReportTable;
import org.ncic.bioinfo.sparkseq.algorithms.walker.baserecalibrator.QuantizationInfo;
import org.ncic.bioinfo.sparkseq.algorithms.walker.baserecalibrator.RecalDatum;
import org.ncic.bioinfo.sparkseq.algorithms.walker.baserecalibrator.RecalibrationArgumentCollection;
import org.ncic.bioinfo.sparkseq.algorithms.walker.baserecalibrator.RecalibrationTables;
import org.ncic.bioinfo.sparkseq.algorithms.walker.baserecalibrator.covariate.Covariate;
import org.ncic.bioinfo.sparkseq.exceptions.ReviewedGATKException;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Author: wbc
*/
public class RecalibrationReport {
private QuantizationInfo quantizationInfo; // histogram containing the counts for qual quantization (calculated after recalibration is done)
private final RecalibrationTables recalibrationTables; // quick access reference to the tables
private final Covariate[] requestedCovariates; // list of all covariates to be used in this calculation
private final HashMap<String, Integer> optionalCovariateIndexes;
private final GATKReportTable argumentTable; // keep the argument table untouched just for output purposes
private final RecalibrationArgumentCollection RAC; // necessary for quantizing qualities with the same parameter
private final int[] tempRGarray = new int[2];
private final int[] tempQUALarray = new int[3];
private final int[] tempCOVarray = new int[4];
public RecalibrationReport(final GATKReport report) {
this(report, getReadGroups(report));
}
public RecalibrationReport(final GATKReport report, final SortedSet<String> allReadGroups) {
argumentTable = report.getTable(RecalUtils.ARGUMENT_REPORT_TABLE_TITLE);
RAC = initializeArgumentCollectionTable(argumentTable);
GATKReportTable quantizedTable = report.getTable(RecalUtils.QUANTIZED_REPORT_TABLE_TITLE);
quantizationInfo = initializeQuantizationTable(quantizedTable);
Pair<ArrayList<Covariate>, ArrayList<Covariate>> covariates = RecalUtils.initializeCovariates(RAC); // initialize the required and optional covariates
ArrayList<Covariate> requiredCovariates = covariates.getFirst();
ArrayList<Covariate> optionalCovariates = covariates.getSecond();
requestedCovariates = new Covariate[requiredCovariates.size() + optionalCovariates.size()];
optionalCovariateIndexes = new HashMap<String, Integer>(optionalCovariates.size());
int covariateIndex = 0;
for (final Covariate covariate : requiredCovariates)
requestedCovariates[covariateIndex++] = covariate;
for (final Covariate covariate : optionalCovariates) {
requestedCovariates[covariateIndex] = covariate;
final String covariateName = covariate.getClass().getSimpleName().split("Covariate")[0]; // get the name of the covariate (without the "covariate" part of it) so we can match with the GATKReport
optionalCovariateIndexes.put(covariateName, covariateIndex-2);
covariateIndex++;
}
for (Covariate cov : requestedCovariates)
cov.initialize(RAC); // initialize any covariate member variables using the shared argument collection
recalibrationTables = new RecalibrationTables(requestedCovariates, allReadGroups.size());
initializeReadGroupCovariates(allReadGroups);
parseReadGroupTable(report.getTable(RecalUtils.READGROUP_REPORT_TABLE_TITLE), recalibrationTables.getReadGroupTable());
parseQualityScoreTable(report.getTable(RecalUtils.QUALITY_SCORE_REPORT_TABLE_TITLE), recalibrationTables.getQualityScoreTable());
parseAllCovariatesTable(report.getTable(RecalUtils.ALL_COVARIATES_REPORT_TABLE_TITLE), recalibrationTables);
}
/**
* Gets the unique read groups in the table
*
* @param report the GATKReport containing the table with RecalUtils.READGROUP_REPORT_TABLE_TITLE
* @return the unique read groups
*/
private static SortedSet<String> getReadGroups(final GATKReport report) {
final GATKReportTable reportTable = report.getTable(RecalUtils.READGROUP_REPORT_TABLE_TITLE);
final SortedSet<String> readGroups = new TreeSet<String>();
for ( int i = 0; i < reportTable.getNumRows(); i++ )
readGroups.add(reportTable.get(i, RecalUtils.READGROUP_COLUMN_NAME).toString());
return readGroups;
}
/**
* Combines two recalibration reports by adding all observations and errors
*
* Note: This method DOES NOT recalculate the empirical qualities and quantized qualities. You have to recalculate
* them after combining. The reason for not calculating it is because this function is intended for combining a
* series of recalibration reports, and it only makes sense to calculate the empirical qualities and quantized
* qualities after all the recalibration reports have been combined. Having the user recalculate when appropriate,
* makes this method faster
*
* Note2: The empirical quality reported, however, is recalculated given its simplicity.
*
* @param other the recalibration report to combine with this one
*/
public void combine(final RecalibrationReport other) {
for ( int tableIndex = 0; tableIndex < recalibrationTables.numTables(); tableIndex++ ) {
final NestedIntegerArray<RecalDatum> myTable = recalibrationTables.getTable(tableIndex);
final NestedIntegerArray<RecalDatum> otherTable = other.recalibrationTables.getTable(tableIndex);
RecalUtils.combineTables(myTable, otherTable);
}
}
public QuantizationInfo getQuantizationInfo() {
return quantizationInfo;
}
public RecalibrationTables getRecalibrationTables() {
return recalibrationTables;
}
public Covariate[] getRequestedCovariates() {
return requestedCovariates;
}
/**
* Initialize read group keys using the shared list of all the read groups.
*
* By using the same sorted set of read groups across all recalibration reports, even if
* one report is missing a read group, all the reports use the same read group keys.
*
* @param allReadGroups The list of all possible read groups
*/
private void initializeReadGroupCovariates(final SortedSet<String> allReadGroups) {
for (String readGroup: allReadGroups) {
requestedCovariates[0].keyFromValue(readGroup);
}
}
/**
* Compiles the list of keys for the Covariates table and uses the shared parsing utility to produce the actual table
*
* @param reportTable the GATKReport table containing data for this table
* @param recalibrationTables the recalibration tables
\ */
private void parseAllCovariatesTable(final GATKReportTable reportTable, final RecalibrationTables recalibrationTables) {
for ( int i = 0; i < reportTable.getNumRows(); i++ ) {
final Object rg = reportTable.get(i, RecalUtils.READGROUP_COLUMN_NAME);
tempCOVarray[0] = requestedCovariates[0].keyFromValue(rg);
final Object qual = reportTable.get(i, RecalUtils.QUALITY_SCORE_COLUMN_NAME);
tempCOVarray[1] = requestedCovariates[1].keyFromValue(qual);
final String covName = (String)reportTable.get(i, RecalUtils.COVARIATE_NAME_COLUMN_NAME);
final int covIndex = optionalCovariateIndexes.get(covName);
final Object covValue = reportTable.get(i, RecalUtils.COVARIATE_VALUE_COLUMN_NAME);
tempCOVarray[2] = requestedCovariates[RecalibrationTables.TableType.OPTIONAL_COVARIATE_TABLES_START.ordinal() + covIndex].keyFromValue(covValue);
final EventType event = EventType.eventFrom((String)reportTable.get(i, RecalUtils.EVENT_TYPE_COLUMN_NAME));
tempCOVarray[3] = event.ordinal();
recalibrationTables.getTable(RecalibrationTables.TableType.OPTIONAL_COVARIATE_TABLES_START.ordinal() + covIndex).put(getRecalDatum(reportTable, i, false), tempCOVarray);
}
}
/**
*
* Compiles the list of keys for the QualityScore table and uses the shared parsing utility to produce the actual table
* @param reportTable the GATKReport table containing data for this table
* @param qualTable the map representing this table
*/
private void parseQualityScoreTable(final GATKReportTable reportTable, final NestedIntegerArray<RecalDatum> qualTable) {
for ( int i = 0; i < reportTable.getNumRows(); i++ ) {
final Object rg = reportTable.get(i, RecalUtils.READGROUP_COLUMN_NAME);
tempQUALarray[0] = requestedCovariates[0].keyFromValue(rg);
final Object qual = reportTable.get(i, RecalUtils.QUALITY_SCORE_COLUMN_NAME);
tempQUALarray[1] = requestedCovariates[1].keyFromValue(qual);
final EventType event = EventType.eventFrom((String)reportTable.get(i, RecalUtils.EVENT_TYPE_COLUMN_NAME));
tempQUALarray[2] = event.ordinal();
qualTable.put(getRecalDatum(reportTable, i, false), tempQUALarray);
}
}
/**
* Compiles the list of keys for the ReadGroup table and uses the shared parsing utility to produce the actual table
*
* @param reportTable the GATKReport table containing data for this table
* @param rgTable the map representing this table
*/
private void parseReadGroupTable(final GATKReportTable reportTable, final NestedIntegerArray<RecalDatum> rgTable) {
for ( int i = 0; i < reportTable.getNumRows(); i++ ) {
final Object rg = reportTable.get(i, RecalUtils.READGROUP_COLUMN_NAME);
tempRGarray[0] = requestedCovariates[0].keyFromValue(rg);
final EventType event = EventType.eventFrom((String)reportTable.get(i, RecalUtils.EVENT_TYPE_COLUMN_NAME));
tempRGarray[1] = event.ordinal();
rgTable.put(getRecalDatum(reportTable, i, true), tempRGarray);
}
}
private double asDouble(final Object o) {
if ( o instanceof Double )
return (Double)o;
else if ( o instanceof Integer )
return (Integer)o;
else if ( o instanceof Long )
return (Long)o;
else
throw new ReviewedGATKException("Object " + o + " is expected to be either a double, long or integer but it's not either: " + o.getClass());
}
private long asLong(final Object o) {
if ( o instanceof Long )
return (Long)o;
else if ( o instanceof Integer )
return ((Integer)o).longValue();
else if ( o instanceof Double )
return ((Double)o).longValue();
else
throw new ReviewedGATKException("Object " + o + " is expected to be a long but it's not: " + o.getClass());
}
private RecalDatum getRecalDatum(final GATKReportTable reportTable, final int row, final boolean hasEstimatedQReportedColumn) {
final long nObservations = asLong(reportTable.get(row, RecalUtils.NUMBER_OBSERVATIONS_COLUMN_NAME));
final double nErrors = asDouble(reportTable.get(row, RecalUtils.NUMBER_ERRORS_COLUMN_NAME));
//final double empiricalQuality = asDouble(reportTable.get(row, RecalUtils.EMPIRICAL_QUALITY_COLUMN_NAME));
// the estimatedQreported column only exists in the ReadGroup table
final double estimatedQReported = hasEstimatedQReportedColumn ?
(Double) reportTable.get(row, RecalUtils.ESTIMATED_Q_REPORTED_COLUMN_NAME) : // we get it if we are in the read group table
Byte.parseByte((String) reportTable.get(row, RecalUtils.QUALITY_SCORE_COLUMN_NAME)); // or we use the reported quality if we are in any other table
final RecalDatum datum = new RecalDatum(nObservations, nErrors, (byte)1);
datum.setEstimatedQReported(estimatedQReported);
//datum.setEmpiricalQuality(empiricalQuality); // don't set the value here because we will want to recompute with a different conditional Q score prior value
return datum;
}
/**
* Parses the quantization table from the GATK Report and turns it into a map of original => quantized quality scores
*
* @param table the GATKReportTable containing the quantization mappings
* @return an ArrayList with the quantization mappings from 0 to MAX_SAM_QUAL_SCORE
*/
private QuantizationInfo initializeQuantizationTable(GATKReportTable table) {
final Byte[] quals = new Byte[QualityUtils.MAX_SAM_QUAL_SCORE + 1];
final Long[] counts = new Long[QualityUtils.MAX_SAM_QUAL_SCORE + 1];
for ( int i = 0; i < table.getNumRows(); i++ ) {
final byte originalQual = (byte)i;
final Object quantizedObject = table.get(i, RecalUtils.QUANTIZED_VALUE_COLUMN_NAME);
final Object countObject = table.get(i, RecalUtils.QUANTIZED_COUNT_COLUMN_NAME);
final byte quantizedQual = Byte.parseByte(quantizedObject.toString());
final long quantizedCount = Long.parseLong(countObject.toString());
quals[originalQual] = quantizedQual;
counts[originalQual] = quantizedCount;
}
return new QuantizationInfo(Arrays.asList(quals), Arrays.asList(counts));
}
/**
* Parses the arguments table from the GATK Report and creates a RAC object with the proper initialization values
*
* @param table the GATKReportTable containing the arguments and its corresponding values
* @return a RAC object properly initialized with all the objects in the table
*/
private RecalibrationArgumentCollection initializeArgumentCollectionTable(GATKReportTable table) {
final RecalibrationArgumentCollection RAC = new RecalibrationArgumentCollection();
for ( int i = 0; i < table.getNumRows(); i++ ) {
final String argument = table.get(i, "Argument").toString();
Object value = table.get(i, RecalUtils.ARGUMENT_VALUE_COLUMN_NAME);
if (value.equals("null"))
value = null; // generic translation of null values that were printed out as strings | todo -- add this capability to the GATKReport
if (argument.equals("covariate") && value != null)
RAC.COVARIATES = value.toString().split(",");
else if (argument.equals("standard_covs"))
RAC.DO_NOT_USE_STANDARD_COVARIATES = Boolean.parseBoolean((String) value);
else if (argument.equals("solid_recal_mode"))
RAC.SOLID_RECAL_MODE = RecalUtils.SOLID_RECAL_MODE.recalModeFromString((String) value);
else if (argument.equals("solid_nocall_strategy"))
RAC.SOLID_NOCALL_STRATEGY = RecalUtils.SOLID_NOCALL_STRATEGY.nocallStrategyFromString((String) value);
else if (argument.equals("mismatches_context_size"))
RAC.MISMATCHES_CONTEXT_SIZE = Integer.parseInt((String) value);
else if (argument.equals("indels_context_size"))
RAC.INDELS_CONTEXT_SIZE = Integer.parseInt((String) value);
else if (argument.equals("mismatches_default_quality"))
RAC.MISMATCHES_DEFAULT_QUALITY = Byte.parseByte((String) value);
else if (argument.equals("insertions_default_quality"))
RAC.INSERTIONS_DEFAULT_QUALITY = Byte.parseByte((String) value);
else if (argument.equals("deletions_default_quality"))
RAC.DELETIONS_DEFAULT_QUALITY = Byte.parseByte((String) value);
else if (argument.equals("maximum_cycle_value"))
RAC.MAXIMUM_CYCLE_VALUE = Integer.parseInt((String) value);
else if (argument.equals("low_quality_tail"))
RAC.LOW_QUAL_TAIL = Byte.parseByte((String) value);
else if (argument.equals("default_platform"))
RAC.DEFAULT_PLATFORM = (String) value;
else if (argument.equals("force_platform"))
RAC.FORCE_PLATFORM = (String) value;
else if (argument.equals("quantizing_levels"))
RAC.QUANTIZING_LEVELS = Integer.parseInt((String) value);
else if (argument.equals("binary_tag_name"))
RAC.BINARY_TAG_NAME = (value == null) ? null : (String) value;
else if (argument.equals("sort_by_all_columns"))
RAC.SORT_BY_ALL_COLUMNS = Boolean.parseBoolean((String) value);
}
return RAC;
}
/**
* this functionality avoids recalculating the empirical qualities, estimated reported quality
* and quantization of the quality scores during every call of combine(). Very useful for the BQSRGatherer.
*/
public void calculateQuantizedQualities() {
quantizationInfo = new QuantizationInfo(recalibrationTables, RAC.QUANTIZING_LEVELS);
}
public GATKReport createGATKReport() {
return RecalUtils.getRecalibrationReport(this.RAC, this.quantizationInfo, this.recalibrationTables, this.requestedCovariates, this.RAC.SORT_BY_ALL_COLUMNS.booleanValue());
}
public RecalibrationArgumentCollection getRAC() {
return RAC;
}
/**
*
* @deprecated use {@link #getRequestedCovariates()} instead.
*/
@Deprecated
public Covariate[] getCovariates() {
return requestedCovariates;
}
/**
* @return true if the report has no data
*/
public boolean isEmpty() {
return recalibrationTables.isEmpty();
}
}
| 50.631854 | 206 | 0.708075 |
fcf82159e740190a59f35e790c372d224ea6e2c7 | 992 | package com.softicar.platform.workflow.module.workflow.management;
import com.softicar.platform.dom.elements.popup.DomPopup;
import com.softicar.platform.dom.refresh.bus.IDomRefreshBusEvent;
import com.softicar.platform.dom.refresh.bus.IDomRefreshBusListener;
import com.softicar.platform.workflow.module.WorkflowI18n;
import com.softicar.platform.workflow.module.workflow.version.AGWorkflowVersion;
public class WorkflowVersionManagementPopup extends DomPopup implements IDomRefreshBusListener {
private final AGWorkflowVersion workflowVersion;
public WorkflowVersionManagementPopup(AGWorkflowVersion workflowVersion) {
this.workflowVersion = workflowVersion;
setCaption(WorkflowI18n.MANAGE_WORKFLOW);
setSubCaption(workflowVersion.toDisplayWithoutId());
appendChild(new WorkflowVersionManagementDiv(workflowVersion));
}
@Override
public void refresh(IDomRefreshBusEvent event) {
removeChildren();
appendChild(new WorkflowVersionManagementDiv(workflowVersion));
}
}
| 35.428571 | 96 | 0.846774 |
08fe4645a5f2c378c3ff57736a027f02ff27ee66 | 5,347 | /**
* View for the category deletion window. This is just a small Yes, No window to confirm the deletion of an category.
*
* Copyright (c) 2020, Matthew Crabtree
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* @author Matthew Crabtree
*/
package delete_category;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import _main.AchieveSettings;
public final class DeleteCategoryView1 extends JFrame implements DeleteCategoryView {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Local stored settings
*/
private AchieveSettings settings;
private String category;
/**
* Controller object registered with this view to observe user-interaction
* events.
*/
private DeleteCategoryController controller;
/**
* Widgets
*/
private final JButton bYes, bNo;
private final JLabel lAsk;
/**
* Default constructor.
*/
public DeleteCategoryView1(AchieveSettings settings, String category) {
// Create the JFrame being extended
/*
* Call the JFrame (superclass) constructor with a String parameter to
* name the window in its title bar
*/
super("Delete Category: " + category + "?");
//Set local settings
this.settings = settings;
this.category = category;
// Set up the GUI widgets --------------------------------------------
/*
* Create widgets
*/
this.bYes = new JButton("Yes");
this.bNo = new JButton("No");
this.lAsk = new JLabel("Are you sure you want to delete: " + category + "?");
// Set up the GUI widgets --------------------------------------------
/*
* Create main button panel
*/
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setBorder(new EmptyBorder(10,10,10,10));
GridBagConstraints mainConstraints = new GridBagConstraints();
mainConstraints.weightx = 1;
mainConstraints.insets = new Insets(3,3,3,3);
mainConstraints.fill = GridBagConstraints.HORIZONTAL;
/*
* Add the buttons to the main button panel, from left to right and top
* to bottom
*/
mainConstraints.gridwidth = 2;
mainPanel.add(this.lAsk, mainConstraints);
mainConstraints.gridy = 1;
mainConstraints.gridwidth = 1;
mainPanel.add(this.bYes, mainConstraints);
mainConstraints.gridx = 1;
mainPanel.add(this.bNo, mainConstraints);
/*
* Add scroll panes and button panel to main window, from left to right
* and top to bottom
*/
this.add(mainPanel);
// Set up the observers ----------------------------------------------
/*
* Register this object as the observer for all GUI events
*/
this.bYes.addActionListener(this);
this.bNo.addActionListener(this);
// Set up the main application window --------------------------------
/*
* Make sure the main window is appropriately sized, centered, exits this program
* on close, and becomes visible to the user
*/
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
this.pack();
}
@Override
public void registerObserver(DeleteCategoryController controller) {
this.controller = controller;
}
public void closeWindow() {
this.dispose();
}
@Override
public void actionPerformed(ActionEvent event) {
/*
* Set cursor to indicate computation on-going; this matters only if
* processing the event might take a noticeable amount of time as seen
* by the user
*/
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
/*
* Determine which event has occurred that we are being notified of by
* this callback; in this case, the source of the event (i.e, the widget
* calling actionPerformed) is all we need because only buttons are
* involved here, so the event must be a button press; in each case,
* tell the controller to do whatever is needed to update the model and
* to refresh the view
*/
Object source = event.getSource();
if (source == this.bYes) {
this.controller.processYesEvent(this.settings, this.category);
} else {
this.controller.processNoEvent();
}
/*
* Set the cursor back to normal (because we changed it at the beginning
* of the method body)
*/
this.setCursor(Cursor.getDefaultCursor());
}
}
| 30.039326 | 117 | 0.610623 |
66da317508c8237bc7c0a8497fa97dc531ab9891 | 2,397 | /*
* The MIT License
*
* Copyright 2014 Cimport java.io.IOException;
import java.util.List;
import org.sa.rainbow.core.ports.eseb.ESEBProvider;
import org.sa.rainbow.translator.effectors.IEffectorIdentifier;
import edu.cmu.cs.able.eseb.participant.ParticipantException;
ut limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.sa.rainbow.core.ports.eseb.rpc;
import edu.cmu.cs.able.eseb.participant.ParticipantException;
import edu.cmu.cs.able.eseb.rpc.OperationTimedOutException;
import org.sa.rainbow.core.ports.eseb.ESEBProvider;
import org.sa.rainbow.translator.effectors.IEffectorIdentifier;
import java.io.IOException;
import java.util.List;
public class ESEBEffectorExecutionRequirerPort extends AbstractESEBDisposableRPCPort implements
IESEBEffectorExecutionRemoteInterface {
private IESEBEffectorExecutionRemoteInterface m_stub;
public ESEBEffectorExecutionRequirerPort (IEffectorIdentifier effector) throws IOException, ParticipantException {
super (ESEBProvider.getESEBClientHost (), ESEBProvider.getESEBClientPort (),
effector.id ());
m_stub = getConnectionRole().createRemoteStub (IESEBEffectorExecutionRemoteInterface.class,
effector.id () + IESEBEffectorExecutionRemoteInterface.class.getSimpleName ());
}
@Override
public Outcome execute (List<String> args) {
try {
return m_stub.execute (args);
}
catch (OperationTimedOutException e) {
return Outcome.TIMEOUT;
}
}
}
| 39.95 | 119 | 0.740509 |
eba071771442cd16d073326ffa6b6a83ce04d98b | 2,500 | package seedu.flashcard.storage;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import seedu.flashcard.commons.exceptions.IllegalValueException;
import seedu.flashcard.model.FlashcardList;
import seedu.flashcard.model.ReadOnlyFlashcardList;
import seedu.flashcard.model.flashcard.Flashcard;
/**
* An Immutable FlashcardList that is serializable to JSON format.
*/
@JsonRootName(value = "flashcardlist")
public class JsonSerializableFlashcardList {
public static final String MESSAGE_DUPLICATE_FLASHCARD = "Flashcards list contains duplicate persons";
public static final String MESSAGE_ILLEGAL_FLASHCARD = "The Json file provided an illegal flashcard";
private final List<JsonAdaptedFlashcard> flashcards = new ArrayList<>();
/**
* Constructs a {@code JsonSerializableFlashcardList} with the given flashcards.
*/
@JsonCreator
public JsonSerializableFlashcardList(@JsonProperty("flashcards") List<JsonAdaptedFlashcard> flashcards) {
this.flashcards.addAll(flashcards);
}
/**
* Converts a given {@code ReadOnlyFlashcardList} into this class for Jackson use.
* @param source future changes to this will not affect the created {@code JsonSerializableFlashcardList}.
*/
public JsonSerializableFlashcardList(ReadOnlyFlashcardList source) {
flashcards.addAll(source.getFlashcardList().stream()
.map(JsonAdaptedFlashcard::new).collect(Collectors.toList()));
}
/**
* Converts this flashcard list into the model's {@code FlashcardList} object.
* @throws IllegalValueException if there were any data constraints violated.
*/
public FlashcardList toModelType() throws IllegalValueException {
FlashcardList flashcardList = new FlashcardList();
for (JsonAdaptedFlashcard jsonAdaptedFlashcard : flashcards) {
Flashcard flashcard = jsonAdaptedFlashcard.toModelType();
if (!flashcard.isValidFlashcard()) {
throw new IllegalValueException(MESSAGE_ILLEGAL_FLASHCARD);
}
if (flashcardList.hasFlashcard(flashcard)) {
throw new IllegalValueException(MESSAGE_DUPLICATE_FLASHCARD);
}
flashcardList.addFlashcard(flashcard);
}
return flashcardList;
}
}
| 39.0625 | 110 | 0.734 |
d9b36d962cdea7b7ce177d02e3461b5526f69657 | 158 | package messenger.external;
public class FightEndEvent extends Event {
@Override
public String getName() {
return "Fight End Event";
}
}
| 17.555556 | 42 | 0.670886 |
764bb128f63cda3aa755d86749c861ee526cb233 | 5,104 | /*
* 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.isis.applib.services.user;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.isis.applib.services.iactn.ExecutionContext;
import org.apache.isis.applib.services.sudo.SudoService;
import org.apache.isis.commons.internal.exceptions._Exceptions;
/**
* Allows the domain object to obtain the identity of the user interacting with
* said object.
*
* <p>
* If {@link SudoService} has been used to temporarily override the user and/or
* roles, then this service will report the overridden values instead.
* </p>
*
* @since 1.x revised in 2.0 {@index}
*/
public interface UserService {
// -- INTERFACE
/**
* Optionally gets the details about the current user,
* based on whether an {@link ExecutionContext} can be found with the current thread's context.
*/
Optional<UserMemento> currentUser();
/**
* Gets the details about the current user.
* @apiNote for backward compatibility
*/
@Nullable
default UserMemento getUser() {
return currentUser().orElse(null);
}
/**
* Gets the details about the current user.
* @throws IllegalStateException if no {@link ExecutionContext} can be found with the current thread's context.
*/
default UserMemento currentUserElseFail() {
return currentUser()
.orElseThrow(()->_Exceptions.illegalState("Current thread has no ExecutionContext."));
}
/**
* Optionally gets the the current user's name,
* based on whether an {@link ExecutionContext} can be found with the current thread's context.
*/
default Optional<String> currentUserName() {
return currentUser()
.map(UserMemento::getName);
}
/**
* Returns either the current user's name or else {@literal Nobody}.
*/
default String currentUserNameElseNobody() {
return currentUserName()
.orElse("Nobody");
}
/**
* Allows implementations to override the current user with another user.
*
* <p>
* This is intended for non-production environments only, where it can
* be invaluable (from a support perspective) to be able to quickly
* use the application "as if" logged in as another user.
* </p>
*
* @see #supportsImpersonation()
* @see #getImpersonatedUser()
* @see #isImpersonating()
* @see #stopImpersonating()
*
* @param userName
* @param roles
*/
default void impersonateUser(final String userName, final List<String> roles) {
throw new RuntimeException("Not implemented");
}
/**
* For implementations that support impersonation, this is to
* programmatically stop impersonating a user
*
* <p>
* Intended to be called at some point after
* {@link #impersonateUser(String, List)} would have been called.
* </p>
*
* @see #supportsImpersonation()
* @see #impersonateUser(String, List)
* @see #getImpersonatedUser()
* @see #isImpersonating()
*/
default void stopImpersonating() {
throw new RuntimeException("Not implemented");
}
/**
* Whether this implementation supports impersonation.
*
* @see #impersonateUser(String, List)
* @see #getImpersonatedUser()
* @see #isImpersonating()
* @see #stopImpersonating()
*/
default boolean supportsImpersonation() {
return false;
}
/**
* The impersonated user, if it has previously been set.
*
* @see #supportsImpersonation()
* @see #impersonateUser(String, List)
* @see #isImpersonating()
* @see #stopImpersonating()
*/
default Optional<UserMemento> getImpersonatedUser() {
return Optional.empty();
}
/**
* Whether or not the user currently reported (in {@link #currentUser()}
* and similar) is actually an impersonated user.
*
* @see #currentUser()
* @see #supportsImpersonation()
* @see #impersonateUser(String, List)
* @see #getImpersonatedUser()
* @see #stopImpersonating()
*/
default boolean isImpersonating() {
return getImpersonatedUser().isPresent();
}
}
| 30.746988 | 115 | 0.654781 |
934e767d2b15163077bf884ca4b612e48b0dbd46 | 2,282 | package com.pixy;
public class PixyCamera {
PixyCamera() {}
public void setAutoWhiteBalanceEnabled(boolean enabled) {
int result = PixyJni.camSetAutoWhiteBalance(enabled);
PixyResult.throwIfError(result);
}
public boolean isAutoWhiteBalanceEnabled() {
int result = PixyJni.camGetAutoWhiteBalance();
PixyResult.throwIfError(result);
return result == 1;
}
public Color getWhiteBalance() {
long result = PixyJni.camGetWhiteBalanceValue();
PixyResult.throwIfError((int) result);
int red = (int) ((result >> 8) & 0xff);
int green = (int) (result & 0xff);
int blue = (int) ((result >> 16) & 0xff);
return new Color(red, green, blue);
}
public void setWhiteBalance(Color whiteBalance) {
int result = PixyJni.camSetWhiteBalanceValue(whiteBalance.getRed(),
whiteBalance.getGreen(), whiteBalance.getBlue());
PixyResult.throwIfError(result);
}
public void setAutoExposureCompensationEnabled(boolean enabled) {
int result = PixyJni.camSetAutoExposureCompensation(enabled);
PixyResult.throwIfError(result);
}
public boolean isAutoExposureCompensationEnabled() {
int result = PixyJni.camGetAutoExposureCompensation();
PixyResult.throwIfError(result);
return result == 1;
}
public void setExposureCompensation(ExposureCompensation exposureCompensation) {
int result = PixyJni.camSetExposureCompensation(exposureCompensation.getGain(),
exposureCompensation.getCompensation());
PixyResult.throwIfError(result);
}
public ExposureCompensation getExposureCompensation() {
int result = PixyJni.camGetExposureCompensation();
PixyResult.throwIfError(result);
int gain = result & 0xff;
int compensation = (result >> 8) & 0xffff;
return new ExposureCompensation(gain, compensation);
}
public void setBrightness(int brightness) {
int result = PixyJni.camSetBrightness(brightness);
PixyResult.throwIfError(result);
}
public int getBrightness() {
int result = PixyJni.camGetBrightness();
PixyResult.throwIfError(result);
return result;
}
}
| 32.140845 | 87 | 0.667397 |
9f3f9e204eb1b25fa5ecfb96c5a79f6b4ea82554 | 1,814 | package com.ctrip.zeus.dao.mapper;
import com.ctrip.zeus.dao.entity.SlbVsDomainR;
import com.ctrip.zeus.dao.entity.SlbVsDomainRExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SlbVsDomainRMapper {
long countByExample(SlbVsDomainRExample example);
int deleteByExample(SlbVsDomainRExample example);
int deleteByPrimaryKey(Long id);
int insert(SlbVsDomainR record);
int insertSelective(SlbVsDomainR record);
SlbVsDomainR selectOneByExample(SlbVsDomainRExample example);
SlbVsDomainR selectOneByExampleSelective(@Param("example") SlbVsDomainRExample example, @Param("selective") SlbVsDomainR.Column ... selective);
List<SlbVsDomainR> selectByExampleSelective(@Param("example") SlbVsDomainRExample example, @Param("selective") SlbVsDomainR.Column ... selective);
List<SlbVsDomainR> selectByExample(SlbVsDomainRExample example);
SlbVsDomainR selectByPrimaryKeySelective(@Param("id") Long id, @Param("selective") SlbVsDomainR.Column ... selective);
SlbVsDomainR selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") SlbVsDomainR record, @Param("example") SlbVsDomainRExample example);
int updateByExample(@Param("record") SlbVsDomainR record, @Param("example") SlbVsDomainRExample example);
int updateByPrimaryKeySelective(SlbVsDomainR record);
int updateByPrimaryKey(SlbVsDomainR record);
int upsert(SlbVsDomainR record);
int upsertSelective(SlbVsDomainR record);
/*Self defined*/
int batchUpdate(List<SlbVsDomainR> records);
int batchInsert(List<SlbVsDomainR> records);
int batchDelete(List<SlbVsDomainR> records);
int batchInsertIncludeId(List<SlbVsDomainR> records);
/*Self defined*/
} | 34.226415 | 151 | 0.753032 |
1a95fa3b60fa6301e5f7dc03284be21b377a221f | 20,591 | /*
* MIT License
*
* Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.openscience.sherlock.dbservice.dataset.controller;
import casekit.nmr.analysis.MultiplicitySectionsBuilder;
import casekit.nmr.dbservice.COCONUT;
import casekit.nmr.dbservice.NMRShiftDB;
import casekit.nmr.model.DataSet;
import casekit.nmr.model.Spectrum;
import casekit.nmr.similarity.Similarity;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.fingerprint.BitSetFingerprint;
import org.openscience.sherlock.dbservice.dataset.db.model.DataSetRecord;
import org.openscience.sherlock.dbservice.dataset.db.model.MultiplicitySectionsSettingsRecord;
import org.openscience.sherlock.dbservice.dataset.db.service.DataSetServiceImplementation;
import org.openscience.sherlock.dbservice.dataset.db.service.MultiplicitySectionsSettingsServiceImplementation;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.FileNotFoundException;
import java.util.*;
@RestController
@RequestMapping(value = "/")
public class DatabaseController {
private final DataSetServiceImplementation dataSetServiceImplementation;
private final MultiplicitySectionsSettingsServiceImplementation multiplicitySectionsSettingsServiceImplementation;
private final String pathToNMRShiftDB = "/data/nmrshiftdb/nmrshiftdb.sdf";
private final String[] pathsToCOCONUT = new String[]{"/data/coconut/acd_coconut_1.sdf",
"/data/coconut/acd_coconut_2.sdf",
"/data/coconut/acd_coconut_3.sdf",
"/data/coconut/acd_coconut_4.sdf",
"/data/coconut/acd_coconut_5.sdf",
"/data/coconut/acd_coconut_6.sdf",
"/data/coconut/acd_coconut_7.sdf",
"/data/coconut/acd_coconut_8.sdf",
"/data/coconut/acd_coconut_9.sdf",
"/data/coconut/acd_coconut_10.sdf",
"/data/coconut/acd_coconut_11.sdf",
"/data/coconut/acd_coconut_12.sdf",
"/data/coconut/acd_coconut_13.sdf",
"/data/coconut/acd_coconut_14.sdf",
"/data/coconut/acd_coconut_15.sdf",
"/data/coconut/acd_coconut_16.sdf",
"/data/coconut/acd_coconut_17.sdf",
"/data/coconut/acd_coconut_18.sdf"};
private final MultiplicitySectionsBuilder multiplicitySectionsBuilder = new MultiplicitySectionsBuilder();
private final Map<String, int[]> multiplicitySectionsSettings = new HashMap<>();
public DatabaseController(final DataSetServiceImplementation dataSetServiceImplementation,
final MultiplicitySectionsSettingsServiceImplementation multiplicitySectionsSettingsServiceImplementation) {
this.dataSetServiceImplementation = dataSetServiceImplementation;
this.multiplicitySectionsSettingsServiceImplementation = multiplicitySectionsSettingsServiceImplementation;
}
@GetMapping(value = "/count")
public Mono<Long> getCount() {
return this.dataSetServiceImplementation.count();
}
@GetMapping(value = "/getById", produces = "application/json")
public Mono<DataSetRecord> getById(@RequestParam final String id) {
return this.dataSetServiceImplementation.findById(id);
}
@GetMapping(value = "/getAll", produces = "application/stream+json")
public Flux<DataSetRecord> getAll() {
return this.dataSetServiceImplementation.findAll();
}
@GetMapping(value = "/getByMf", produces = "application/stream+json")
public Flux<DataSetRecord> getByMf(@RequestParam final String mf) {
return this.dataSetServiceImplementation.findByMf(mf);
}
@GetMapping(value = "/getByNuclei", produces = "application/stream+json")
public Flux<DataSetRecord> getByDataSetSpectrumNuclei(@RequestParam final String[] nuclei) {
return this.dataSetServiceImplementation.findByDataSetSpectrumNuclei(nuclei);
}
@GetMapping(value = "/getByNucleiAndSignalCount", produces = "application/stream+json")
public Flux<DataSetRecord> getByDataSetSpectrumNucleiAndDataSetSpectrumSignalCount(
@RequestParam final String[] nuclei, @RequestParam final int signalCount) {
return this.dataSetServiceImplementation.findByDataSetSpectrumNucleiAndDataSetSpectrumSignalCount(nuclei,
signalCount);
}
@GetMapping(value = "/getByNucleiAndSignalCountAndMf", produces = "application/stream+json")
public Flux<DataSetRecord> getByDataSetSpectrumNucleiAndDataSetSpectrumSignalCountAndMf(
@RequestParam final String[] nuclei, @RequestParam final int signalCount, @RequestParam final String mf) {
return this.dataSetServiceImplementation.findByDataSetSpectrumNucleiAndDataSetSpectrumSignalCountAndMf(nuclei,
signalCount,
mf);
}
@PostMapping(value = "/insert", consumes = "application/json")
public Mono<DataSetRecord> insert(@RequestBody final DataSetRecord dataSetRecord) {
return this.dataSetServiceImplementation.insert(dataSetRecord);
}
@DeleteMapping(value = "/deleteAll")
public Mono<Void> deleteAll() {
return this.dataSetServiceImplementation.deleteAll();
}
@PostMapping(value = "/replaceAll")
public void replaceAll(@RequestParam final String[] nuclei, @RequestParam final boolean setLimits) {
this.deleteAll()
.block();
// detect bitset ranges and store in DB
List<DataSet> dataSetList;
if (setLimits) {
try {
dataSetList = NMRShiftDB.getDataSetsFromNMRShiftDB(this.pathToNMRShiftDB, nuclei);
Map<String, Integer[]> limits = this.setMinLimitAndMaxLimitOfMultiplicitySectionsBuilder(dataSetList,
new HashMap<>());
System.out.println("dataset size NMRShiftDB -> "
+ dataSetList.size());
System.out.println("limits NMRShiftDB: "
+ Arrays.toString(limits.get("13C")));
for (int i = 0; i
< this.pathsToCOCONUT.length; i++) {
System.out.println(" -> COCONUT "
+ i
+ " -> "
+ this.pathsToCOCONUT[i]);
dataSetList = COCONUT.getDataSetsWithShiftPredictionFromCOCONUT(this.pathsToCOCONUT[i], nuclei);
System.out.println("dataset size COCONUT "
+ i
+ " -> "
+ dataSetList.size());
limits = this.setMinLimitAndMaxLimitOfMultiplicitySectionsBuilder(dataSetList, limits);
System.out.println("limits COCONUT "
+ i
+ ": "
+ Arrays.toString(limits.get("13C")));
}
} catch (final FileNotFoundException | CDKException e) {
e.printStackTrace();
}
} else {
MultiplicitySectionsSettingsRecord multiplicitySectionsSettingsRecord;
for (final String nucleus : nuclei) {
multiplicitySectionsSettingsRecord = this.multiplicitySectionsSettingsServiceImplementation.findByNucleus(
nucleus)
.block();
this.multiplicitySectionsSettings.put(multiplicitySectionsSettingsRecord.getNucleus(),
multiplicitySectionsSettingsRecord.getMultiplicitySectionsSettings());
}
}
// store datasets in DB
// with checks whether a dataset with identical spectrum already exists
try {
dataSetList = NMRShiftDB.getDataSetsFromNMRShiftDB(this.pathToNMRShiftDB, nuclei);
System.out.println("dataset size NMRShiftDB -> "
+ dataSetList.size());
this.filterAndInsertDataSetRecords(dataSetList, new HashMap<>());
System.out.println("stored for NMRShiftDB done -> "
+ this.getCount()
.block());
final Map<String, Map<String, List<Spectrum>>> inserted = new HashMap<>(); // molecule id -> nucleus -> spectra list
Flux.fromArray(this.pathsToCOCONUT)
.doOnNext(pathToCOCONUT -> {
try {
System.out.println("storing -> "
+ pathToCOCONUT);
this.filterAndInsertDataSetRecords(
COCONUT.getDataSetsWithShiftPredictionFromCOCONUT(pathToCOCONUT, nuclei), inserted);
System.out.println(pathToCOCONUT
+ " -> done -> "
+ this.getCount()
.block());
} catch (final CDKException | FileNotFoundException e) {
e.printStackTrace();
}
})
.subscribe();
} catch (final FileNotFoundException | CDKException e) {
e.printStackTrace();
}
}
private void filterAndInsertDataSetRecords(final List<DataSet> dataSetList,
final Map<String, Map<String, List<Spectrum>>> insertedMap) {
String id, nucleus;
Spectrum spectrum;
Double averageDeviation;
final Set<String> insertedKeys = new HashSet<>();
for (final DataSet dataSet : new ArrayList<>(dataSetList)) {
id = dataSet.getMeta()
.get("id");
if (id
== null) {
continue;
}
spectrum = dataSet.getSpectrum()
.toSpectrum();
nucleus = spectrum.getNuclei()[0];
insertedMap.putIfAbsent(id, new HashMap<>());
insertedMap.get(id)
.putIfAbsent(nucleus, new ArrayList<>());
if (insertedMap.get(id)
.get(nucleus)
.isEmpty()) {
insertedMap.get(id)
.get(nucleus)
.add(spectrum);
insertedKeys.add(id);
continue;
}
for (final Spectrum insertedSpectrum : new ArrayList<>(insertedMap.get(id)
.get(nucleus))) {
averageDeviation = Similarity.calculateAverageDeviation(insertedSpectrum, spectrum, 0, 0, 0.0, true,
true, false);
if (averageDeviation
!= null
&& averageDeviation
== 0.0) {
dataSetList.remove(dataSet);
} else {
insertedMap.get(id)
.get(nucleus)
.add(spectrum);
insertedKeys.add(id);
break;
}
}
}
// we here assume that each spectrum of the same compound should appear in one row
// so we keep the keys from this insertion for next time to know the last inserted keys and check it
for (final String insertedMapKey : new HashSet<>(insertedMap.keySet())) {
if (!insertedKeys.contains(insertedMapKey)) {
insertedMap.remove(insertedMapKey);
}
}
this.dataSetServiceImplementation.insertMany(Flux.fromIterable(dataSetList)
.map(dataSet -> {
final String nucleusTemp = dataSet.getSpectrum()
.getNuclei()[0];
final MultiplicitySectionsBuilder multiplicitySectionsBuilder = new MultiplicitySectionsBuilder();
multiplicitySectionsBuilder.setMinLimit(
this.multiplicitySectionsSettings.get(
nucleusTemp)[0]);
multiplicitySectionsBuilder.setMaxLimit(
this.multiplicitySectionsSettings.get(
nucleusTemp)[1]);
multiplicitySectionsBuilder.setStepSize(
this.multiplicitySectionsSettings.get(
nucleusTemp)[2]);
final BitSetFingerprint bitSetFingerprint = Similarity.getBitSetFingerprint(
dataSet.getSpectrum()
.toSpectrum(), 0,
multiplicitySectionsBuilder);
final String setBitsString = Arrays.toString(
bitSetFingerprint.getSetbits());
dataSet.addMetaInfo("fpSize", String.valueOf(
bitSetFingerprint.size()));
dataSet.addMetaInfo("setBits", setBitsString);
return new DataSetRecord(null, dataSet);
}))
.subscribe();
}
@GetMapping(value = "/getMultiplicitySectionsSettings", produces = "application/json")
public Map<String, int[]> getMultiplicitySectionsSettings() {
final List<MultiplicitySectionsSettingsRecord> multiplicitySectionsSettingsRecordList = this.multiplicitySectionsSettingsServiceImplementation.findAll()
.collectList()
.block();
if (multiplicitySectionsSettingsRecordList
!= null) {
for (final MultiplicitySectionsSettingsRecord multiplicitySectionsSettingsRecord : multiplicitySectionsSettingsRecordList) {
this.multiplicitySectionsSettings.put(multiplicitySectionsSettingsRecord.getNucleus(),
multiplicitySectionsSettingsRecord.getMultiplicitySectionsSettings());
}
}
return this.multiplicitySectionsSettings;
}
private Map<String, Integer[]> setMinLimitAndMaxLimitOfMultiplicitySectionsBuilder(final List<DataSet> dataSetList,
final Map<String, Integer[]> prevLimits) {
final Map<String, Integer> stepSizes = new HashMap<>();
stepSizes.put("13C", 5);
stepSizes.put("15N", 10);
stepSizes.put("1H", 1);
final Map<String, Integer[]> limits = new HashMap<>(prevLimits); // min/max limit per nucleus
String nucleus;
Double tempMin, tempMax;
Spectrum spectrum;
for (final DataSet dataSet : dataSetList) {
spectrum = dataSet.getSpectrum()
.toSpectrum();
nucleus = spectrum.getNuclei()[0];
limits.putIfAbsent(nucleus, new Integer[]{null, null});
tempMin = Collections.min(spectrum.getShifts(0));
tempMax = Collections.max(spectrum.getShifts(0));
if (limits.get(nucleus)[0]
== null
|| tempMin
< limits.get(nucleus)[0]) {
limits.get(nucleus)[0] = tempMin.intValue();
}
if (limits.get(nucleus)[1]
== null
|| tempMax
> limits.get(nucleus)[1]) {
limits.get(nucleus)[1] = tempMax.intValue();
}
}
// delete previously stored multiplicity sections settings
this.multiplicitySectionsSettingsServiceImplementation.deleteAll()
.block();
int[] settings;
for (final Map.Entry<String, Integer[]> entry : limits.entrySet()) {
nucleus = entry.getKey();
settings = new int[3];
settings[0] = limits.get(nucleus)[0]
- stepSizes.get(nucleus); // extend by one more step
settings[1] = limits.get(nucleus)[1]
// extend by one more step
+ stepSizes.get(nucleus);
settings[2] = stepSizes.get(nucleus);
this.multiplicitySectionsSettings.put(nucleus, settings);
this.multiplicitySectionsSettingsServiceImplementation.insert(
new MultiplicitySectionsSettingsRecord(null, nucleus, settings))
.block();
}
return limits;
}
}
| 56.413699 | 164 | 0.5093 |
7edd571f421fb04e995da45f38fb2c3527daf529 | 295 | package com.grg.security.common.properties;
import lombok.Data;
/**
* qq登录配置项
* @author tjshan
* @date 2019-7-22 22:10
*/
@Data
public class QQProperties {
private String appId;
private String appSecret;
/**
* providerId
*/
private String providerId = "qq";
}
| 13.409091 | 43 | 0.640678 |
492580a5b2b028eeb0ec4a8c0cf6e3514e14c57e | 463 | package com.fount4j.security.csrf;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class CsrfToken {
public static final String ATTRIBUTE_NAME = "_csrf";
public static final String HEADER_META_NAME = "_csrf_header";
public static final String DEFAULT_HEADER_NAME = "X-CSRF-TOKEN";
private final String token;
private final long expireTime;
private final String headerName;
private final String parameterName;
}
| 25.722222 | 68 | 0.760259 |
fe7324c7057c821eb99e01ac5360442c5aeb841f | 544 | package org.smartregister.eusm.presenter;
import org.smartregister.view.contract.BaseRegisterFragmentContract;
public class BaseRegisterFragmentPresenter implements BaseRegisterFragmentContract.Presenter {
@Override
public void processViewConfigurations() {
//do nothing
}
@Override
public void initializeQueries(String s) {
//do nothing
}
@Override
public void startSync() {
//do nothing
}
@Override
public void searchGlobally(String s) {
//do nothing
}
}
| 19.428571 | 94 | 0.683824 |
76f21532ae80a370ca02ef1d389efdf2d68717d4 | 11,379 | package com.google.cloud.storage;
import com.google.cloud.storage.spi.v1.*;
import java.util.concurrent.*;
import com.google.api.gax.retrying.*;
import com.google.cloud.*;
import java.io.*;
import java.util.*;
import com.google.common.base.*;
public class CopyWriter implements Restorable<CopyWriter>
{
private final StorageOptions serviceOptions;
private final StorageRpc storageRpc;
private StorageRpc.RewriteResponse rewriteResponse;
CopyWriter(final StorageOptions a1, final StorageRpc.RewriteResponse a2) {
super();
this.serviceOptions = a1;
this.rewriteResponse = a2;
this.storageRpc = a1.getStorageRpcV1();
}
public Blob getResult() {
while (!this.isDone()) {
this.copyChunk();
}
return Blob.fromPb((Storage)this.serviceOptions.getService(), this.rewriteResponse.result);
}
public long getBlobSize() {
return this.rewriteResponse.blobSize;
}
public boolean isDone() {
return this.rewriteResponse.isDone;
}
public long getTotalBytesCopied() {
return this.rewriteResponse.totalBytesRewritten;
}
public void copyChunk() {
if (!this.isDone()) {
try {
this.rewriteResponse = (StorageRpc.RewriteResponse)RetryHelper.runWithRetries((Callable)new Callable<StorageRpc.RewriteResponse>() {
final /* synthetic */ CopyWriter this$0;
CopyWriter$1() {
this.this$0 = a1;
super();
}
@Override
public StorageRpc.RewriteResponse call() {
return this.this$0.storageRpc.continueRewrite(this.this$0.rewriteResponse);
}
@Override
public /* bridge */ Object call() throws Exception {
return this.call();
}
}, this.serviceOptions.getRetrySettings(), (ResultRetryAlgorithm)StorageImpl.EXCEPTION_HANDLER, this.serviceOptions.getClock());
}
catch (RetryHelper.RetryHelperException v1) {
throw StorageException.translateAndThrow(v1);
}
}
}
public RestorableState<CopyWriter> capture() {
return StateImpl.newBuilder(this.serviceOptions, BlobId.fromPb(this.rewriteResponse.rewriteRequest.source), this.rewriteResponse.rewriteRequest.sourceOptions, this.rewriteResponse.rewriteRequest.overrideInfo, BlobInfo.fromPb(this.rewriteResponse.rewriteRequest.target), this.rewriteResponse.rewriteRequest.targetOptions).setResult((this.rewriteResponse.result != null) ? BlobInfo.fromPb(this.rewriteResponse.result) : null).setBlobSize(this.getBlobSize()).setIsDone(this.isDone()).setMegabytesCopiedPerChunk(this.rewriteResponse.rewriteRequest.megabytesRewrittenPerCall).setRewriteToken(this.rewriteResponse.rewriteToken).setTotalBytesRewritten(this.getTotalBytesCopied()).build();
}
static /* synthetic */ StorageRpc.RewriteResponse access$000(final CopyWriter a1) {
return a1.rewriteResponse;
}
static /* synthetic */ StorageRpc access$100(final CopyWriter a1) {
return a1.storageRpc;
}
static class StateImpl implements RestorableState<CopyWriter>, Serializable
{
private static final long serialVersionUID = 1693964441435822700L;
private final StorageOptions serviceOptions;
private final BlobId source;
private final Map<StorageRpc.Option, ?> sourceOptions;
private final boolean overrideInfo;
private final BlobInfo target;
private final Map<StorageRpc.Option, ?> targetOptions;
private final BlobInfo result;
private final long blobSize;
private final boolean isDone;
private final String rewriteToken;
private final long totalBytesCopied;
private final Long megabytesCopiedPerChunk;
StateImpl(final Builder a1) {
super();
this.serviceOptions = a1.serviceOptions;
this.source = a1.source;
this.sourceOptions = a1.sourceOptions;
this.overrideInfo = a1.overrideInfo;
this.target = a1.target;
this.targetOptions = a1.targetOptions;
this.result = a1.result;
this.blobSize = a1.blobSize;
this.isDone = a1.isDone;
this.rewriteToken = a1.rewriteToken;
this.totalBytesCopied = a1.totalBytesCopied;
this.megabytesCopiedPerChunk = a1.megabytesCopiedPerChunk;
}
static Builder newBuilder(final StorageOptions a1, final BlobId a2, final Map<StorageRpc.Option, ?> a3, final boolean a4, final BlobInfo a5, final Map<StorageRpc.Option, ?> a6) {
return new Builder(a1, a2, (Map)a3, a4, a5, (Map)a6);
}
public CopyWriter restore() {
final StorageRpc.RewriteRequest v1 = new StorageRpc.RewriteRequest(this.source.toPb(), this.sourceOptions, this.overrideInfo, this.target.toPb(), this.targetOptions, this.megabytesCopiedPerChunk);
final StorageRpc.RewriteResponse v2 = new StorageRpc.RewriteResponse(v1, (this.result != null) ? this.result.toPb() : null, this.blobSize, this.isDone, this.rewriteToken, this.totalBytesCopied);
return new CopyWriter(this.serviceOptions, v2);
}
@Override
public int hashCode() {
return Objects.hash(this.serviceOptions, this.source, this.sourceOptions, this.overrideInfo, this.target, this.targetOptions, this.result, this.blobSize, this.isDone, this.megabytesCopiedPerChunk, this.rewriteToken, this.totalBytesCopied);
}
@Override
public boolean equals(final Object a1) {
if (a1 == null) {
return false;
}
if (!(a1 instanceof StateImpl)) {
return false;
}
final StateImpl v1 = (StateImpl)a1;
return Objects.equals(this.serviceOptions, v1.serviceOptions) && Objects.equals(this.source, v1.source) && Objects.equals(this.sourceOptions, v1.sourceOptions) && Objects.equals(this.overrideInfo, v1.overrideInfo) && Objects.equals(this.target, v1.target) && Objects.equals(this.targetOptions, v1.targetOptions) && Objects.equals(this.result, v1.result) && Objects.equals(this.rewriteToken, v1.rewriteToken) && Objects.equals(this.megabytesCopiedPerChunk, v1.megabytesCopiedPerChunk) && this.blobSize == v1.blobSize && this.isDone == v1.isDone && this.totalBytesCopied == v1.totalBytesCopied;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("source", this.source).add("overrideInfo", this.overrideInfo).add("target", this.target).add("result", this.result).add("blobSize", this.blobSize).add("isDone", this.isDone).add("rewriteToken", this.rewriteToken).add("totalBytesCopied", this.totalBytesCopied).add("megabytesCopiedPerChunk", this.megabytesCopiedPerChunk).toString();
}
public /* bridge */ Restorable restore() {
return (Restorable)this.restore();
}
static class Builder
{
private final StorageOptions serviceOptions;
private final BlobId source;
private final Map<StorageRpc.Option, ?> sourceOptions;
private final boolean overrideInfo;
private final BlobInfo target;
private final Map<StorageRpc.Option, ?> targetOptions;
private BlobInfo result;
private long blobSize;
private boolean isDone;
private String rewriteToken;
private long totalBytesCopied;
private Long megabytesCopiedPerChunk;
private Builder(final StorageOptions a1, final BlobId a2, final Map<StorageRpc.Option, ?> a3, final boolean a4, final BlobInfo a5, final Map<StorageRpc.Option, ?> a6) {
super();
this.serviceOptions = a1;
this.source = a2;
this.sourceOptions = a3;
this.overrideInfo = a4;
this.target = a5;
this.targetOptions = a6;
}
Builder setResult(final BlobInfo a1) {
this.result = a1;
return this;
}
Builder setBlobSize(final long a1) {
this.blobSize = a1;
return this;
}
Builder setIsDone(final boolean a1) {
this.isDone = a1;
return this;
}
Builder setRewriteToken(final String a1) {
this.rewriteToken = a1;
return this;
}
Builder setTotalBytesRewritten(final long a1) {
this.totalBytesCopied = a1;
return this;
}
Builder setMegabytesCopiedPerChunk(final Long a1) {
this.megabytesCopiedPerChunk = a1;
return this;
}
RestorableState<CopyWriter> build() {
return (RestorableState<CopyWriter>)new StateImpl(this);
}
static /* synthetic */ StorageOptions access$200(final Builder a1) {
return a1.serviceOptions;
}
static /* synthetic */ BlobId access$300(final Builder a1) {
return a1.source;
}
static /* synthetic */ Map access$400(final Builder a1) {
return a1.sourceOptions;
}
static /* synthetic */ boolean access$500(final Builder a1) {
return a1.overrideInfo;
}
static /* synthetic */ BlobInfo access$600(final Builder a1) {
return a1.target;
}
static /* synthetic */ Map access$700(final Builder a1) {
return a1.targetOptions;
}
static /* synthetic */ BlobInfo access$800(final Builder a1) {
return a1.result;
}
static /* synthetic */ long access$900(final Builder a1) {
return a1.blobSize;
}
static /* synthetic */ boolean access$1000(final Builder a1) {
return a1.isDone;
}
static /* synthetic */ String access$1100(final Builder a1) {
return a1.rewriteToken;
}
static /* synthetic */ long access$1200(final Builder a1) {
return a1.totalBytesCopied;
}
static /* synthetic */ Long access$1300(final Builder a1) {
return a1.megabytesCopiedPerChunk;
}
Builder(final StorageOptions a1, final BlobId a2, final Map a3, final boolean a4, final BlobInfo a5, final Map a6, final CopyWriter$1 a7) {
this(a1, a2, a3, a4, a5, a6);
}
}
}
}
| 43.102273 | 689 | 0.589068 |
e915e926d8289f9004c175e8d11036a9dc7f2422 | 4,141 | package soot.asm.backend;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.util.TraceClassVisitor;
/**
* Test for try catch bytecode instructions
*
* @author Tobias Hamann, Florian Kuebler, Dominik Helm, Lukas Sommer
*
*/
public class TryCatchTest extends AbstractASMBackendTest {
@Override
protected void generate(TraceClassVisitor cw) {
MethodVisitor mv;
cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/TryCatch", null, "java/lang/Object", null);
cw.visitSource("TryCatch.java", null);
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
if (targetCompiler == TargetCompiler.eclipse) {
mv = cw.visitMethod(0, "doSth", "(Ljava/lang/Object;)I", null, null);
mv.visitCode();
Label l0 = new Label();
Label l1 = new Label();
Label l2 = new Label();
mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NullPointerException");
Label l3 = new Label();
Label l4 = new Label();
mv.visitTryCatchBlock(l0, l3, l4, "java/lang/Throwable");
mv.visitInsn(ICONST_0);
mv.visitVarInsn(ISTORE, 0);
mv.visitLabel(l0);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "notify", "()V", false);
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, 0);
mv.visitLabel(l1);
Label l5 = new Label();
mv.visitJumpInsn(GOTO, l5);
mv.visitLabel(l2);
//mv.visitFrame(F_FULL, 3, new Object[] {"soot/asm/backend/targets/TryCatch", "java/lang/Object", INTEGER}, 1, new Object[] {"java/lang/NullPointerException"});
mv.visitVarInsn(ASTORE, 1);
mv.visitInsn(ICONST_M1);
mv.visitVarInsn(ISTORE, 0);
mv.visitLabel(l3);
mv.visitJumpInsn(GOTO, l5);
mv.visitLabel(l4);
//mv.visitFrame(F_SAME1, 0, null, 1, new Object[] {"java/lang/Throwable"});
mv.visitVarInsn(ASTORE, 1);
mv.visitLabel(l5);
//mv.visitFrame(F_SAME, 0, null, 0, null);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(IRETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
else {
mv = cw.visitMethod(0, "doSth", "(Ljava/lang/Object;)I", null, null);
mv.visitCode();
Label l0 = new Label();
Label l1 = new Label();
Label l2 = new Label();
mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NullPointerException");
Label l3 = new Label();
mv.visitTryCatchBlock(l0, l1, l3, "java/lang/Throwable");
Label l4 = new Label();
mv.visitTryCatchBlock(l2, l4, l3, "java/lang/Throwable");
Label l5 = new Label();
mv.visitTryCatchBlock(l3, l5, l3, "java/lang/Throwable");
mv.visitLabel(l0);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "notify", "()V", false);
mv.visitLabel(l1);
mv.visitInsn(ICONST_1);
mv.visitInsn(IRETURN);
mv.visitLabel(l2);
mv.visitVarInsn(ASTORE, 0);
mv.visitLabel(l4);
mv.visitInsn(ICONST_M1);
mv.visitInsn(IRETURN);
mv.visitLabel(l3);
mv.visitVarInsn(ASTORE, 0);
mv.visitLabel(l5);
mv.visitInsn(ICONST_0);
mv.visitInsn(IRETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
cw.visitEnd();
}
@Override
protected String getTargetClass() {
return "soot.asm.backend.targets.TryCatch";
}
}
| 31.135338 | 162 | 0.685583 |
a37130cbe06933aeb8fdd42acfbc7f729a0ae260 | 2,438 | package org.joverseer.domain;
import java.io.Serializable;
/**
* Stores information about an element of an army estimate.
*
* @author Marios Skounakis
*
*/
public class ArmyEstimateElement implements Serializable {
private static final long serialVersionUID = 5958104833199695499L;
String description;
ArmyElementType type;
int number;
String weaponsDescription;
String weaponsRange;
int weapons;
String armorDescription;
String armorRange;
int armor;
String trainingDescription;
String trainingRange;
int training;
public int getArmor() {
return this.armor;
}
public void setArmor(int armor) {
this.armor = armor;
}
public String getArmorDescription() {
return this.armorDescription;
}
public void setArmorDescription(String armorDescription) {
this.armorDescription = armorDescription;
}
public String getArmorRange() {
return this.armorRange;
}
public void setArmorRange(String armorRange) {
this.armorRange = armorRange;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public int getNumber() {
return this.number;
}
public void setNumber(int number) {
this.number = number;
}
public int getTraining() {
return this.training;
}
public void setTraining(int training) {
this.training = training;
}
public String getTrainingDescription() {
return this.trainingDescription;
}
public void setTrainingDescription(String trainingDescription) {
this.trainingDescription = trainingDescription;
}
public String getTrainingRange() {
return this.trainingRange;
}
public void setTrainingRange(String trainingRange) {
this.trainingRange = trainingRange;
}
public ArmyElementType getType() {
return this.type;
}
public void setType(ArmyElementType type) {
this.type = type;
}
public int getWeapons() {
return this.weapons;
}
public void setWeapons(int weapons) {
this.weapons = weapons;
}
public String getWeaponsDescription() {
return this.weaponsDescription;
}
public void setWeaponsDescription(String weaponsDescription) {
this.weaponsDescription = weaponsDescription;
}
public String getWeaponsRange() {
return this.weaponsRange;
}
public void setWeaponsRange(String weaponsRange) {
this.weaponsRange = weaponsRange;
}
}
| 23.442308 | 68 | 0.725595 |
19f200f70adf829f6654ffee9bb85cb47931627e | 7,710 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.distributed;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.pivotal.gemfirexd.internal.engine.Misc;
import com.pivotal.gemfirexd.internal.engine.GfxdConstants;
import com.pivotal.gemfirexd.internal.engine.access.GemFireTransaction;
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils;
import com.pivotal.gemfirexd.internal.engine.locks.GfxdLockSet;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.store.raw.ContainerHandle;
/**
* Some helper methods for {@link GfxdResultCollector} implementations.
*
* @author swale
*/
public final class GfxdResultCollectorHelper extends ReentrantLock {
private static final long serialVersionUID = 5295482892857557452L;
private Set<DistributedMember> members;
private Collection<GemFireContainer> containersToClose;
private GemFireTransaction tran;
private int numRefs;
/**
* @see GfxdResultCollector#setResultMembers(Set)
*/
public final void setResultMembers(Set<DistributedMember> members) {
this.members = members;
}
/**
* @see GfxdResultCollector#getResultMembers()
*/
public final Set<DistributedMember> getResultMembers() {
return this.members;
}
public final void addResultMember(final DistributedMember member) {
if (member != null) {
final Set<DistributedMember> members = this.members;
if (members != null) {
// TODO: SW: instead of sync on members, can use the helper to lock
synchronized (members) {
members.add(member);
}
}
}
}
/**
* @see GfxdResultCollector#setupContainersToClose(Collection,
* GemFireTransaction)
*/
public final boolean setupContainersToClose(final GfxdResultCollector<?> rc,
final Collection<GemFireContainer> containers,
final GemFireTransaction tran) throws StandardException {
if (containers != null && tran != null && containers.size() > 0) {
if (GemFireXDUtils.TraceRSIter) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_RSITER,
"GfxdResultCollectorHelper#setupContainersToClose: "
+ "for ResultCollector " + rc + " setting containers: "
+ containers);
}
this.lock();
for (GemFireContainer container : containers) {
container.open(tran, ContainerHandle.MODE_READONLY);
}
this.containersToClose = containers;
this.tran = tran;
this.numRefs = 0;
this.unlock();
tran.getLockSpace().rcSet(rc);
return true;
}
return false;
}
/**
* Close the containers setup with
* {@link #setupContainersToClose(Collection, GemFireTransaction)} releasing
* any read/write locks obtained on them in this Transaction.
*/
public final void closeContainers(final GfxdResultCollector<?> rc,
boolean rcEnd) {
this.lock();
try {
final Collection<GemFireContainer> closeContainers =
this.containersToClose;
if (closeContainers != null) {
// check that all references have invoked closeContainers
if (removeReference()) {
if (GemFireXDUtils.TraceRSIter) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_RSITER,
"GfxdResultCollectorHelper#closeContainers: "
+ "clearing ResultCollector " + rc
+ " and closing containers: " + closeContainers);
}
// release the DML locks
closeContainers(closeContainers, rc, this.tran);
}
else if (rcEnd) {
if (GemFireXDUtils.TraceRSIter) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_RSITER,
"GfxdResultCollectorHelper#closeContainers: force "
+ "end ResultCollector " + rc);
}
final GemFireTransaction tran = this.tran;
final GfxdLockSet lockSet;
if (tran != null && (lockSet = tran.getLockSpace()) != null) {
lockSet.rcEnd(rc);
}
}
}
} finally {
this.unlock();
}
}
public final void clear(final GfxdResultCollector<?> rc) {
if (GemFireXDUtils.TraceRSIter) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_RSITER,
"GfxdResultCollectorHelper#clear: end ResultCollector " + rc);
}
this.lock();
try {
assert this.numRefs >= 0: "clear: unexpected numRefs=" + this.numRefs;
// this.members = null;
if (this.numRefs > 0) {
final Collection<GemFireContainer> closeContainers =
this.containersToClose;
if (closeContainers != null) {
closeContainers(closeContainers, rc, this.tran);
}
this.numRefs = 0;
}
} finally {
this.unlock();
}
}
private void closeContainers(
final Collection<GemFireContainer> closeContainers,
final GfxdResultCollector<?> rc, final GemFireTransaction tran) {
assert this.isHeldByCurrentThread(): "closeContainers: lock not held";
GemFireContainer container = null;
try {
Iterator<GemFireContainer> iter = closeContainers.iterator();
while (iter.hasNext()) {
container = iter.next();
container.closeForEndTransaction(tran, false);
}
this.containersToClose = null;
this.tran = null;
} catch (RuntimeException ex) {
final LogWriter logger = Misc.getCacheLogWriter();
logger.error("GfxdResultCollectorHelper#closeContainers: "
+ "for ResultCollector " + rc + " unexpected exception "
+ "in closing container " + container, ex);
throw ex;
} finally {
if (GemFireXDUtils.TraceRSIter) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_RSITER,
"GfxdResultCollectorHelper#closeContainers: "
+ "end ResultCollector " + rc);
}
final GfxdLockSet lockSet;
if (tran != null && (lockSet = tran.getLockSpace()) != null) {
lockSet.rcEnd(rc);
}
}
}
/**
* Add a reference to this helper so that the helper will wait for an
* additional {@link #closeContainers(GfxdResultCollector)} call for this
* reference before actually closing the containers.
*/
public final void addReference() {
this.lock();
this.numRefs++;
this.unlock();
}
/**
* Remove a reference added by {@link #addReference()} and return true if the
* current number of references (before removal) is zero.
*/
private final boolean removeReference() {
assert this.isHeldByCurrentThread(): "removeReference: lock not held";
if (this.numRefs == 0) {
return true;
}
this.numRefs--;
return false;
}
}
| 33.521739 | 79 | 0.671725 |
6f8d785bf2c21d82650ccab00cd19dcbb5075559 | 4,775 | /*
* Copyright (c) 2017. Hans-Peter Grahsl ([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 at.bronzels.kafka.connect.kudu.cdc.debezium.mongodb;
import at.bronzels.libcdcdw.OperationType;
import at.bronzels.libcdcdw.kudu.pool.MyKudu;
import at.bronzels.libcdcdw.util.MyKuduTypeValue;
import at.grahsl.kafka.connect.converter.SinkDocument;
import at.bronzels.kafka.connect.kudu.cdc.CdcOperation;
import at.bronzels.libcdcdw.util.MyBson;
import at.bronzels.libcdcdw.kudu.KuduOperation;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kudu.Type;
import org.apache.kudu.client.*;
import org.bson.BsonDocument;
import org.bson.BsonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class MongoDbUpdate implements CdcOperation {
private static Logger logger = LoggerFactory.getLogger(MongoDbUpdate.class);
String methodSet = "$set";
String methodUnset = "$unset";
public static final String JSON_DOC_FIELD_PATH = "patch";
@Override
public Collection<Operation> perform(SinkDocument doc, MyKudu myKudu, boolean isSrcFieldNameWTUpperCase, Schema valueSchema) {
//patch contains idempotent change only to update original document with
BsonDocument keyDoc = doc.getKeyDoc().orElseThrow(
() -> new DataException("error: key doc must not be missing for update operation")
);
BsonDocument valueDoc = doc.getValueDoc().orElseThrow(
() -> new DataException("error: value doc must not be missing for update operation")
);
BsonDocument updateDoc = BsonDocument.parse(
valueDoc.getString(JSON_DOC_FIELD_PATH).getValue()
);
Set<String> keySet = updateDoc.keySet();
if (keySet.contains(methodSet))
updateDoc = updateDoc.get(methodSet).asDocument();
else if (keySet.contains(methodUnset)) {
Set<String> keys2Unset = updateDoc.get(methodUnset).asDocument().keySet();
updateDoc = new BsonDocument();
for (String key : keys2Unset)
updateDoc.put(key, new BsonNull());
}
//throw new RuntimeException(String.format("unrecognized format, keyDoc:%s, updateDoc:%s", keyDoc, updateDoc));
List<Operation> opList = new ArrayList<>();
Map<String, Type> newCol2TypeMap = MyKuduTypeValue.getBsonCol2Add(myKudu.getName2TypeMap(), updateDoc, isSrcFieldNameWTUpperCase);
if(newCol2TypeMap.size() > 0){
logger.info("col name to add : {}, type: {}", newCol2TypeMap.keySet(), newCol2TypeMap.values());
myKudu.addColumns(newCol2TypeMap);
}
//patch contains full new document for replacement
if (updateDoc.containsKey(at.bronzels.libcdcdw.Constants.RK_4_MONGODB_AND_OTHER_DBS_ID_FIELD_NAME)) {
BsonDocument filterDoc =
new BsonDocument(at.bronzels.libcdcdw.Constants.RK_4_MONGODB_AND_OTHER_DBS_ID_FIELD_NAME,
updateDoc.get(at.bronzels.libcdcdw.Constants.RK_4_MONGODB_AND_OTHER_DBS_ID_FIELD_NAME));
Operation opDelete = KuduOperation.getOperation(OperationType.DELETE, myKudu.getKuduTable(), filterDoc, isSrcFieldNameWTUpperCase);
if (opDelete != null)
opList.add(opDelete);
Operation opInsert = KuduOperation.getOperation(OperationType.CREATE, myKudu.getKuduTable(), updateDoc, isSrcFieldNameWTUpperCase);
if (opInsert != null)
opList.add(opInsert);
return opList;
}
BsonDocument filterDoc = BsonDocument.parse(
"{" + at.bronzels.libcdcdw.Constants.RK_4_MONGODB_AND_OTHER_DBS_ID_FIELD_NAME +
":" + keyDoc.getString(MongoDbHandler.JSON_ID_FIELD_PATH)
.getValue() + "}"
);
BsonDocument merged = MyBson.getMerged(filterDoc, updateDoc);
Operation opUpdate = KuduOperation.getOperation(OperationType.UPDATE, myKudu.getKuduTable(), merged, isSrcFieldNameWTUpperCase);
if (opUpdate != null)
opList.add(opUpdate);
return opList.isEmpty() ? null : opList;
}
}
| 42.633929 | 143 | 0.69089 |
09d44d394f2a284659e64b01c0a809a1cae7642d | 2,033 | /*
* 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.sling.launchpad.testservices.handlers;
import org.apache.jackrabbit.server.io.DeleteContext;
import org.apache.jackrabbit.server.io.DeleteHandler;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
public abstract class AbstractDeleteHandler implements DeleteHandler {
protected String HANDLER_NAME = "";
protected String HANDLER_BKP;
@Override
public boolean delete(DeleteContext deleteContext,
DavResource resource) throws DavException {
try {
deleteContext.getSession().getWorkspace().move(resource.getResourcePath(), resource.getResourcePath() + HANDLER_BKP);
return true;
} catch (RepositoryException e) {
return false;
}
}
@Override
public boolean canDelete(DeleteContext deleteContext,
DavResource resource) {
try {
Node nodeToDelete = deleteContext.getSession().getNode(resource.getResourcePath());
return HANDLER_NAME.equals(nodeToDelete.getName());
} catch (RepositoryException e) {
return false;
}
}
}
| 35.051724 | 129 | 0.719134 |
fc9344365d0fe0f04ca30ea45196fda82c1704b6 | 3,554 | /**
* Copyright (C) 2013-2017 Helical IT Solutions (http://www.helicalinsight.com) - All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helicalinsight.efw.vf;
import com.google.gson.JsonArray;
import com.helicalinsight.efw.exceptions.ClassNotConfiguredException;
import com.helicalinsight.efw.framework.FactoryMethodWrapper;
import com.helicalinsight.efw.resourceprocessor.IProcessor;
import com.helicalinsight.efw.resourceprocessor.ResourceProcessorFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Muqtar
* @author Rajasekhar
* @see ChartService
*/
public class ChartResource {
private static final Logger logger = LoggerFactory.getLogger(ChartResource.class);
private final String settingPath;
private final JsonArray data;
private final JSONObject chartData;
private final Integer chartId;
/**
* <p>
* Constructor that sets the instance variables
* path
* </p>
*
* @param settingPath The path to setting.xml
* @param data The query execution result
* @param chartData The properties of chart(The prop tag in Chart)
*/
public ChartResource(String settingPath, JsonArray data, JSONObject chartData, Integer chartId) {
this.settingPath = settingPath;
this.data = data;
this.chartData = chartData;
this.chartId = chartId;
}
/**
* <p>
* Responsibility of this method is create instance of a class which is
* available in setting.xml file within Charts tag. Before that it checks
* type of Charts node in setting.xml whether it is same as the type
* coming from front end.
* </p>
*
* @return Returns the data along with the chart script
*/
public String getScript() {
IProcessor processor = ResourceProcessorFactory.getIProcessor();
JSONObject settingXMLJsonObject = processor.getJSONObject(settingPath, false);
JSONArray settingXMLDataMap = settingXMLJsonObject.getJSONArray("Charts");
String chartScript;
IChart chartObject = null;
String type = chartData.getString("type");
if (logger.isDebugEnabled()) {
logger.debug("The type of chart being rendered is " + type);
}
for (int count = 0; count < settingXMLDataMap.size(); count++) {
if (type.equalsIgnoreCase(settingXMLDataMap.getJSONObject(count).getString("@type"))) {
String clazz = settingXMLDataMap.getJSONObject(count).getString("@class");
chartObject = (IChart) FactoryMethodWrapper.getUntypedInstance(clazz);
break;
}
}
if (chartObject == null) {
throw new ClassNotConfiguredException("IChart implementation is not found");
}
chartScript = chartObject.getChartDetails(chartData, data, String.valueOf(chartId));
return chartScript;
}
} | 37.808511 | 105 | 0.685706 |
b7612c30f1bbbd7e4e1d3f067b479e7a0ae9a214 | 1,462 | package org.academiadecodigo.koxtiposix.acdefender;
import org.academiadecodigo.koxtiposix.acdefender.enemy.Enemy;
import org.academiadecodigo.koxtiposix.acdefender.weapons.Bullet;
import org.academiadecodigo.simplegraphics.pictures.Picture;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class CollisionDetector {
private List<Enemy> enemies;
private LinkedList<Bullet> bullets;
public CollisionDetector(List<Enemy> enemies) {
this.enemies = enemies;
}
public void setBullets(LinkedList<Bullet> bullets) {
this.bullets = bullets;
}
public Boolean checkCollision(Picture bullet) {
for (int i = 0; i < enemies.size(); i++) {
if (bullet.getY() > enemies.get(i).getEnemyChar().getY() &&
bullet.getY() < enemies.get(i).getEnemyChar().getY() + enemies.get(i).getEnemyChar().getHeight()) {
if (bullet.getX() + bullet.getWidth() >= enemies.get(i).getEnemyChar().getX()) {
//System.out.println("Shoot");
enemies.get(i).suffer();
return true;
}
//System.out.println("Close");
}
}
Iterator<Enemy> iterator = enemies.iterator();
while (iterator.hasNext()) {
if (iterator.next().isDead()) {
iterator.remove();
}
}
return false;
}
}
| 27.584906 | 119 | 0.593707 |
40fbb0383b9e3fc0f9ce906ab20cf8336d1837af | 6,719 | /*
* Copyright 2014 Andrew Reitz
*
* 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 shillelagh;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.test.AndroidTestCase;
import com.example.shillelagh.model.SimpleObject;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class QueryBuilderTest extends AndroidTestCase {
private Shillelagh shillelagh;
@Override protected void setUp() throws Exception {
super.setUp();
SQLiteOpenHelper sqliteOpenHelper = new QueryBuilderTestSQLiteOpenHelper(getContext());
shillelagh = new Shillelagh(sqliteOpenHelper);
for (int i = 0; i < 1000; i++) {
final SimpleObject simpleObject =
new SimpleObject(String.valueOf(i), String.valueOf((i % 10) + 1), (i % 100) + 1);
shillelagh.insert(simpleObject);
}
}
@Override protected void tearDown() throws Exception {
getContext().deleteDatabase(QueryBuilderTestSQLiteOpenHelper.DATABASE_NAME);
super.tearDown();
}
public void testSelect() {
final WhereBuilder<SimpleObject> builder = shillelagh.selectFrom(SimpleObject.class);
assertThat(builder.toString()).isEqualTo("SELECT * FROM SimpleObject");
assertThat(builder.toList()).hasSize(1000);
assertThat(builder.toCursor().getCount()).isEqualTo(1000);
assertThat(builder.toObservable().toList().toBlocking().first().size()).isEqualTo(1000);
}
public void testWhere() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isEqualTo(14);
assertThat(selectStatement.toString()).isEqualTo("SELECT * FROM SimpleObject WHERE id = 14");
assertThat(selectStatement.toList()).hasSize(1);
}
public void testWhereNotNull() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isNotNull();
assertThat(selectStatement.toList()).hasSize(1000);
}
public void testWhereNull() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isNull();
assertThat(selectStatement.toList()).hasSize(0);
}
public void testWhereNotEqual() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("name").isNotEqualTo(100);
assertThat(selectStatement.toList()).hasSize(999);
}
public void testWhereGreaterThanEqualTo() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isGreaterThanOrEqualTo(999);
assertThat(selectStatement.toList()).hasSize(2);
}
public void testWhereGreaterThan() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isGreaterThan(999);
assertThat(selectStatement.toList()).hasSize(1);
}
public void testWhereLessThanEqualTo() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isLessThanOrEqualTo(2);
assertThat(selectStatement.toList()).hasSize(2);
}
public void testWhereLessThan() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").isLessThan(2);
assertThat(selectStatement.toList()).hasSize(1);
}
public void testBetween() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("id").between(10, 12);
assertThat(selectStatement.toList()).hasSize(3);
}
public void testAnd() {
final QueryBuilder<SimpleObject> selectStatement = shillelagh.selectFrom(SimpleObject.class)
.where("name")
.isEqualTo(0)
.and("address")
.isEqualTo(1);
assertThat(selectStatement.toList()).hasSize(1);
}
public void testOr() {
final QueryBuilder<SimpleObject> selectStatement = shillelagh.selectFrom(SimpleObject.class)
.where("name")
.isEqualTo(0)
.or("address")
.isEqualTo(1);
assertThat(selectStatement.toList()).hasSize(100);
}
public void testLike() {
final QueryBuilder<SimpleObject> selectStatement =
shillelagh.selectFrom(SimpleObject.class).where("name").like("%00");
assertThat(selectStatement.toList()).hasSize(9);
}
public void testOrderBy() {
final List<SimpleObject> objects =
shillelagh.selectFrom(SimpleObject.class).orderBy("customerId").toList();
int last = 0;
for (final SimpleObject simpleObject : objects) {
assertThat(simpleObject.getCustomerId()).isGreaterThanOrEqualTo(last);
last = (int) simpleObject.getCustomerId();
}
}
public void testOrderByAscending() {
final List<SimpleObject> objects =
shillelagh.selectFrom(SimpleObject.class).orderBy("customerId").ascending().toList();
int last = 0;
for (final SimpleObject simpleObject : objects) {
assertThat(simpleObject.getCustomerId()).isGreaterThanOrEqualTo(last);
last = (int) simpleObject.getCustomerId();
}
}
public void testOrderByDescending() {
final List<SimpleObject> objects =
shillelagh.selectFrom(SimpleObject.class).orderBy("customerId").descending().toList();
int last = Integer.MAX_VALUE;
for (final SimpleObject simpleObject : objects) {
assertThat(simpleObject.getCustomerId()).isLessThanOrEqualTo(last);
last = (int) simpleObject.getCustomerId();
}
}
private static class QueryBuilderTestSQLiteOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "query_builder.db";
private static final int DATABASE_VERSION = 3;
public QueryBuilderTestSQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override public void onCreate(SQLiteDatabase db) {
Shillelagh.createTable(db, SimpleObject.class);
}
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Shillelagh.dropTable(db, SimpleObject.class);
onCreate(db);
}
}
}
| 33.427861 | 97 | 0.721536 |
105d1a9ad89e2c0c157c14a4c106d8025faf1e08 | 5,828 | package mainpackage;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Demonstration {
static final int MAX_STUDENTS = 30;
static final String csvPath = "./data.csv";
static String[][] parseCSV(String path) {
String[][] dataToRet = new String[MAX_STUDENTS][4];
String csvFilePath = path;
BufferedReader br = null;
String line = "";
String csvSplitBy = ",";
int index = 0;
try {
br = new BufferedReader(new FileReader(csvFilePath));
while ((line = br.readLine()) != null) {
String[] data = line.split(csvSplitBy);
dataToRet[index++] = data;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return (dataToRet);
}
static Student[] FillStudents() {
Student[] studentArray = new Student[MAX_STUDENTS];
for (int i = 0; i < MAX_STUDENTS; i++) {
studentArray[i] = new Student();
}
String[][] parsedData = parseCSV(csvPath);
for (int i = 0; i < MAX_STUDENTS; i++) {
studentArray[i].setName(parsedData[i][0]);
studentArray[i].setSurname(parsedData[i][1]);
studentArray[i].setGroup(Integer.parseInt(parsedData[i][2]));
studentArray[i].setZachetka(Integer.parseInt(parsedData[i][3]));
}
return (studentArray);
}
static void PrintStudents(Student[] studentArray) {
System.out.println("");
System.out.printf("-----------------------------\n%-7s %-10s %-4s %-4s\n-----------------------------\n",
"Name", "Surname", "Group", "Zach");
for (int i = 0; i < MAX_STUDENTS; i++) {
System.out.printf("%-7s %-12s %-4d %-4d\n", studentArray[i].getName(), studentArray[i].getSurname(),
studentArray[i].getGroup(), studentArray[i].getZachetka());
}
System.out.println("-----------------------------\n");
}
static int StudentsCompareFacultyGroup(Student s1, Student s2) {
int result = Integer.valueOf(s1.getGroup()).compareTo(s2.getGroup());
if (result == 0) {
return Integer.valueOf(s1.getZachetka()).compareTo(s2.getZachetka());
} else {
return result;
}
}
static void SwapStudents(Student a, Student b) {
Student temp = new Student();
temp.StudentCopy(a);
a.StudentCopy(b);
b.StudentCopy(temp);
}
static void InsertionSort(Student[] arr) {
for (int i = 1; i < arr.length; i++) {
Student elem = arr[i];
int j = i - 1;
while (j >= 0 && StudentsCompareFacultyGroup(arr[j], elem) > 0) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = elem;
}
}
static void ShellSort(Student[] arr) {
int h = 1;
while (h <= arr.length / 3) {
h = h * 3 + 1;
}
//h=13
while (h > 0) {
for (int i = h; i < arr.length; i++) {
Student temp = arr[i];
int j = i;
while (j > h - 1 && arr[j - h].getZachetka() >= temp.getZachetka()) {
arr[j] = arr[j - h];
j -= h;
}
arr[j] = temp;
}
h /= 3;
}
}
static Student[][] ConvertTwoDimensionalArray(Student[] studentArray) {
// Count how many different groups exists in studentArray.
// We need this var for returning array initialization.
int groupCountMax = studentArray[0].getGroup();
for (int i = 1; i < MAX_STUDENTS; i++) {
if (studentArray[i].getGroup() > groupCountMax) {
groupCountMax = studentArray[i].getGroup();
}
}
// Initialize returning array - that`s why we needed groupCountMax
// integer.
Student[][] out = new Student[groupCountMax][];
// Fill returning array with certain students.
for (int i = 0; i < groupCountMax; i++) {
// How much students are in certain group.
int studentInGroup = 0;
for (int j = 0; j < MAX_STUDENTS; j++) {
if (studentArray[j].getGroup() == (i + 1)) {
studentInGroup++;
}
}
out[i] = new Student[studentInGroup];
// Paste Students into returning array.
int indexStudentInGroup = 0;
for (int j = 0; j < MAX_STUDENTS; j++) {
if (studentArray[j].getGroup() == (i + 1)) {
out[i][indexStudentInGroup++] = studentArray[j];
}
}
}
// Return sorted two-dimensional array.
return (out);
}
static void PrintStudentsTwoDimensional(Student[][] toPrint) {
System.out.println("");
System.out.println("-----------------------------\n");
for (int i = 0; i < toPrint.length; i++) {
System.out.printf("GROUP %d\n", (i + 1));
System.out.printf("%-7s %-10s %-4s\n", "Name", "Surname", "Zach");
for (int j = 0; j < toPrint[i].length; j++) {
System.out.printf("%-7s %-10s %-4d\n", toPrint[i][j].getName(), toPrint[i][j].getSurname(),
toPrint[i][j].getZachetka());
}
System.out.println("");
}
System.out.println("-----------------------------\n");
}
static void Task1(Student[] studentArray) {
System.out.println("Task1 - insertion sort.");
System.out.println("Students array before sorting:");
PrintStudents(studentArray);
InsertionSort(studentArray);
System.out.println("Students array, sorted by group and zachetka:");
PrintStudents(studentArray);
}
static void Task2(Student[] studentArray) {
System.out.println("Task 2 - Shell sort.");
System.out.println("Students array before sorting:");
Student[][] twoDimStudentArray = ConvertTwoDimensionalArray(studentArray);
PrintStudentsTwoDimensional(twoDimStudentArray);
// Sort each group by increasing by zachetka with Shellsort algorithm.
for (int i = 0; i < twoDimStudentArray.length; i++) {
ShellSort(twoDimStudentArray[i]);
}
System.out.println("Students array, sorted by group and zachetka");
PrintStudentsTwoDimensional(twoDimStudentArray);
}
public static void main(String[] args) throws IOException {
Student[] studentArray = FillStudents();
// Task1(studentArray);
Task2(studentArray);
}
}
| 29.887179 | 107 | 0.624228 |
e6cf81909099582860bebe8d327a2eba10170046 | 4,148 | package com.felipeflohr.w2gbuilder.seleniumbuilder;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Scanner;
public class Builder {
private final File txtLinkFiles;
private final String username;
private final boolean notWorkingVideosEnabled;
private final File notWorkingVideosFile;
private final WebDriver driver;
public Builder(File txtLinkFiles, String username, boolean notWorkingVideosEnabled, File notWorkingVideosFile) throws FileNotFoundException, InterruptedException {
this.txtLinkFiles = txtLinkFiles;
this.username = username;
this.notWorkingVideosEnabled = notWorkingVideosEnabled;
this.notWorkingVideosFile = notWorkingVideosFile;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--mute-audio");
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(chromeOptions);
buildW2G();
}
private void buildW2G() throws InterruptedException, FileNotFoundException {
generateW2GRoom();
getVideoURLs().forEach(video -> {
try {
addVideo(video);
} catch (IOException e) {
e.printStackTrace();
}
});
}
private void generateW2GRoom() throws InterruptedException {
driver.get("https://w2g.tv/?lang=pt");
driver.manage().window().maximize();
// Will click to create a room
WebElement createRoomBtn = driver.findElement(new By.ByXPath("//*[@id=\"create_room_button\"]"));
createRoomBtn.click();
// Will enter the username
WebElement usernameInput = driver.findElement(new By.ByXPath("//*[@id=\"intro-nickname\"]"));
usernameInput.clear();
usernameInput.sendKeys(this.username); // Sets the username to the chosen one
// Will click the "Enter room" button
WebElement enterRoomBtn = driver.findElement(new By.ByXPath("//*[@id=\"intro-modal\"]/div[2]/div"));
enterRoomBtn.click();
Thread.sleep(3000);
}
private void addVideo(String url) throws IOException {
// Selects the video search bar and inserts the video URL
WebElement videoSearchBar = new WebDriverWait(this.driver, Duration.ofSeconds(5))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"search-bar-input\"]")));
videoSearchBar.clear();
videoSearchBar.sendKeys(url);
// Clicks the button "search"
WebElement searchBtn = this.driver.findElement(By.xpath("//*[@id=\"search-bar-form\"]/div/button"));
searchBtn.click();
// Clicks to add the video
try{
WebElement videoAddBtn = new WebDriverWait(this.driver, Duration.ofSeconds(5))
.until(ExpectedConditions.elementToBeClickable(
By.xpath("//*[@id=\"w2g-search-results\"]/div[4]/div/div[3]/div[2]")));
videoAddBtn.click();
}
catch(TimeoutException e){
if (notWorkingVideosEnabled) {
FileWriter writer = new FileWriter(notWorkingVideosFile.getAbsolutePath(), true);
writer.write("\n" + url);
writer.close();
}
}
}
private ArrayList<String> getVideoURLs() throws FileNotFoundException {
final ArrayList<String> links = new ArrayList<>();
Scanner scanner = new Scanner(txtLinkFiles);
while (scanner.hasNext()) {
links.add(scanner.nextLine());
}
scanner.close();
return links;
}
} | 37.035714 | 167 | 0.659354 |
f5290a9769288fc14ce60ccd58bab56585a36505 | 5,787 | /*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.opt.logical;
import com.hazelcast.jet.sql.impl.connector.SqlConnectorUtil;
import com.hazelcast.jet.sql.impl.opt.OptUtils;
import com.hazelcast.jet.sql.impl.schema.HazelcastRelOptTable;
import com.hazelcast.jet.sql.impl.schema.HazelcastTable;
import com.hazelcast.sql.impl.schema.Table;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.rel.logical.LogicalTableScan;
import org.apache.calcite.rel.logical.LogicalValues;
import java.util.List;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
import static org.apache.calcite.plan.RelOptRule.none;
import static org.apache.calcite.plan.RelOptRule.operand;
import static org.apache.calcite.plan.RelOptRule.operandJ;
// no support for UPDATE FROM SELECT case (which is not yet implemented)
// once joins are there we need to create complementary rule
final class UpdateLogicalRules {
@SuppressWarnings("checkstyle:anoninnerlength")
static final RelOptRule INSTANCE =
new RelOptRule(
operandJ(
LogicalTableModify.class, null, TableModify::isUpdate,
operand(
LogicalProject.class,
operand(LogicalTableScan.class, none())
)
),
UpdateLogicalRules.class.getSimpleName()
) {
@Override
public void onMatch(RelOptRuleCall call) {
LogicalTableModify update = call.rel(0);
LogicalTableScan scan = call.rel(2);
UpdateLogicalRel rel = new UpdateLogicalRel(
update.getCluster(),
OptUtils.toLogicalConvention(update.getTraitSet()),
update.getTable(),
update.getCatalogReader(),
rewriteScan(scan),
update.getUpdateColumnList(),
update.getSourceExpressionList(),
update.isFlattened()
);
call.transformTo(rel);
}
// rewrites existing project to just primary keys project
private RelNode rewriteScan(LogicalTableScan scan) {
HazelcastRelOptTable relTable = (HazelcastRelOptTable) scan.getTable();
HazelcastTable hazelcastTable = relTable.unwrap(HazelcastTable.class);
return new FullScanLogicalRel(
scan.getCluster(),
OptUtils.toLogicalConvention(scan.getTraitSet()),
OptUtils.createRelTable(
relTable.getDelegate().getQualifiedName(),
hazelcastTable.withProject(keyProjects(hazelcastTable.getTarget())),
scan.getCluster().getTypeFactory()),
null,
-1);
}
private List<Integer> keyProjects(Table table) {
List<String> primaryKey = SqlConnectorUtil.getJetSqlConnector(table).getPrimaryKey(table);
return IntStream.range(0, table.getFieldCount())
.filter(i -> primaryKey.contains(table.getField(i).getName()))
.boxed()
.collect(toList());
}
};
// no-updates case, i.e. '... WHERE __key = 1 AND __key = 2'
// could/should be optimized to no-op
static final RelOptRule NOOP_INSTANCE =
new RelOptRule(
operandJ(
LogicalTableModify.class, null, TableModify::isUpdate,
operand(LogicalValues.class, none())
),
UpdateLogicalRules.class.getSimpleName() + "(NOOP)"
) {
@Override
public void onMatch(RelOptRuleCall call) {
LogicalTableModify update = call.rel(0);
LogicalValues values = call.rel(1);
UpdateLogicalRel rel = new UpdateLogicalRel(
update.getCluster(),
OptUtils.toLogicalConvention(update.getTraitSet()),
update.getTable(),
update.getCatalogReader(),
OptUtils.toLogicalInput(values),
update.getUpdateColumnList(),
update.getSourceExpressionList(),
update.isFlattened()
);
call.transformTo(rel);
}
};
private UpdateLogicalRules() {
}
}
| 43.840909 | 110 | 0.563159 |
9ac14626e683ae8d2b9673cffae31592c69c9516 | 121 | package best.reich.ingros.events.entity;
import net.b0at.api.event.Event;
public class TeleportEvent extends Event {
}
| 17.285714 | 42 | 0.793388 |
7eb5eda1812943de76a279807a5a4dbdc04bcec5 | 27,062 | package Utils;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
/**
* Класс, который отвечает за стиль JSON
* @author Илья
*
*/
public class JSON {
/**Перечисление разных состояний парсинга файла*/
private enum JSON_TOKEN{
BEGIN_OBJECT("{"), END_OBJECT("}"), BEGIN_ARRAY("["), END_ARRAY("]"), NULL("null"), NUMBER("number"),
STRING("str"), BOOLEAN("true/false"), SEP_COLON(":"), SEP_COMMA(","), END_DOCUMENT("");
/**Описание символа*/
@SuppressWarnings("unused")
private String help;
/**Номер перечисления, уникальный бит*/
int value;
JSON_TOKEN(String help) {this.help=help;value = 1 << this.ordinal();}
}
/**Возможные ошибки*/
public enum ERROR{
UNEXPECTED_CHAR,UNEXPECTED_TOKEN,UNEXPECTED_EXCEPTION,UNEXPECTED_VALUE,UNKNOW
}
/**Один прочитанный токен из потока*/
private class Token{
public Token(JSON.JSON_TOKEN type, Object value) {
this.type=type;
this.value=value;
}
public JSON_TOKEN type;
public Object value;
public String toString() {return type + " " + value;}
}
/**Чтец токенов*/
private class TokenReader {
/**Поток, из которого читаем*/
Reader stream;
/**Текущая позиция чтения*/
long pos = 0;
/**Последний символ, который прочитали из потока*/
char lastChar;
/**Сдвинули каретку назад, то есть в следующий раз получим предыдущий символ*/
boolean isBack = false;
public TokenReader(Reader in) {
stream=in;
}
/**
* Вычитывает следующий токен из входного потока
* @return
* @throws IOException
* @throws JSON.ParseException
*/
public JSON.Token next() throws IOException, JSON.ParseException {
char ch;
do {
if (!stream.ready())
return new Token(JSON_TOKEN.END_DOCUMENT, null);
ch = read();
}while(isWhiteSpace(ch));
switch (ch) { // Не пробел, а что?
case '{':
return new JSON.Token(JSON_TOKEN.BEGIN_OBJECT, null);
case '}':
return new Token(JSON_TOKEN.END_OBJECT, null);
case '[':
return new Token(JSON_TOKEN.BEGIN_ARRAY, null);
case ']':
return new Token(JSON_TOKEN.END_ARRAY, null);
case ',':
return new Token(JSON_TOKEN.SEP_COMMA, null);
case ':':
return new Token(JSON_TOKEN.SEP_COLON, null);
case 'n':
return readNull();
case 't':
case 'f':
return readBoolean(ch);
case '"':
return readString();
case '-':
return readNumber(ch);
}
if (isDigit(ch))
return readNumber(ch);
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
}
/**
* Читает число из входного потока
* @param ch - первое число, может быть числом, а может быть -
* @return
* @throws IOException
* @throws JSON.ParseException
*/
private JSON.Token readNumber(char ch) throws IOException, JSON.ParseException{
boolean isNegativ = ch == '-';
if(isNegativ) ch = read();
StringBuilder sb = new StringBuilder();
if(ch == '0') {
ch = read();
if(ch == '.') { //Десятичное число 0.ххх
if(isNegativ)
return new Token(JSON_TOKEN.NUMBER, -readFracAndExp(ch));
else
return new Token(JSON_TOKEN.NUMBER, readFracAndExp(ch));
}else { //Это просто нуль и ни чего более
back();
return new Token(JSON_TOKEN.NUMBER, 0);
}
} else if (isDigit(ch)) {
do {
sb.append(ch);
ch = read();
} while (isDigit(ch));
Long long_ = Long.parseLong(sb.toString());
if(ch == '.') { // Если это не число, то может точка?
Double val = long_.doubleValue() + readFracAndExp(ch);
return new Token(JSON_TOKEN.NUMBER, isNegativ ? -val: val);
} else {
back();
if(long_ < Integer.MAX_VALUE)
return new Token(JSON_TOKEN.NUMBER, isNegativ ? -long_.intValue() : long_.intValue());
else
return new Token(JSON_TOKEN.NUMBER, isNegativ ? -long_ : long_);
}
} else {
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
}
}
/**
* Вычитывает число с плавающей точкой. Но только дробную часть!
* @return
*/
private Double readFracAndExp(char ch) throws IOException, JSON.ParseException{
StringBuilder sb = new StringBuilder();
sb.append('0');
if (ch == '.') {
sb.append(ch);
ch = read();
if (!isDigit(ch))
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
do {
sb.append(ch);
ch = read();
} while (isDigit(ch));
if (isExp(ch)) { // А вдруг это экспонента?
sb.append(ch);
sb.append(readExp().toString());
} else {
back(); // А мы хз что это, не к нам
}
} else {
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
}
return Double.parseDouble(sb.toString());
}
/**
* Читает из потока экспоненту
* @return Число, представляющще собой экспоненту
* @throws IOException
* @throws JSON.ParseException
*/
private Long readExp() throws IOException, JSON.ParseException {
StringBuilder sb = new StringBuilder();
char ch = read();
if (ch == '+' || ch == '-') {
sb.append(ch);
ch = read();
if (isDigit(ch)) {
do {
sb.append(ch);
ch = read();
} while (isDigit(ch));
back(); //Это не число, дальше мы всё
} else {
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
}
} else {
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
}
return Long.parseLong(sb.toString());
}
/**
* Вычитывает строку из потока
* @return
* @throws IOException
* @throws JSON.ParseException
*/
private JSON.Token readString() throws IOException, JSON.ParseException {
StringBuilder sb = new StringBuilder();
while (true) {
char ch = read();
if (ch == '\\') {
char escapeCh = read();
if (!isEscape(escapeCh))
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
sb.append('\\');
sb.append(ch);
if (ch == 'u') {
for (int i = 0; i < 4; i++) {
ch = read();
if (isHex(ch))
sb.append(ch);
else
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
}
}
} else if (ch == '"') {
return new Token(JSON_TOKEN.STRING, sb.toString());
} else if (ch == '\r' || ch == '\n') {
throw new ParseException(pos,ERROR.UNEXPECTED_CHAR,ch);
} else {
sb.append(ch);
}
}
}
/**
* Вычитывает значение true/false
* @param ch - первый символ слова true или false
* @return токен, который вычитает - Boolean
* @throws IOException
* @throws JSON.ParseException
*/
private JSON.Token readBoolean(char ch) throws IOException, JSON.ParseException {
if (ch == 't') {
char[] buf = new char[3];
pos += stream.read(buf);
if (!(buf[0] == 'r' && buf[1] == 'u' && buf[2] == 'e'))
throw new ParseException(pos,ERROR.UNEXPECTED_VALUE,"t" + buf[0] + buf[1] + buf[2]);
else
return new Token(JSON_TOKEN.BOOLEAN, Boolean.valueOf(true));
} else {
char[] buf = new char[4];
pos += stream.read(buf);
if (!(buf[0] == 'a' && buf[1] == 'l' && buf[2] == 's' && buf[3] == 'e'))
throw new ParseException(pos,ERROR.UNEXPECTED_VALUE,"f" + buf[0] + buf[1] + buf[2] + buf[3]);
else
return new Token(JSON_TOKEN.BOOLEAN, Boolean.valueOf(false));
}
}
/**
* Вычитывает значение null
* @return токен, который вычитает - токен null
* @throws IOException
* @throws JSON.ParseException
*/
private JSON.Token readNull() throws IOException, JSON.ParseException {
char[] buf = new char[3];
pos += stream.read(buf);
if (!(buf[0] == 'u' && buf[1] == 'l' && buf[2] == 'l'))
throw new ParseException(pos,ERROR.UNEXPECTED_VALUE,"n" + buf[0] + buf[1] + buf[2]);
else
return new Token(JSON_TOKEN.NULL, "null");
}
/**Првоеряет, что символ является числом*/
private boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
/**
* Проверяет, что символ относится к экспоненциальной записи числа
* @param ch
* @return
* @throws IOException
*/
private boolean isExp(char ch) {
return ch == 'e' || ch == 'E';
}
/**
* Проверяет, что символ относится к хексам
* @param ch
* @return
*/
private boolean isHex(char ch) {
return ((ch >= '0' && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'));
}
/**Проверяет, что у нас один из экранированных символов - " \ n r...*/
private boolean isEscape(char ch) {
return (ch == '"' || ch == '\\' || ch == 'u' || ch == 'r' || ch == 'n' || ch == 'b' || ch == 't' || ch == 'f');
}
/**
* Показывает, является-ли введённый символ пробелом (таблом, ентером и т.д.)
* @param ch
* @return
*/
private boolean isWhiteSpace(char ch) {
return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n');
}
/**
* Показывает, можно-ли ещё вычитать из буфера что либо
* @return
*/
public boolean hasNext() {
try {
return stream.ready();
} catch (IOException e) {
return false;
}
}
/**
* Читает символ из потока. Запоминает прочитанный символ во временный буфер
* @return
* @throws IOException
*/
private char read() throws IOException {
if(!isBack)
lastChar = (char) stream.read();
else
isBack = false;
pos++;
return lastChar;
}
/**Сдвинуть курсор чтения на одну позицию назад*/
private void back() {isBack = true;pos--;};
}
/**
* Разные ошибки, возникающие при парсинге файла
*
*/
public class ParseException extends Exception {
private ERROR errorType;
private Object unexpectedObject;
private long position;
public ParseException(long position, ERROR errorType, Object unexpectedObject) {
this.position = position;
this.errorType = errorType;
this.unexpectedObject = unexpectedObject;
}
public ERROR getErrorType() {
return errorType;
}
/**
* @see org.json.simple.parser.JSONParser#getPosition()
*
* @return The character position (starting with 0) of the input where the error
* occurs.
*/
public long getPosition() {
return position;
}
/**
* @see org.json.simple.parser.JSONtoken
*
* @return One of the following base on the value of errorType:
* ERROR_UNEXPECTED_CHAR java.lang.Character ERROR_UNEXPECTED_TOKEN
* org.json.simple.parser.JSONtoken ERROR_UNEXPECTED_EXCEPTION
* java.lang.Exception
*/
public Object getUnexpectedObject() {
return unexpectedObject;
}
public String getMessage() {
StringBuffer sb = new StringBuffer();
switch (errorType) {
case UNEXPECTED_CHAR:
sb.append("Неожиданный символ '").append(unexpectedObject).append("' в позиции ").append(position)
.append(".");
break;
case UNEXPECTED_TOKEN:
sb.append("Неожиданный токен '").append(unexpectedObject).append("' в позиции ").append(position)
.append(".");
break;
case UNEXPECTED_EXCEPTION:
sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
break;
case UNEXPECTED_VALUE:
sb.append("Неожиданное значение в позиции ").append(position).append(": ").append(unexpectedObject);
break;
default:
sb.append("Неизвестная ошибка в позиции ").append(position).append(".");
break;
}
return sb.toString();
}
}
/**Интерфейс для любого параметра JSON*/
private interface JSON_par{
public void write(Writer writer, String tabs) throws IOException;
}
/**Специальный класс, который хранит только значение*/
private class JSON_O<T> implements JSON_par{
/**Вариант, когда значение - простой тип*/
T value_o = null;
/**
* Создаёт параметр
* @param value - значение
*/
public JSON_O(T value) {
this.value_o = value;
}
/**
* Записывает красиво форматированный объект в поток.
* @param writer - цель, куда записывается объект
* @param tabs - специальная переменная, позволяет сделать красивое форматирование.
* Если она null, то форматирования не будет
* @throws IOException - следует учитывать возможность выброса исключения при работе с файлом
*/
public void write(Writer writer, String tabs) throws IOException {
if (value_o != null && value_o instanceof JSON) {
if (tabs != null) {
writer.write("\n");
((JSON) value_o).toBeautifulJSONString(writer, tabs);
writer.write("\n" + tabs);
} else {
((JSON) value_o).toBeautifulJSONString(writer, null);
}
} else if(value_o != null) {
writer.write(getVal(value_o));
} else {
writer.write("null");
}
}
private String getVal(T value_o) {
if(value_o instanceof String) {
return "\"" + value_o.toString().replaceAll("\"", "\\\\\"") + "\"";
}else {
return value_o.toString();
}
}
public String toString() {
return value_o != null ? value_o.toString() : "null";
}
}
/**Специальный класс, который хранит только список значений*/
private class JSON_A<T> implements JSON_par{
/**Массив простых типов*/
List<T> value_mo = null;
/**
* Создаёт параметр
* @param value - значение
*/
public JSON_A(List<T> value) {
this.value_mo = value;
}
public JSON_A(T[] value) {
this(Arrays.asList(value));
}
/**
* Создаёт параметр из массива примитивов
* Не проивзодится проверка на null,
* тот факт, что T - примитивный тип
* Всё это может вызвать ошибки!
* @param value - значение
*/
@SuppressWarnings("unchecked")
public JSON_A(T value) {
final int length = java.lang.reflect.Array.getLength(value);
if(length == 0) {
this.value_mo = new ArrayList<>();
}else {
final Object first = java.lang.reflect.Array.get(value, 0);
Object[] arr = (Object[]) java.lang.reflect.Array.newInstance(first.getClass(), length);
arr[0] = first;
for (int i = 1; i < length; i++)
arr[i] = java.lang.reflect.Array.get(value, i);
this.value_mo = (List<T>) Arrays.asList(arr);
}
}
/**
* Записывает красиво форматированный объект в поток.
* @param writer - цель, куда записывается объект
* @param tabs - специальная переменная, позволяет сделать красивое форматирование.
* Если она null, то форматирования не будет
* @throws IOException - следует учитывать возможность выброса исключения при работе с файлом
*/
public void write(Writer writer, String tabs) throws IOException {
if(value_mo != null && !value_mo.isEmpty() && value_mo.get(0) instanceof JSON) {
writer.write("[");
if (tabs != null)
writer.write("\n");
boolean isFirst = true;
for(T i : value_mo) {
if(isFirst)
isFirst = false;
else if (tabs != null)
writer.write(",\n");
else
writer.write(",");
if (tabs != null) {
writer.write(tabs + "\t");
((JSON) i).toBeautifulJSONString(writer, tabs + "\t");
} else {
((JSON) i).toBeautifulJSONString(writer, null);
}
}
if (tabs != null)
writer.write("\n" + tabs + "]");
else
writer.write("]");
} else if(value_mo != null) {
StringBuilder vals = new StringBuilder();
for (T i : value_mo) {
if (!vals.isEmpty())
vals.append(",");
vals.append(getVal(i));
}
writer.write("[" + vals + "]");
} else {
writer.write("[]");
}
}
private String getVal(T value_o) {
if(value_o instanceof String) {
return "\"" + value_o.toString().replaceAll("\"", "\\\\\"") + "\"";
}else {
return value_o.toString();
}
}
public String toString() {
return value_mo != null ? value_mo.toString() : "null";
}
}
/**Это список всех параметров объекта. Используется лист пар потому что было важное условие - сохранить порядок данных*/
private LinkedHashMap<String,JSON_par> parametrs;
/**
* Создаёт объект JSON в который будут заносится значения для серелизации
*/
public JSON(){
parametrs = new LinkedHashMap<>();
}
/**Парсинг JSON строки и заполнение соответствующих объектов
* @throws JSON.ParseException
* @throws IOException */
public JSON(String parseStr) throws JSON.ParseException, IOException {
this(new StringReader(parseStr));
}
/**Парсинг JSON потока и заполнение соответствующих объектов
* @throws JSON.ParseException
* @throws IOException */
public JSON(Reader parseStr) throws JSON.ParseException, IOException {
parametrs = parse(parseStr).parametrs;
}
/**
* Разбирает поток в формат JSON
* @param in
* @return
* @throws JSON.ParseException
* @throws IOException
*/
public JSON parse(Reader in) throws IOException, JSON.ParseException{
TokenReader reader = new TokenReader(in);
if(!reader.hasNext()) { // Пустой файл
return new JSON();
}else {
Token token = reader.next();
if(token.type == JSON_TOKEN.BEGIN_OBJECT)
return parseO(reader);
else
throw new ParseException(reader.pos, ERROR.UNEXPECTED_TOKEN, token.value);
}
}
/**
* Парсит объект JSON, первый символ { уже получили
* @param reader
* @return
* @throws JSON.ParseException
* @throws IOException
*/
private JSON parseO(JSON.TokenReader reader) throws JSON.ParseException, IOException {
JSON json = new JSON();
int expectToken = JSON_TOKEN.STRING.value | JSON_TOKEN.END_OBJECT.value; // Ключ или конец объекта
String key = null;
JSON_TOKEN lastToken = JSON_TOKEN.BEGIN_OBJECT;
while (reader.hasNext()) {
Token token = reader.next();
if ((expectToken & token.type.value) == 0)
throw new ParseException(reader.pos, ERROR.UNEXPECTED_TOKEN, token.type);
switch (token.type) {
case BEGIN_ARRAY:
json.add(key, parseA(reader));
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_OBJECT.value; // Или следующий объект или мы всё
break;
case BEGIN_OBJECT:
json.add(key, parseO(reader));
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_OBJECT.value; // Или следующий объект или мы всё
break;
case END_ARRAY:
break;
case END_DOCUMENT: // Этого мы ни когда не ждём!
throw new ParseException(reader.pos, ERROR.UNEXPECTED_EXCEPTION, "Неожиданный конец документа");
case END_OBJECT:
return json; //Мы всё!
case NULL:
json.add(key, (Object) null);
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_OBJECT.value; // Или следующий объект или мы всё
break;
case BOOLEAN:
case NUMBER:
json.add(key, token.value);
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_OBJECT.value; // Или следующий объект или мы всё
break;
case SEP_COLON:
expectToken = JSON_TOKEN.NULL.value | JSON_TOKEN.NUMBER.value | JSON_TOKEN.BOOLEAN.value
| JSON_TOKEN.STRING.value | JSON_TOKEN.BEGIN_OBJECT.value | JSON_TOKEN.BEGIN_ARRAY.value; // А дальше значение ждём!
break;
case SEP_COMMA:
expectToken = JSON_TOKEN.STRING.value; // Теперь снова ключ
break;
case STRING:
if(lastToken == JSON_TOKEN.SEP_COLON) { // Если у нас было :, то мы просто значение
json.add(key, token.value);
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_OBJECT.value; // Или следующий объект или мы всё
} else { //А раз нет - то мы ключ
key = (String) token.value;
expectToken = JSON_TOKEN.SEP_COLON.value; // А дальше значение ждём!
}
break;
}
lastToken = token.type;
}
throw new ParseException(reader.pos, ERROR.UNEXPECTED_EXCEPTION, "Неожиданный конец документа");
}
/**
* Парсит массив JSON, первый символ [ уже получили
* @param reader
* @return
* @throws JSON.ParseException
* @throws IOException
*/
private List<Object> parseA(JSON.TokenReader reader) throws JSON.ParseException, IOException {
List<Object> array = new ArrayList<>();
int expectToken = JSON_TOKEN.BEGIN_ARRAY.value | JSON_TOKEN.END_ARRAY.value | JSON_TOKEN.BEGIN_OBJECT.value
| JSON_TOKEN.NUMBER.value | JSON_TOKEN.BOOLEAN.value | JSON_TOKEN.STRING.value | JSON_TOKEN.NULL.value; // Массив чего у нас там?
Object sample = null;
while (reader.hasNext()) {
Token token = reader.next();
if ((expectToken & token.type.value) == 0)
throw new ParseException(reader.pos, ERROR.UNEXPECTED_TOKEN, token.value);
switch (token.type) {
case BEGIN_ARRAY:
if(sample == null || sample instanceof List) {
sample = parseA(reader);
array.add(sample);
} else {
throw new ParseException(reader.pos, ERROR.UNKNOW, "Массив содержит значения разных типов");
}
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_ARRAY.value; // Или следующий объект или мы всё
break;
case BEGIN_OBJECT:
if(sample == null || sample instanceof JSON) {
sample = parseO(reader);
array.add(sample);
} else {
throw new ParseException(reader.pos, ERROR.UNKNOW, "Массив содержит значения разных типов");
}
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_ARRAY.value; // Или следующий объект или мы всё
break;
case END_ARRAY:
return array;
case END_OBJECT:
case SEP_COLON:
case END_DOCUMENT: // Этого мы ни когда не ждём!
throw new ParseException(reader.pos, ERROR.UNKNOW, "Ошибка библиотеки");
case NULL:
array.add((Object)null);
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_ARRAY.value; // Или следующий объект или мы всё
break;
case BOOLEAN:
case NUMBER:
case STRING:
if(sample == null || sample.getClass() == token.value.getClass()) {
sample = token.value;
array.add(sample);
} else {
throw new ParseException(reader.pos, ERROR.UNKNOW, "Массив содержит значения разных типов");
}
expectToken = JSON_TOKEN.SEP_COMMA.value | JSON_TOKEN.END_ARRAY.value; // Или следующий объект или мы всё
break;
case SEP_COMMA:
expectToken = JSON_TOKEN.NULL.value | JSON_TOKEN.NUMBER.value | JSON_TOKEN.BOOLEAN.value
| JSON_TOKEN.STRING.value | JSON_TOKEN.BEGIN_OBJECT.value | JSON_TOKEN.BEGIN_ARRAY.value; // А дальше значение ждём!
break;
}
}
throw new ParseException(reader.pos, ERROR.UNEXPECTED_EXCEPTION, "Неожиданный конец документа");
}
/**
* Добавить новую пару ключ-значение в объект.
* Поддерживает не только добавление простых значений,
* но и векторов простых типов!
* @param key - ключ
* @param value - значение
*/
public <T> void add(String key, T value) {
if(value.getClass().isArray()) // Массивы
parametrs.put(key, new JSON_A<T>(value));
else
parametrs.put(key, new JSON_O<T>(value));
}
/**
* Добавить новую пару ключ-значение в объект
* @param key - ключ
* @param value - значение
*/
public <T> void add(String key, T[] value) {
parametrs.put(key, new JSON_A<T>(value));
}
/**
* Добавить новую пару ключ-значение в объект
* @param key - ключ
* @param value - значение
*/
public <T> void add(String key, List<T> value) {
parametrs.put(key, new JSON_A<T>(value));
}
/**
* Получает любые векторные значения по ключу
* @param key - ключ
* @return - значение, или null, если значение не найдено
*/
@SuppressWarnings("unchecked")
public <T> List<T> getA(String key) {
var par = parametrs.get(key);
if (par instanceof JSON_A)
return ((JSON_A<T>) par).value_mo;
else
return null;
}
/**
* Получает любые векторные значения по ключу
* @param key - ключ
* @return - значение, или null, если значение не найдено
*/
public List<JSON> getAJ(String key) {
return getA(key);
}
/**
* Получает значение по ключу
* @param key - ключ
* @return - значение, или null, если значение не найдено
*/
public JSON getJ(String key) {
return get(key);
}
/**
* Получает значение по ключу. Заглушка, потому что во
* время исполнения не определить запрашиваемый тип
* @param key - ключ
* @return - значение, или null, если значение не найдено
*/
public Integer getI(String key) {
Number val = get(key);
if(val == null) return null;
if (val instanceof Integer) {
return (Integer) val;
}else if (val instanceof Long) {
return ((Long) val).intValue();
}else {
return null;
}
}
/**
* Получает значение по ключу. Заглушка, потому что во
* время исполнения не определить запрашиваемый тип
* @param key - ключ
* @return - значение, или null, если значение не найдено
*/
public Long getL(String key) {
Number val = get(key);
if(val == null) return null;
if (val instanceof Long) {
return (Long) val;
}else if (val instanceof Integer) {
return ((Integer) val).longValue();
}else {
return null;
}
}
/**
* Получает значение по ключу
* @param key - ключ
* @return - значение, или null, если значение не найдено
*/
@SuppressWarnings("unchecked")
public <T> T get(String key) {
var par = parametrs.get(key);
if (par instanceof JSON_O) {
return ((JSON_O<T>) par).value_o;
}else {
return null;
}
}
/**
* Приводит JSON объект к строке
* @return Одна простая и длинная строка без форматирвоания
*/
public String toJSONString() {
StringWriter sw = new StringWriter();
try {
toJSONString(sw);
} catch (IOException e) {} // Быть такого не может! Не должен SW давать ошибки IO
return sw.toString();
}
/**
* Приводит JSON объект к строке - простой и длинной строке без форматирвоания.
* И дописывает её в конец
* @throws IOException
*/
public void toJSONString(Writer writer) throws IOException {
toBeautifulJSONString(writer,null);
}
/**
* Приводит JSON объект к строке
* @return строка, форматированная согласно правилам составления JSON объектов, с табами и подобным
*/
public String toBeautifulJSONString() {
StringWriter sw = new StringWriter();
try {
toBeautifulJSONString(sw);
} catch (IOException e) {}
return sw.toString();
}
/**
* Приводит JSON объект к строке, форматированной согласно правилам составления JSON объектов, с табами и подобным.
* Дописывает в конец документа
* @throws IOException
*/
public void toBeautifulJSONString(Writer writer) throws IOException {
toBeautifulJSONString(writer,"");
}
/**Внутренний метод для печати объекта. Объект состоит из открывающей табы ну и дальше по тексту*/
private void toBeautifulJSONString(Writer writer,String tabs) throws IOException {
writer.write("{");
if(tabs != null)
writer.write("\n");
boolean isFirst = true;
for (Entry<String, JSON.JSON_par> param : parametrs.entrySet()) {
if(isFirst)
isFirst = false;
else if(tabs != null)
writer.write(",\n");
else
writer.write(",");
if(tabs != null) {
writer.write(tabs + "\t");
writer.write("\"" + param.getKey() + "\": ");
param.getValue().write(writer, tabs + "\t");
} else {
writer.write("\"" + param.getKey() + "\":");
param.getValue().write(writer, null);
}
}
if(tabs != null)
writer.write("\n" + tabs);
writer.write("}");
}
public String toString() {
return toJSONString();
}
public boolean containsKey(String key) {
return parametrs.containsKey(key);
}
}
| 30.338565 | 134 | 0.643818 |
3c5eb0779c873e1e09378d2281a440610191a524 | 2,090 | package de.katzenpapst.amunra.world.neper;
import java.util.List;
import cpw.mods.fml.common.registry.GameRegistry;
import de.katzenpapst.amunra.block.ARBlocks;
import de.katzenpapst.amunra.world.AmunraBiomeDecorator;
import de.katzenpapst.amunra.world.WorldGenOre;
import micdoodle8.mods.galacticraft.api.prefab.core.BlockMetaPair;
import net.minecraft.init.Blocks;
import net.minecraft.world.gen.feature.WorldGenTallGrass;
import net.minecraft.world.gen.feature.WorldGenerator;
public class NeperBiomeDecorator extends AmunraBiomeDecorator {
protected WorldGenerator grassGen = new WorldGenTallGrass(Blocks.tallgrass, 1);
private int grassPerChunk = 10;
@Override
protected List<WorldGenOre> getOreGenerators()
{
BlockMetaPair stone = new BlockMetaPair(Blocks.stone, (byte) 0);
List<WorldGenOre> list = super.getOreGenerators();
list.add(new WorldGenOre(new BlockMetaPair(Blocks.diamond_ore, (byte) 0), 4, stone, 8, 0, 12));
list.add(new WorldGenOre(new BlockMetaPair(Blocks.emerald_ore, (byte) 0), 4, stone, 4, 8, 32));
list.add(new WorldGenOre(new BlockMetaPair(Blocks.iron_ore, (byte) 0), 8, stone, 16, 2, 70));
list.add(new WorldGenOre(new BlockMetaPair(Blocks.gold_ore, (byte) 0), 8, stone, 8, 2, 40));
list.add(new WorldGenOre(new BlockMetaPair(GameRegistry.findBlock("MorePlanet", "polongnius_block"), (byte) 9), 10, stone, 4, 2, 32));
list.add(new WorldGenOre(ARBlocks.blockOldConcrete, 64, stone, 16, 30, 70));
list.add(new WorldGenOre(ARBlocks.oreSteelConcrete, 10, ARBlocks.blockOldConcrete, 16, 30, 70));
list.add(new WorldGenOre(ARBlocks.oreBoneConcrete, 6, ARBlocks.blockOldConcrete, 12, 30, 70));
return list;
}
@Override
protected void decorate() {
super.decorate();
for (int j = 0; j < this.grassPerChunk ; ++j)
{
int k = this.chunkX + this.mWorld.rand.nextInt(16) + 8;
int l = this.chunkZ + this.mWorld.rand.nextInt(16) + 8;
int i1 = mWorld.rand.nextInt(this.mWorld.getHeightValue(k, l) * 2);
grassGen.generate(this.mWorld, this.mWorld.rand, k, i1, l);
}
}
}
| 40.192308 | 136 | 0.729187 |
fb0c8c06d729bcb9a4e82f127f46d6035d78d3dc | 1,853 |
import com.github.newk5.flui.Alignment;
import com.github.newk5.flui.Color;
import com.github.newk5.flui.widgets.Canvas;
import com.github.newk5.flui.widgets.Label;
import com.github.newk5.flui.widgets.UI;
import com.github.newk5.flui.widgets.Window;
public class WindowWithAlignedCanvasTest {
public static void main(String[] args) {
UI.render(() -> {
new Window("w")
.width("100%").height("100%")
.children(
new Canvas("canv2")
.width("50%").height("50%")
.color(new Color(50, 20, 15, 255))
.align(Alignment.TOP_LEFT)
.children(
new Label("text")
.text("label")
.align(Alignment.CENTER)
),
new Canvas("canv3")
.width("50%").height("50%")
.color(new Color(15, 20, 100, 255))
.align(Alignment.TOP_RIGHT),
new Canvas("canv4")
.width("50%").height("50%")
.color(new Color(15, 100, 100, 255))
.align(Alignment.BOTTOM_LEFT),
new Canvas("canv5")
.width("50%").height("50%")
.color(new Color(150, 20, 100, 255))
.align(Alignment.BOTTOM_RIGHT)
);
});
}
}
| 44.119048 | 77 | 0.361576 |
b379b03a59e9eeb50ae072784883a58a377d4819 | 15,457 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.styling.util;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.actionSystem.Toggleable;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.vladsch.flexmark.util.misc.DelimitedBuilder;
import com.vladsch.md.nav.actions.handlers.util.CaretContextInfo;
import com.vladsch.md.nav.settings.MdApplicationSettings;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Consumer;
public class DisabledConditionBuilder {
public static final String ORIGINAL_TOOLTIP = "MARKDOWN_NAVIGATOR_ORIGINAL_TOOLTIP";
private final AnActionEvent myEvent;
private final Presentation myPresentation;
private final AnAction myAction;
private final String myPlace;
private final String myOriginalText;
private final DelimitedBuilder myBuilder;
private boolean myEnabled;
private boolean mySelected;
private boolean myMenuAction;
public DisabledConditionBuilder(AnActionEvent event, AnAction action) {
this(event, action, !event.getPlace().equals(ActionPlaces.EDITOR_TOOLBAR));
}
public boolean isMenuAction() {
return myMenuAction;
}
private DisabledConditionBuilder(AnActionEvent event, AnAction action, boolean inMenuAction) {
myEvent = event;
myPresentation = myEvent.getPresentation();
myMenuAction = inMenuAction || !event.isFromActionToolbar();
String originalTooltip = (String) myPresentation.getClientProperty(ORIGINAL_TOOLTIP);
if (originalTooltip == null) {
originalTooltip = myPresentation.getText();
myPresentation.putClientProperty(ORIGINAL_TOOLTIP, originalTooltip != null ? originalTooltip : "");
}
myAction = action;
myPlace = event.getPlace();
myOriginalText = originalTooltip;
myBuilder = new DelimitedBuilder(myMenuAction ? ", " : "");
myEnabled = true;
mySelected = false;
myBuilder.append(myOriginalText);
myBuilder.append(myMenuAction ? " (" : ", disabled by:<ul style='margin:0 0 0 20'>");
if (!myMenuAction) myBuilder.mark();
}
public DisabledConditionBuilder notNull(Object object, CharSequence elementName) {
return notNull(object, elementName, false, null);
}
public DisabledConditionBuilder notNull(Object object, CharSequence elementName, final boolean fullMessage, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
if (object == null) {
myEnabled = false;
if (!myMenuAction) myBuilder.append("<li style='margin-top:0;margin-bottom:0'>");
if (fullMessage) {
myBuilder.append(elementName);
} else {
myBuilder.append(elementName).append(" is null");
}
if (!myMenuAction) myBuilder.append("</li>");
myBuilder.mark();
} else {
if (runnable != null) {
runnable.accept(this);
}
}
return this;
}
public boolean isSelected() {
return mySelected;
}
public void setSelected(final boolean selected) {
mySelected = selected;
}
public DisabledConditionBuilder menuAction() {
myMenuAction = true;
return this;
}
public DisabledConditionBuilder notNull(Project object) {
return notNull(object, (Consumer<? super DisabledConditionBuilder>) null);
}
public DisabledConditionBuilder notNull(Project object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
return notNull(object, "Project", false, runnable);
}
public DisabledConditionBuilder notNull(Editor object) {
return notNull(object, (Consumer<? super DisabledConditionBuilder>) null);
}
public DisabledConditionBuilder notNull(Editor object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
return notNull(object, "Editor is not showing", true, runnable);
}
public DisabledConditionBuilder notNull(FileEditor object) {
return notNull(object, (Consumer<? super DisabledConditionBuilder>) null);
}
public DisabledConditionBuilder notNull(FileEditor object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
return notNull(object, "FileEditor is not showing", true, runnable);
}
public DisabledConditionBuilder notNull(PsiFile object) {
return notNull(object, (Consumer<? super DisabledConditionBuilder>) null);
}
public DisabledConditionBuilder notNull(PsiFile object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
return notNull(object, "PsiFile", false, runnable);
}
public DisabledConditionBuilder notNull(VirtualFile object) {
return notNull(object, (Consumer<? super DisabledConditionBuilder>) null);
}
public DisabledConditionBuilder notNull(VirtualFile object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
return notNull(object, "File", false, runnable);
}
public DisabledConditionBuilder notNull(CaretContextInfo object) {
return notNull(object, (Consumer<? super DisabledConditionBuilder>) null);
}
public DisabledConditionBuilder notNull(CaretContextInfo object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
return and(object != null, "caret context not found, editor is not showing", runnable);
}
public DisabledConditionBuilder isValid(PsiFile object) {
return isValid(object, null);
}
public DisabledConditionBuilder isValid(PsiFile object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
notNull(object, "PsiFile");
if (object != null) {
boolean valid = object.isValid();
and(valid, "PsiFile is not valid");
and(runnable);
}
return this;
}
public DisabledConditionBuilder isValid(VirtualFile object) {
return isValid(object, null);
}
public DisabledConditionBuilder isValid(VirtualFile object, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
notNull(object, "VirtualFile");
if (object != null) {
boolean valid = object.isValid();
and(valid, "VirtualFile is not valid");
and(runnable);
}
return this;
}
public DisabledConditionBuilder and(boolean predicate, CharSequence... disabledText) {
if (!predicate) {
myEnabled = false;
for (CharSequence text : disabledText) {
if (!myMenuAction) myBuilder.append("<li style='margin-top:0;margin-bottom:0'>");
myBuilder.append(text);
if (!myMenuAction) myBuilder.append("</li>");
myBuilder.mark();
}
}
return this;
}
public DisabledConditionBuilder and(boolean predicate, CharSequence disabledText, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
if (!predicate) {
myEnabled = false;
if (!myMenuAction) myBuilder.append("<li style='margin-top:0;margin-bottom:0'>");
myBuilder.append(disabledText);
if (!myMenuAction) myBuilder.append("</li>");
myBuilder.mark();
} else if (runnable != null) {
runnable.accept(this);
}
return this;
}
public DisabledConditionBuilder and(@Nullable Consumer<? super DisabledConditionBuilder> runnable) {
if (myEnabled && runnable != null) {
runnable.accept(this);
}
return this;
}
public DisabledConditionBuilder isVisible(@Nullable Editor editor) {
return and(editor != null && editor.getComponent().isVisible(), "Editor is not showing");
}
public DisabledConditionBuilder andSingleCaret(@Nullable final Editor editor) {
return andSingleCaret(editor, null);
}
public DisabledConditionBuilder andSingleCaret(@Nullable final Editor editor, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
if (editor != null) {
boolean predicate = editor.getCaretModel().getCaretCount() == 1;
and(predicate, "Multiple carets are not supported", runnable);
}
return this;
}
public DisabledConditionBuilder andNoSelection(@Nullable final Editor editor) {
return andNoSelection(editor, null);
}
public DisabledConditionBuilder andNoSelection(@Nullable final Editor editor, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
if (editor != null) {
boolean predicate = !editor.getSelectionModel().hasSelection();
and(predicate, "Selection(s) are not supported", runnable);
}
return this;
}
public DisabledConditionBuilder andSingleCaretOrNoSelection(@Nullable final Editor editor) {
return andSingleCaretOrNoSelection(editor, null);
}
public DisabledConditionBuilder andSingleCaretOrNoSelection(@Nullable final Editor editor, @Nullable Consumer<? super DisabledConditionBuilder> runnable) {
if (editor != null) {
boolean predicate = !editor.getSelectionModel().hasSelection() || editor.getCaretModel().getCaretCount() == 1;
and(predicate, "Selections with multiple carets are not supported", runnable);
}
return this;
}
public DisabledConditionBuilder enabledAnd(boolean predicate, CharSequence disabledText) {
if (myEnabled) {
and(predicate, disabledText);
}
return this;
}
public boolean isEnabled() {
return myEnabled;
}
public DisabledConditionBuilder done() {
return done(null, false);
}
public DisabledConditionBuilder done(boolean keepVisible) {
return done(keepVisible, false);
}
public DisabledConditionBuilder doneToggleable() {
return done(null, true);
}
public void doneToggleable(boolean keepVisible) {
done(keepVisible, true);
}
public DisabledConditionBuilder done(Boolean keepVisible, boolean toggleable) {
boolean showDisabledText = !myAction.displayTextInToolbar();
if (myEnabled) {
myPresentation.setText(myOriginalText);
myPresentation.setEnabled(true);
myPresentation.setVisible(true);
} else {
myBuilder.unmark().append(myMenuAction ? ")" : "</ul>");
if (!myMenuAction) myBuilder.mark();
if (showDisabledText) {
myPresentation.setText(myBuilder.toString(), false);
} else {
myPresentation.setText(myOriginalText);
}
myPresentation.setEnabled(false);
myPresentation.setVisible(keepVisible == null ? !MdApplicationSettings.getInstance().getDocumentSettings().getHideDisabledButtons() : keepVisible);
}
if (toggleable) myPresentation.putClientProperty(Toggleable.SELECTED_PROPERTY, mySelected);
return this;
}
@Override
public String toString() { return myBuilder.toString(); }
public String getAndClear() { return myBuilder.getAndClear(); }
public DisabledConditionBuilder clear() {
myBuilder.clear();
return this;
}
public String toStringOrNull() { return myBuilder.toStringOrNull(); }
public DisabledConditionBuilder mark() {
myBuilder.mark();
return this;
}
public DisabledConditionBuilder unmark() {
myBuilder.unmark();
return this;
}
public DisabledConditionBuilder push() {
myBuilder.push();
return this;
}
public DisabledConditionBuilder push(final String delimiter) {
myBuilder.push(delimiter);
return this;
}
public DisabledConditionBuilder pop() {
myBuilder.pop();
return this;
}
public DisabledConditionBuilder append(final char v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final int v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final boolean v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final long v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final float v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final double v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final String v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final String v, final int start, final int end) {
myBuilder.append(v, start, end);
return this;
}
public DisabledConditionBuilder append(final CharSequence v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final CharSequence v, final int start, final int end) {
myBuilder.append(v, start, end);
return this;
}
public DisabledConditionBuilder append(final char[] v) {
myBuilder.append(v);
return this;
}
public DisabledConditionBuilder append(final char[] v, final int start, final int end) {
myBuilder.append(v, start, end);
return this;
}
public <V> DisabledConditionBuilder appendAll(final V[] v) {
myBuilder.appendAll(v);
return this;
}
public <V> DisabledConditionBuilder appendAll(final V[] v, final int start, final int end) {
myBuilder.appendAll(v, start, end);
return this;
}
public <V> DisabledConditionBuilder appendAll(final String delimiter, final V[] v) {
myBuilder.appendAll(delimiter, v);
return this;
}
public <V> DisabledConditionBuilder appendAll(final String delimiter, final V[] v, final int start, final int end) {
myBuilder.appendAll(delimiter, v, start, end);
return this;
}
public <V> DisabledConditionBuilder appendAll(final List<? extends V> v) {
myBuilder.appendAll(v);
return this;
}
public <V> DisabledConditionBuilder appendAll(final List<? extends V> v, final int start, final int end) {
myBuilder.appendAll(v, start, end);
return this;
}
public <V> DisabledConditionBuilder appendAll(final String delimiter, final List<? extends V> v) {
myBuilder.appendAll(delimiter, v);
return this;
}
public <V> DisabledConditionBuilder appendAll(
final String delimiter,
final List<? extends V> v,
final int start,
final int end
) {
myBuilder.appendAll(delimiter, v, start, end);
return this;
}
}
| 34.813063 | 177 | 0.663971 |
2b002549f8d75c6749b6df45365c58165f78eefc | 4,718 | package ru.zav.storedbooksinfo.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.zav.storedbooksinfo.dao.BookRepository;
import ru.zav.storedbooksinfo.dao.GenreRepository;
import ru.zav.storedbooksinfo.domain.Genre;
import ru.zav.storedbooksinfo.utils.AppDaoException;
import ru.zav.storedbooksinfo.utils.AppServiceException;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
@RequiredArgsConstructor
public class GenreServiceImpl implements GenreService {
private final GenreRepository genreRepository;
private final BookRepository bookRepository;
@Override
public Genre add(String genreDescription) {
if(StringUtils.isBlank(genreDescription)) throw new AppServiceException("Ошибка! Не указан Description для добавляемого жанра.");
try {
final Optional<Genre> genreOptional = genreRepository.findByDescription(genreDescription);
return genreOptional.orElseGet(() -> genreRepository.save(new Genre(null, StringUtils.trim(genreDescription))));
} catch (AppDaoException e) {
throw new AppServiceException(e.getMessage(), e);
}
}
@Override
public int delete(String genreDescription) {
if(StringUtils.isBlank(genreDescription)) throw new AppServiceException("Ошибка! Не указан Description для удаляемого жанра.");
final String genreDescriptionTrimmed = StringUtils.trim(genreDescription);
final Optional<Genre> genreOptional;
try {
genreOptional = genreRepository.findByDescription(genreDescriptionTrimmed);
} catch (AppDaoException e) {
throw new AppServiceException(e.getMessage(), e);
}
return genreOptional.filter(genre -> {
try {
return !isUsed(genre);
} catch (AppServiceException e) {
log.error(e.getLocalizedMessage());
}
return false;
})
.map(Genre::getId)
.map(id -> {
try {
genreRepository.deleteById(id);
return 1;
} catch (EmptyResultDataAccessException e) {
log.error(e.getLocalizedMessage());
}
return 0;
})
.orElse(0);
}
@Override
public Genre rename(String oldDescription, String newDescription) {
if(StringUtils.isBlank(oldDescription) || StringUtils.isBlank(newDescription)) throw new AppServiceException("Ошибка! Не указан Description для переименования жанра.");
final String oldDescriptionTrimmed = StringUtils.trim(oldDescription);
final String newDescriptionTrimmed = StringUtils.trim(newDescription);
final Optional<Genre> genreOptional;
try {
genreOptional = genreRepository.findByDescription(oldDescriptionTrimmed);
} catch (AppDaoException e) {
throw new AppServiceException(e.getMessage(), e);
}
Genre updatedGenre = genreOptional.map(genre -> {
try {
return genreRepository.save(new Genre(genre.getId(), newDescriptionTrimmed));
} catch (AppDaoException e) {
log.error(e.getLocalizedMessage());
}
return genre;
})
.orElseThrow(() -> new AppServiceException(String.format("Не удалось найти жанр по названию: %s", oldDescriptionTrimmed)));
if(!updatedGenre.getDescription().equals(newDescriptionTrimmed)) throw new AppServiceException(String.format("Не удалось переименовать жанр %s в %s", oldDescriptionTrimmed, newDescriptionTrimmed));
return updatedGenre;
}
@Override
public List<Genre> getAll() {
try {
return genreRepository.findAll();
} catch (AppDaoException e) {
throw new AppServiceException(e.getMessage(), e);
}
}
@Override
public Optional<Genre> findByDescription(String description) {
try {
return genreRepository.findByDescription(description);
} catch (AppDaoException e) {
throw new AppServiceException(e.getMessage(), e);
}
}
private boolean isUsed(Genre genre) {
try {
return !bookRepository.findByGenre(genre).isEmpty();
} catch (AppDaoException e) {
throw new AppServiceException(e.getMessage(), e);
}
}
}
| 37.444444 | 205 | 0.653879 |
8d5ede983151f1c7e0ed4c8a5cbb09255341a351 | 5,644 | package com.starrocks.connector.datax.plugin.writer.starrockswriter;
import java.io.Serializable;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.plugin.rdbms.util.DBUtilErrorCode;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StarRocksWriterOptions implements Serializable {
private static final long serialVersionUID = 1l;
private static final long KILO_BYTES_SCALE = 1024l;
private static final long MEGA_BYTES_SCALE = KILO_BYTES_SCALE * KILO_BYTES_SCALE;
private static final int MAX_RETRIES = 1;
private static final int BATCH_ROWS = 500000;
private static final long BATCH_BYTES = 90 * MEGA_BYTES_SCALE;
private static final long FLUSH_INTERVAL = 300000;
private static final String KEY_LOAD_PROPS_FORMAT = "format";
public enum StreamLoadFormat {
CSV, JSON;
}
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_DATABASE = "database";
private static final String KEY_TABLE = "table";
private static final String KEY_COLUMN = "column";
private static final String KEY_PRE_SQL = "preSql";
private static final String KEY_POST_SQL = "postSql";
private static final String KEY_JDBC_URL = "jdbcUrl";
private static final String KEY_MAX_BATCH_ROWS = "maxBatchRows";
private static final String KEY_MAX_BATCH_SIZE = "maxBatchSize";
private static final String KEY_FLUSH_INTERVAL = "flushInterval";
private static final String KEY_LOAD_URL = "loadUrl";
private static final String KEY_FLUSH_QUEUE_LENGTH = "flushQueueLength";
private static final String KEY_LOAD_PROPS = "loadProps";
private final Configuration options;
private List<String> infoCchemaColumns;
private List<String> userSetColumns;
private boolean isWildcardColumn;
public StarRocksWriterOptions(Configuration options) {
this.options = options;
this.userSetColumns = options.getList(KEY_COLUMN, String.class).stream().map(str -> str.replace("`", "")).collect(Collectors.toList());
if (1 == options.getList(KEY_COLUMN, String.class).size() && "*".trim().equals(options.getList(KEY_COLUMN, String.class).get(0))) {
this.isWildcardColumn = true;
}
}
public void doPretreatment() {
validateRequired();
validateStreamLoadUrl();
}
public String getJdbcUrl() {
return options.getString(KEY_JDBC_URL);
}
public String getDatabase() {
return options.getString(KEY_DATABASE);
}
public String getTable() {
return options.getString(KEY_TABLE);
}
public String getUsername() {
return options.getString(KEY_USERNAME);
}
public String getPassword() {
return options.getString(KEY_PASSWORD);
}
public List<String> getLoadUrlList() {
return options.getList(KEY_LOAD_URL, String.class);
}
public List<String> getColumns() {
if (isWildcardColumn) {
return this.infoCchemaColumns;
}
return this.userSetColumns;
}
public boolean isWildcardColumn() {
return this.isWildcardColumn;
}
public void setInfoCchemaColumns(List<String> cols) {
this.infoCchemaColumns = cols;
}
public List<String> getPreSqlList() {
return options.getList(KEY_PRE_SQL, String.class);
}
public List<String> getPostSqlList() {
return options.getList(KEY_POST_SQL, String.class);
}
public Map<String, Object> getLoadProps() {
return options.getMap(KEY_LOAD_PROPS);
}
public int getMaxRetries() {
return MAX_RETRIES;
}
public int getBatchRows() {
Integer rows = options.getInt(KEY_MAX_BATCH_ROWS);
return null == rows ? BATCH_ROWS : rows;
}
public long getBatchSize() {
Long size = options.getLong(KEY_MAX_BATCH_SIZE);
return null == size ? BATCH_BYTES : size;
}
public long getFlushInterval() {
Long interval = options.getLong(KEY_FLUSH_INTERVAL);
return null == interval ? FLUSH_INTERVAL : interval;
}
public int getFlushQueueLength() {
Integer len = options.getInt(KEY_FLUSH_QUEUE_LENGTH);
return null == len ? 1 : len;
}
public StreamLoadFormat getStreamLoadFormat() {
Map<String, Object> loadProps = getLoadProps();
if (null == loadProps) {
return StreamLoadFormat.CSV;
}
if (loadProps.containsKey(KEY_LOAD_PROPS_FORMAT)
&& StreamLoadFormat.JSON.name().equalsIgnoreCase(String.valueOf(loadProps.get(KEY_LOAD_PROPS_FORMAT)))) {
return StreamLoadFormat.JSON;
}
return StreamLoadFormat.CSV;
}
private void validateStreamLoadUrl() {
List<String> urlList = getLoadUrlList();
for (String host : urlList) {
if (host.split(":").length < 2) {
throw DataXException.asDataXException(DBUtilErrorCode.CONF_ERROR,
"loadUrl的格式不正确,请输入 `fe_ip:fe_http_ip;fe_ip:fe_http_ip`。");
}
}
}
private void validateRequired() {
final String[] requiredOptionKeys = new String[]{
KEY_USERNAME,
KEY_DATABASE,
KEY_TABLE,
KEY_COLUMN,
KEY_LOAD_URL
};
for (String optionKey : requiredOptionKeys) {
options.getNecessaryValue(optionKey, DBUtilErrorCode.REQUIRED_VALUE);
}
}
}
| 33.005848 | 143 | 0.671687 |
0b9fd830bc7387c349115d00f6b9b0769eb44b6e | 9,502 | /**
*
*/
package org.opentravel.dex.controllers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opentravel.application.common.AbstractMainWindowController;
import org.opentravel.application.common.StatusType;
import org.opentravel.common.ImageManager;
import org.opentravel.dex.actions.DexFullActionManager;
import org.opentravel.dex.controllers.popup.DialogBoxContoller;
import org.opentravel.dex.events.DexEvent;
import org.opentravel.model.OtmModelManager;
import org.opentravel.objecteditor.UserSettings;
import org.opentravel.schemacompiler.repository.RepositoryManager;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.stage.Stage;
/**
* Abstract base controller for main controllers.
*
* @author dmh
*
*/
public abstract class DexMainControllerBase extends AbstractMainWindowController implements DexMainController {
private static Log log = LogFactory.getLog(DexMainControllerBase.class);
protected DexMainController mainController;
protected ImageManager imageMgr;
protected OtmModelManager modelMgr;
protected DexFullActionManager actionMgr;
// preferences (improve as i use it)
protected UserSettings userSettings;
protected List<DexIncludedController<?>> includedControllers = new ArrayList<>();
private Map<EventType<?>, List<DexIncludedController<?>>> eventPublishers = new HashMap<>();
private Map<EventType<?>, List<DexIncludedController<?>>> eventSubscribers = new HashMap<>();
protected DexStatusController statusController;
protected MenuBarWithProjectController menuBarController;
protected DialogBoxContoller dialogBoxController;
protected Stage stage;
public DexMainControllerBase() {
log.debug("Constructing controller.");
}
@Override
public void addIncludedController(DexIncludedController<?> controller) {
if (controller == null)
throw new IllegalStateException("Tried to add null Included controller");
controller.checkNodes();
includedControllers.add(controller);
controller.configure(this);
// Register any published event types
for (EventType et : controller.getPublishedEventTypes())
if (eventPublishers.containsKey(et)) {
eventPublishers.get(et).add(controller);
} else {
ArrayList<DexIncludedController<?>> list = new ArrayList<>();
list.add(controller);
eventPublishers.put(et, list);
}
// Register any subscribed event types
for (EventType et : controller.getSubscribedEventTypes())
if (eventSubscribers.containsKey(et)) {
eventSubscribers.get(et).add(controller);
} else {
ArrayList<DexIncludedController<?>> list = new ArrayList<>();
list.add(controller);
eventSubscribers.put(et, list);
}
}
@Override
public void clear() {
includedControllers.forEach(DexIncludedController::clear);
}
// /**
// * Use the subscribers and publishers maps to set handlers
// */
// // TODO - do i need subscriber map? Can i just traverse all included controllers?
// protected void configureEventHandlersX() {
// if (!eventSubscribers.isEmpty())
// for (Entry<EventType<?>, List<DexIncludedController<?>>> entry : eventSubscribers.entrySet())
// // For each subscriber to this event type
// for (DexIncludedController<?> c : entry.getValue()) {
// // Get the handler from the subscriber
// EventType<? extends DexEvent> et = (EventType<? extends DexEvent>) entry.getKey();
// // EventHandler<DexEvent> handler = c::handler;
// if (eventPublishers.containsKey(entry.getValue()))
// for (DexIncludedController<?> publisher : eventPublishers.get(entry.getValue()))
// // Put handler in all publishers of this event
// publisher.setEventHandler(et, c::handleEvent);
// }
// }
@SuppressWarnings("unchecked")
protected void configureEventHandlers() {
for (DexIncludedController<?> c : includedControllers) {
List<EventType> subscriptions = c.getSubscribedEventTypes();
if (subscriptions != null && !subscriptions.isEmpty())
for (EventType et : subscriptions)
if (eventPublishers.containsKey(et)) {
List<DexIncludedController<?>> publishers = eventPublishers.get(et);
EventType<? extends DexEvent> dexET = et;
for (DexIncludedController<?> publisher : publishers)
publisher.setEventHandler(dexET, c::handleEvent);
}
}
// if (!eventSubscribers.isEmpty())
// for (Entry<EventType<?>, List<DexIncludedController<?>>> entry : eventSubscribers.entrySet())
// // For each subscriber to this event type
// for (DexIncludedController<?> c : entry.getValue()) {
// // Get the handler from the subscriber
// EventType<? extends DexEvent> et = (EventType<? extends DexEvent>) entry.getKey();
// // EventHandler<DexEvent> handler = c::handler;
// if (eventPublishers.containsKey(entry.getValue()))
// for (DexIncludedController<?> publisher : eventPublishers.get(entry.getValue()))
// // Put handler in all publishers of this event
// publisher.setEventHandler(et, c::eventHandler);
// }
}
public DialogBoxContoller getDialogBoxController() {
if (dialogBoxController == null)
dialogBoxController = DialogBoxContoller.init();
return dialogBoxController;
}
@Override
public ImageManager getImageManager() {
if (imageMgr != null)
return imageMgr;
return mainController != null ? mainController.getImageManager() : null;
}
@Override
public OtmModelManager getModelManager() {
if (modelMgr != null)
return modelMgr;
return mainController != null ? mainController.getModelManager() : null;
}
@Override
public RepositoryManager getRepositoryManager() {
return null;
}
@Override
public Stage getStage() {
return stage;
}
// @Override
// public ReadOnlyObjectProperty<?> getSelectable() {
// return null;
// }
@Override
public DexStatusController getStatusController() {
if (statusController != null)
return statusController;
return mainController != null ? mainController.getStatusController() : null;
}
@Override
public UserSettings getUserSettings() {
return userSettings;
}
@FXML
@Override
public void initialize() {
log.debug("Initializing controller: " + this.getClass().getSimpleName());
}
@Override
public void postError(Exception e, String title) {
if (getDialogBoxController() != null)
if (e == null)
getDialogBoxController().show("", title);
else {
log.debug(title + e.getLocalizedMessage());
if (e.getCause() == null)
getDialogBoxController().show(title, e.getLocalizedMessage());
else
getDialogBoxController().show(title,
e.getLocalizedMessage() + " \n\n(" + e.getCause().toString() + ")");
}
else
log.debug("Missing dialog box to show: " + title);
}
@Override
public void postProgress(double percentDone) {
if (getStatusController() != null)
getStatusController().postProgress(percentDone);
}
@Override
public void postStatus(String string) {
if (getStatusController() != null)
getStatusController().postStatus(string);
}
@Override
public void refresh() {
includedControllers.forEach(DexIncludedController::refresh);
}
/**
* Set the stage for a top level main controller. Called by the application on startup. Initialize action, model and
* image managers. checkNodes().
*
* @param primaryStage
*/
public void setStage(Stage primaryStage) {
// These may be needed by sub-controllers
this.stage = primaryStage;
this.mainController = null;
// Initialize managers
actionMgr = new DexFullActionManager(this);
modelMgr = new OtmModelManager(actionMgr);
imageMgr = new ImageManager(primaryStage);
checkNodes();
}
/**
* Set the main controller field. Set model manager's status controller.
*
* @param controller
*/
protected void setMainController(DexMainController controller) {
mainController = controller;
modelMgr.setStatusController(getStatusController());
}
/**
* Create a main controller that has a main controller parent.
*
* @param parent
*/
public void setParent(DexMainController parent) {
this.stage = parent.getStage();
this.mainController = parent;
if (mainController.getImageManager() == null)
imageMgr = new ImageManager(stage);
}
// Required by AbstractApp...
@Override
protected void setStatusMessage(String message, StatusType statusType, boolean disableControls) {
if (getStatusController() != null)
getStatusController().postStatus(message);
}
@Override
public void updateActionQueueSize(int size) {
if (menuBarController != null)
menuBarController.updateActionQueueSize(size);
}
@Override
protected void updateControlStates() {
// Platform.runLater(() -> {
// // boolean exDisplayDisabled = (originalDocument == null);
// // boolean exControlsDisabled = (model == null) || (originalDocument == null);
// //
// // libraryText.setText( (modelFile == null) ? "" : modelFile.getName() );
// // libraryTooltip.setText( (modelFile == null) ? "" : modelFile.getAbsolutePath() );
// // exampleText.setText( (exampleFile == null) ? "" : exampleFile.getName() );
// // exampleTooltip.setText( (exampleFile == null) ? "" : exampleFile.getAbsolutePath() );
}
}
| 32.541096 | 118 | 0.705746 |
f0648036ba7934e24ed848a3e7f7ada478c6e872 | 1,227 | package com.lintcode;
/**
* @author : Joshua
* Date: 3/9/16
* @see <a href="http://www.lintcode.com/zh-cn/problem/merge-sorted-array-ii/">合并排序数组</a>
*/
public class MergeSortedArray {
/**
* @param A and B: sorted integer array A and B.
* @return: A new sorted integer array
*/
public int[] mergeSortedArray(int[] A, int[] B) {
// Write your code here
int i = 0;
int a = 0;
int b = 0;
int totalSize = A.length + B.length;
int[] result = new int[totalSize];
while (i < totalSize) {
if (a == A.length) {
result[i] = B[b];
b += 1;
i += 1;
continue;
}
if (b == B.length) {
result[i] = A[a];
a += 1;
i += 1;
continue;
}
if (A[a] <= B[b]) {
result[i] = A[a];
a += 1;
i += 1;
continue;
}
if (A[a] > B[b]) {
result[i] = B[b];
b += 1;
i += 1;
continue;
}
}
return result;
}
}
| 24.54 | 89 | 0.363488 |
dab6531d66ad7e66e0074b8da6092ffe578dd7b3 | 2,329 | package com.jia54321.utils.entity.rowmapper;
import com.jia54321.utils.entity.query.ITableDesc;
import org.easymock.EasyMock;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class AbstractRowMapperTest {
@Test
public void mapRow() throws SQLException {
AbstractRowMapper<ITableDesc> mapper = new AbstractRowMapper<ITableDesc>() {
};
//
ResultSetMetaData metaData = (ResultSetMetaData) EasyMock.createMock(ResultSetMetaData.class);
EasyMock.expect(metaData.getColumnCount()).andReturn(7).anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(1)).andReturn("TYPE_ID").anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(2)).andReturn("TYPE_ALIAS_ID").anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(3)).andReturn("TYPE_MK").anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(4)).andReturn("TYPE_ENTITY_NAME").anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(5)).andReturn("TYPE_DISPLAY_NAME").anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(6)).andReturn("TYPE_PK_NAME").anyTimes(); //期望使用参数
EasyMock.expect(metaData.getColumnName(7)).andReturn("TYPE_OPTS").anyTimes(); //期望使用参数
EasyMock.replay(metaData);//保存期望结果
ResultSet rs = (ResultSet) EasyMock.createMock(ResultSet.class);
EasyMock.expect(rs.getMetaData()).andReturn(metaData).anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(1)).andReturn("TYPE_ID").anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(2)).andReturn("TYPE_ALIAS_ID").anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(3)).andReturn("SYS").anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(4)).andReturn("USER").anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(5)).andReturn("TYPE_DISPLAY_NAME").anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(6)).andReturn("TYPE_PK_NAME").anyTimes(); //期望使用参数
EasyMock.expect(rs.getObject(7)).andReturn("10").anyTimes(); //期望使用参数
EasyMock.replay(rs);//保存期望结果
ITableDesc desc = (ITableDesc)mapper.mapRow(rs,1);
System.out.println(desc);
}
@Test
public void newInstance() {
}
} | 47.530612 | 104 | 0.693431 |
851f0550d0aaeeacda97fb3069b77b2b8abef57b | 1,415 | package tech.indicio.ariesmobileagentandroid.admin.credentials.eventRecords;
import com.google.gson.JsonObject;
import tech.indicio.ariesmobileagentandroid.admin.credentials.messages.CredentialReceivedMessage;
import tech.indicio.ariesmobileagentandroid.admin.credentials.offerObjects.CredentialAttribute;
import tech.indicio.ariesmobileagentandroid.connections.ConnectionRecord;
import tech.indicio.ariesmobileagentandroid.storage.BaseRecord;
public class AdminCredentialReceivedRecord extends BaseRecord {
public static final String type = "admin_credential_received_record";
public ConnectionRecord adminConnection;
public CredentialReceivedMessage messageObject;
public CredentialAttribute[] attributes;
public String connectionId;
public String credentialExchangeId;
public AdminCredentialReceivedRecord(CredentialReceivedMessage message, ConnectionRecord adminConnection) {
this.adminConnection = adminConnection;
this.messageObject = message;
this.attributes = message.credentialProposalDict.credentialProposal.attributes;
this.connectionId = message.connectionId;
this.id = message.id;
this.credentialExchangeId = message.credentialExchangeId;
this.tags = new JsonObject();
tags.addProperty("adminConnection", adminConnection.id);
}
@Override
public String getType() {
return type;
}
}
| 41.617647 | 111 | 0.790813 |
1716b11079ce834950655fa0b3013487b588eb7c | 5,396 | package gr.eap.dxt.backlog;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import gr.eap.dxt.R;
import gr.eap.dxt.persons.Person;
import gr.eap.dxt.sprints.Sprint;
import gr.eap.dxt.tools.AppShared;
import gr.eap.dxt.tools.Keyboard;
import gr.eap.dxt.tools.MyAlertDialog;
/**
* Created by GEO on 12/2/2017.
*/
public class BacklogDialogActivity extends Activity implements
BacklogShowFragment.FragmentInteractionListener,
BacklogEditFragment.FragmentInteractionListener{
/**
* Static content for input
*/
private static Backlog backlog;
public static void setStaticContent(Backlog _backlog){
clearStaticContent();
// Create a copy from this backlog, so if cancel the changes are only on the copy, not on the original person
backlog = Backlog.getCopy(_backlog);
}
private static void clearStaticContent(){
backlog = null;
}
/**
* End of static content
*/
private TextView myTitleTextView;
private ImageButton backButton;
private ImageButton saveButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_activity_backlog);
myTitleTextView = (TextView) findViewById(R.id.my_title_view);
backButton = (ImageButton) findViewById(R.id.back);
if (backButton != null){
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Keyboard.close(BacklogDialogActivity.this);
finish();
}
});
}
saveButton = (ImageButton) findViewById(R.id.save);
setDimensions();
if (savedInstanceState == null) {
goToBacklogShowFragment();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
clearStaticContent();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setDimensions();
}
private void setDimensions(){
if(getResources().getBoolean(R.bool.large_screen)){
DisplayMetrics metrics = getResources().getDisplayMetrics();
int height = (int) (metrics.heightPixels*0.8);
int width = (int) (metrics.widthPixels*0.8);
getWindow().setLayout(width,height);
return;
}
getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
}
private void goToBacklogShowFragment(){
setDimensions();
BacklogShowFragment fragment = BacklogShowFragment.newInstance(backlog, true);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
if (myTitleTextView != null){
String name = backlog != null ? backlog.getName() : null;
myTitleTextView.setText(name != null ? name : getString(R.string.backlog));
}
if (backButton != null){
backButton.setImageResource(R.drawable.ic_action_back);
}
if (saveButton != null){
saveButton.setVisibility(View.INVISIBLE);
}
}
private void goToBacklogEditFragment(Backlog mBacklog, Person person, Sprint sprint){
setDimensions();
final BacklogEditFragment fragment = BacklogEditFragment.newInstance(mBacklog, person, sprint, BacklogEditFragment.BacklogEditFrom.EDIT);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
if (myTitleTextView != null){
myTitleTextView.setText(R.string.edit);
}
if (backButton != null){
backButton.setImageResource(R.drawable.ic_action_not_ok);
}
if (saveButton != null){
saveButton.setVisibility(View.VISIBLE);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (fragment != null) fragment.saveChanges();
}
});
}
}
/** from {@link BacklogShowFragment.FragmentInteractionListener} */
@Override
public void onBacklogEdit(Backlog mBacklog, Person person, Sprint sprint) {
goToBacklogEditFragment(mBacklog, person, sprint);
}
/** from {@link BacklogEditFragment.FragmentInteractionListener} */
@Override
public void onBacklogChangesSaved(String errorMsg) {
if (errorMsg != null && !errorMsg.isEmpty()){
AppShared.writeErrorToLogString(getClass().toString(), errorMsg);
MyAlertDialog.alertError(this, null, errorMsg);
}else{
Intent data = new Intent();
data.putExtra(BacklogEditFragment.RELOAD, true);
setResult(Activity.RESULT_OK, data);
finish();
}
}
}
| 33.725 | 146 | 0.626761 |
a9130fe0c584fe123c7ce2222e83e0214e0f0fa2 | 2,237 | package com.github.sakserv.minicluster.yarn.util;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* 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.
*/
public class ExecShellCliParserTest {
// Logger
private static final Logger LOG = LoggerFactory.getLogger(ExecShellCliParserTest.class);
private static final String command = "whoami";
private static final String stdoutFile = "./target/com.github.sakserv.minicluster.impl.YarnLocalCluster/com.github.sakserv.minicluster.impl.YarnLocalCluster-logDir-nm-0_0/application_1431983196063_0001/container_1431983196063_0001_01_000002/stdout";
private static final String stderrFile = "./target/com.github.sakserv.minicluster.impl.YarnLocalCluster/com.github.sakserv.minicluster.impl.YarnLocalCluster-logDir-nm-0_0/application_1431983196063_0001/container_1431983196063_0001_01_000002/stderr";
private static final String cliString = command + " 1>" + stdoutFile + " 2>" + stderrFile;
private static ExecShellCliParser execShellCliParser;
@Before
public void setUp() {
execShellCliParser = new ExecShellCliParser(cliString);
}
@Test
public void testGetCommand() {
assertEquals(command, execShellCliParser.getCommand());
}
@Test
public void testGetStdoutPath() {
assertEquals(stdoutFile, execShellCliParser.getStdoutPath());
}
@Test
public void testGetStderrPath() {
assertEquals(stderrFile, execShellCliParser.getStderrPath());
}
@Test
public void testRunCommand() throws Exception {
assertEquals(0, execShellCliParser.runCommand());
}
}
| 36.080645 | 253 | 0.750112 |
ced52c3c9033308d7ebed39bb6e38ac95f468eda | 4,183 | package seedu.address.model.bug;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.Assert.assertThrows;
import org.junit.jupiter.api.Test;
class PriorityTest {
@Test
public void constructor_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new Priority(null));
}
@Test
public void constructor_invalidPriority_throwsIllegalArgumentException() {
String invalidPriority = "";
assertThrows(IllegalArgumentException.class, () -> new Priority(invalidPriority));
}
@Test
public void isValidPriority() {
// null state
assertThrows(NullPointerException.class, () -> Priority.isValidPriority(null));
// blank state
assertFalse(Priority.isValidPriority("")); // empty string
assertFalse(Priority.isValidPriority(" ")); // spaces only
// incomplete word
assertFalse(Priority.isValidPriority("hig"));
assertFalse(Priority.isValidPriority("lo"));
// invalid priority
assertFalse(Priority.isValidPriority("very high")); // one valid word
assertFalse(Priority.isValidPriority("low high")); // multiple valid words
assertFalse(Priority.isValidPriority("medium medium")); // multiple valid words
assertFalse(Priority.isValidPriority("highlow")); // multiple valid words concatenated
assertFalse(Priority.isValidPriority("fillertext")); // only filler text
assertFalse(Priority.isValidPriority("mediumfiller")); // trailing filler text
assertFalse(Priority.isValidPriority("fillerhigh")); // leading filler text
assertFalse(Priority.isValidPriority("fillerlowtext")); // sandwiched valid word
assertFalse(Priority.isValidPriority(" medium")); // leading space
assertFalse(Priority.isValidPriority("medium ")); // trailing space
assertFalse(Priority.isValidPriority(" medium ")); // leading and trailing space
// valid priority
assertTrue(Priority.isValidPriority("low"));
assertTrue(Priority.isValidPriority("medium"));
assertTrue(Priority.isValidPriority("high"));
assertTrue(Priority.isValidPriority("Low")); // uppercase is allowed
assertTrue(Priority.isValidPriority("HIGH")); // uppercase is allowed
assertTrue(Priority.isValidPriority("meDiUm")); // uppercase is allowed
}
@Test
public void isEqualPriority() {
Priority p1 = new Priority("low");
Priority p2 = new Priority("low");
Priority p3 = new Priority("medium");
Priority p4 = new Priority("meDIuM");
Object p5 = new Priority("medium");
assertEquals(p1, p1); // same object
assertEquals(p1, p2); // same value
assertEquals(p3, p4); // same value
assertEquals(p3, p5); // same value and runtime type but different compile time types
}
@Test
public void isNotEqualPriority() {
Priority p1 = new Priority("low");
Priority p2 = new Priority("medium");
Priority p3 = new Priority("meDIuM");
Priority p4 = new Priority("high");
Priority p5 = new Priority();
assertNotEquals(p1, p2); // different values
assertNotEquals(p3, p4); // different values
assertNotEquals(p3, null); // compare to null
assertNotEquals(p1, "low"); // different types
assertNotEquals(p1, p5);
}
@Test
public void isEqualHashCodePriority() {
Priority p1 = new Priority("low");
Priority p2 = new Priority("low");
Priority p3 = new Priority("LOw");
assertEquals(p1.hashCode(), p2.hashCode());
assertEquals(p1.hashCode(), p3.hashCode());
}
@Test
public void isNull() {
assertFalse(new Priority("low").isNull());
assertFalse(new Priority("medium").isNull());
assertFalse(new Priority("high").isNull());
assertTrue(new Priority().isNull());
}
}
| 39.093458 | 94 | 0.66579 |
c70a4e03d2fd5b06a5a487c48202b5abf960b08a | 3,196 | /**
* Copyright 2013-present memtrip LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License isEqualTo 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 net.frju.androidquery.operation.function;
import android.support.annotation.NonNull;
import net.frju.androidquery.database.DatabaseProvider;
import net.frju.androidquery.database.Query;
import net.frju.androidquery.operation.condition.Where;
import java.util.concurrent.Callable;
import io.reactivex.Single;
/**
* Executes a Count query against the SQLite database
* @author Samuel Kirton [[email protected]]
*/
public class Count extends Query {
private final Where[] mWhere;
public Where[] getClause() {
return mWhere;
}
private Count(Where[] where) {
mWhere = where;
}
public static
@NonNull
<T> Count.Builder getBuilder(@NonNull Class<T> classDef, @NonNull DatabaseProvider databaseProvider) {
return new Count.Builder<>(classDef, databaseProvider);
}
public static class Builder<T> {
private Where[] mWhere;
private final Class<T> mClassDef;
private final DatabaseProvider mDatabaseProvider;
private Builder(@NonNull Class<T> classDef, @NonNull DatabaseProvider databaseProvider) {
mClassDef = classDef;
mDatabaseProvider = databaseProvider;
}
/**
* Specify a Compare where for the Count query
* @param where Compare where
* @return Call Builder#query or the rx methods to run the query
*/
public
@NonNull
Builder<T> where(Where... where) {
mWhere = where;
return this;
}
/**
* Execute a Count query
* @return The row count returned by the query
*/
public long query() {
return count(
new Count(mWhere),
mClassDef,
mDatabaseProvider
);
}
/**
* Execute a Count query
* @return An RxJava Observable
*/
public
@NonNull
rx.Single<Long> rx() {
return wrapRx(new Callable<Long>() {
@Override
public Long call() throws Exception {
return query();
}
});
}
/**
* Execute a Count query
*
* @return An RxJava2 Observable
*/
public
@NonNull
Single<Long> rx2() {
return wrapRx2(new Callable<Long>() {
@Override
public Long call() throws Exception {
return query();
}
});
}
}
} | 28.035088 | 106 | 0.585419 |
300b2f4a87fb47e7b6094564d848a5f852e79c4d | 1,320 | /**
* Copyright 2008-2017 Qualogy Solutions B.V.
*
* 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.qualogy.qafe.mgwt.client.vo.functions;
public class RegExpValidateGVO extends BuiltInFunctionGVO {
private String regExp;
private String message;
private String type;
public final static String PYTHONSCRIPT="python";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getRegExp() {
return regExp;
}
public void setRegExp(String regExp) {
this.regExp = regExp;
}
public String getClassName() {
return "com.qualogy.qafe.gwt.client.vo.functions.RegExpValidateGVO";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 20 | 75 | 0.725758 |
be4dfca8c7036ebc3820c781aeabe93d6c4d857b | 27,395 |
/*
* 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 VISTAS;
import DATOS.vusuario;
import LOGICA.fusuario;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
/**
*
* @author user
*/
public class frmusuario extends javax.swing.JInternalFrame {
/**
* Creates new form frmusuario
*/
public frmusuario() {
initComponents();
inhabilitar();
mostrar("");
}
private void sizetable(){
TableColumnModel columnModel = tablaUsuarios.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(60);
columnModel.getColumn(1).setPreferredWidth(100);
columnModel.getColumn(2).setPreferredWidth(100);
columnModel.getColumn(3).setPreferredWidth(100);
}
private void inhabilitar (){
//deshabilitar cajas de texto
txtcodigoUsuario.setEnabled(false);
txtnombre.setEnabled(false);
txtclave.setEnabled(false);
txtprivilegios.setEnabled(false);
//deshabilitar botones
btnguardar.setEnabled(false);
btneliminar.setEnabled(false);
btnmodificar.setEnabled(false);
btncancelar.setEnabled(false);
//vaciar cajas de texto
txtcodigoUsuario.setText("");
txtnombre.setText("");
txtclave.setText("");
txtprivilegios.setText("");
txtprivilegios.setText("");
}
void habilitar (){
//habilitar cajas de texto
txtcodigoUsuario.setEnabled(true);
txtnombre.setEnabled(true);
txtclave.setEnabled(true);
txtprivilegios.setEnabled(true);
//habilitar botones
btnguardar.setEnabled(true);
btnmenu.setEnabled(true);
btneliminar.setEnabled(true);
//vaciar cajas de texto
txtcodigoUsuario.setText("");
txtnombre.setText("");
txtclave.setText("");
txtprivilegios.setText("");
}
private void mostrar (String buscar){
try {
DefaultTableModel modelo;
fusuario func= new fusuario();
modelo=func.mostrar(buscar);
tablaUsuarios.setModel(modelo);
lblTotal.setText(""+ Integer.toString(func.totalRegistros));
} catch (Exception e) {
JOptionPane.showConfirmDialog(rootPane, e);
}
}
/**
* 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() {
panel2 = new java.awt.Panel();
btnnuevo = new javax.swing.JButton();
btnguardar = new javax.swing.JButton();
btnmodificar = new javax.swing.JButton();
btncancelar = new javax.swing.JButton();
btneliminar = new javax.swing.JButton();
btnmenu = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tablaUsuarios = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
txtbuscar = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
lblTotal = new javax.swing.JLabel();
btnbuscar = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
lblcodigo = new javax.swing.JLabel();
lblusuario = new javax.swing.JLabel();
lblclave = new javax.swing.JLabel();
lblprivilegios = new javax.swing.JLabel();
txtcodigoUsuario = new javax.swing.JTextField();
txtnombre = new javax.swing.JTextField();
txtclave = new javax.swing.JTextField();
txtprivilegios = new javax.swing.JTextField();
setBackground(new java.awt.Color(255, 255, 255));
setBorder(null);
setTitle("Mantenimiento Usuario");
setMaximumSize(new java.awt.Dimension(530, 510));
setMinimumSize(new java.awt.Dimension(530, 510));
setPreferredSize(new java.awt.Dimension(530, 510));
getContentPane().setLayout(null);
panel2.setBackground(new java.awt.Color(0, 102, 153));
panel2.setLayout(null);
btnnuevo.setBackground(new java.awt.Color(255, 255, 255));
btnnuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/agregar-documento-simbolo-delineado.png"))); // NOI18N
btnnuevo.setToolTipText("NUEVO REGISTRO");
btnnuevo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnnuevoActionPerformed(evt);
}
});
panel2.add(btnnuevo);
btnnuevo.setBounds(0, 0, 50, 50);
btnguardar.setBackground(new java.awt.Color(255, 255, 255));
btnguardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/guardar.png"))); // NOI18N
btnguardar.setToolTipText("GUARDAR REGISTRO");
btnguardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnguardarActionPerformed(evt);
}
});
panel2.add(btnguardar);
btnguardar.setBounds(50, 0, 50, 50);
btnmodificar.setBackground(new java.awt.Color(255, 255, 255));
btnmodificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/archivo-nuevo.png"))); // NOI18N
btnmodificar.setToolTipText("MODIFICAR REGISTRO");
btnmodificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnmodificarActionPerformed(evt);
}
});
panel2.add(btnmodificar);
btnmodificar.setBounds(100, 0, 50, 50);
btncancelar.setBackground(new java.awt.Color(255, 255, 255));
btncancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/expediente.png"))); // NOI18N
btncancelar.setToolTipText("CANCELAR REGISTRO");
btncancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btncancelarActionPerformed(evt);
}
});
panel2.add(btncancelar);
btncancelar.setBounds(150, 0, 50, 50);
btneliminar.setBackground(new java.awt.Color(255, 255, 255));
btneliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/cubo-de-basura.png"))); // NOI18N
btneliminar.setToolTipText("ELIMINAR REGISTRO");
btneliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btneliminarActionPerformed(evt);
}
});
panel2.add(btneliminar);
btneliminar.setBounds(200, 0, 50, 50);
btnmenu.setBackground(new java.awt.Color(255, 255, 255));
btnmenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/salida.png"))); // NOI18N
btnmenu.setText("MENU");
btnmenu.setToolTipText("IR A MENU");
btnmenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnmenuActionPerformed(evt);
}
});
panel2.add(btnmenu);
btnmenu.setBounds(400, 0, 110, 50);
getContentPane().add(panel2);
panel2.setBounds(0, 0, 600, 50);
tablaUsuarios.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"ID", "USUARIO", "CLAVE", "PRIVILEGIOS"
}
));
tablaUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablaUsuariosMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tablaUsuarios);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(10, 220, 500, 230);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("USUARIOS REGISTRADOS");
getContentPane().add(jLabel1);
jLabel1.setBounds(20, 180, 160, 30);
txtbuscar.setText(" ");
txtbuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtbuscarActionPerformed(evt);
}
});
txtbuscar.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
txtbuscarPropertyChange(evt);
}
});
getContentPane().add(txtbuscar);
txtbuscar.setBounds(330, 180, 120, 30);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel7.setText("TOTAL DE REGISTROS:");
getContentPane().add(jLabel7);
jLabel7.setBounds(260, 450, 140, 20);
lblTotal.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTotal.setForeground(new java.awt.Color(255, 0, 0));
lblTotal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblTotal.setText("0");
getContentPane().add(lblTotal);
lblTotal.setBounds(400, 450, 110, 20);
btnbuscar.setBackground(new java.awt.Color(255, 255, 255));
btnbuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ARCHIVOS/buscar.png"))); // NOI18N
btnbuscar.setToolTipText("BUSCAR USUARIO");
btnbuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnbuscarActionPerformed(evt);
}
});
getContentPane().add(btnbuscar);
btnbuscar.setBounds(450, 170, 60, 50);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "DETALLE DE USUARIO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14), new java.awt.Color(255, 0, 0))); // NOI18N
jPanel1.setLayout(null);
lblcodigo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblcodigo.setText("CODIGO ");
jPanel1.add(lblcodigo);
lblcodigo.setBounds(10, 20, 60, 30);
lblusuario.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblusuario.setText("USUARIO");
jPanel1.add(lblusuario);
lblusuario.setBounds(10, 60, 60, 30);
lblclave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblclave.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblclave.setText("CLAVE");
jPanel1.add(lblclave);
lblclave.setBounds(220, 60, 90, 30);
lblprivilegios.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblprivilegios.setText("PRIVILEGIOS");
jPanel1.add(lblprivilegios);
lblprivilegios.setBounds(220, 20, 80, 30);
txtcodigoUsuario.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtcodigoUsuarioActionPerformed(evt);
}
});
txtcodigoUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtcodigoUsuarioKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txtcodigoUsuarioKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txtcodigoUsuarioKeyTyped(evt);
}
});
jPanel1.add(txtcodigoUsuario);
txtcodigoUsuario.setBounds(70, 20, 130, 30);
txtnombre.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtnombreActionPerformed(evt);
}
});
txtnombre.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtnombreKeyTyped(evt);
}
});
jPanel1.add(txtnombre);
txtnombre.setBounds(70, 60, 130, 30);
txtclave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtclaveActionPerformed(evt);
}
});
txtclave.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtclaveKeyTyped(evt);
}
});
jPanel1.add(txtclave);
txtclave.setBounds(310, 60, 170, 30);
txtprivilegios.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtprivilegiosActionPerformed(evt);
}
});
txtprivilegios.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtprivilegiosKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txtprivilegiosKeyTyped(evt);
}
});
jPanel1.add(txtprivilegios);
txtprivilegios.setBounds(310, 20, 170, 30);
getContentPane().add(jPanel1);
jPanel1.setBounds(10, 60, 500, 110);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnnuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnuevoActionPerformed
habilitar();
txtcodigoUsuario.requestFocus();
btnmodificar.setEnabled(false);
btnmenu.setEnabled(false);
btnnuevo.setEnabled(false);
btneliminar.setEnabled(false);
btncancelar.setEnabled(true);
btnguardar.setEnabled(true);
}//GEN-LAST:event_btnnuevoActionPerformed
private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardarActionPerformed
if (txtcodigoUsuario.getText().length()==0){
JOptionPane.showMessageDialog(rootPane, "Debes ingresar un Codigo para el usuario");
txtcodigoUsuario.requestFocus();
return;
}
if (txtnombre.getText().length()==0){
JOptionPane.showMessageDialog(rootPane, "Debes ingresar un nombre de usuario");
txtnombre.requestFocus();
return;
}
if (txtclave.getText().length()==0){
JOptionPane.showMessageDialog(rootPane, "Debes ingresar una clave");
txtclave.requestFocus();
return;
}
if (txtprivilegios.getText().length()==0){
JOptionPane.showMessageDialog(rootPane, "Debes determinar los privilegios de este Usuario");
txtprivilegios.requestFocus();
return;
}
try {
vusuario dts = new vusuario();
fusuario func = new fusuario();
dts.setCodigoUsuario(Integer.parseInt(txtcodigoUsuario.getText()));
dts.setNombre(txtnombre.getText());
dts.setClave(txtclave.getText());
dts.setPrivilegio(txtprivilegios.getText());
func.insertar(dts);
mostrar("");
inhabilitar();
//habilitar botones
btnmenu.setEnabled(true);
btnnuevo.setEnabled(true);
//ihabilitar botones
btnguardar.setEnabled(false);
sizetable();
JOptionPane.showMessageDialog(rootPane, "Se ha almacenado el registro exitosamente.");
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "Ha ocurrido un error al intentar guardar el registro.");
}
}//GEN-LAST:event_btnguardarActionPerformed
private void btnmodificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnmodificarActionPerformed
if (txtcodigoUsuario.getText().length()==0){
JOptionPane.showConfirmDialog(rootPane, "Debes ingresar un codigo para el usuario");
txtcodigoUsuario.requestFocus();
return;
}
if (txtnombre.getText().length()==0){
JOptionPane.showConfirmDialog(rootPane, "Debes ingresar un nombre de usuario");
txtnombre.requestFocus();
return;
}
if (txtclave.getText().length()==0){
JOptionPane.showConfirmDialog(rootPane, "Debes ingresar una clave");
txtclave.requestFocus();
return;
}
if (txtprivilegios.getText().length()==0){
JOptionPane.showConfirmDialog(rootPane, "Debes determinar los privilegios de este Usuario");
txtprivilegios.requestFocus();
return;
}
try {
vusuario dts = new vusuario();
fusuario func = new fusuario();
dts.setCodigoUsuario(Integer.parseInt(txtcodigoUsuario.getText()));
dts.setNombre(txtnombre.getText());
dts.setClave(txtclave.getText());
dts.setPrivilegio(txtprivilegios.getText());
func.modificar(dts);
mostrar("");
inhabilitar();
btnmenu.setEnabled(true);
sizetable();
JOptionPane.showMessageDialog(rootPane, "Se ha modificado el registro exitosamente");
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "Ha ocurrido un error al intentar modificar el registro.");
}
}//GEN-LAST:event_btnmodificarActionPerformed
private void btncancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btncancelarActionPerformed
// TODO add your handling code here:
inhabilitar ();
btnmenu.setEnabled(true);
btnnuevo.setEnabled(true);
mostrar("");
sizetable();
JOptionPane.showMessageDialog(rootPane, "Se ha cancelado la operacion.");
}//GEN-LAST:event_btncancelarActionPerformed
private void btneliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btneliminarActionPerformed
// TODO add your handling code here:
if (!txtcodigoUsuario.getText().equals("")) {
int confirmacion = JOptionPane.showConfirmDialog(rootPane, "Seguro que quiere eliminar este registro?", "Confirmar", 2);
if (confirmacion==0) {
try {
fusuario func = new fusuario();
vusuario dts = new vusuario();
dts.setCodigoUsuario(Integer.parseInt(txtcodigoUsuario.getText()));
func.eliminar(dts);
mostrar("");
inhabilitar();
btnmenu.setEnabled(true);
sizetable();
JOptionPane.showMessageDialog(rootPane, "Se ha eliminado el registro.");
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "Ha ocurrido un error al intentar eliminar el usuario");
}
}
}
}//GEN-LAST:event_btneliminarActionPerformed
private void btnmenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnmenuActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_btnmenuActionPerformed
private void tablaUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaUsuariosMouseClicked
// TODO add your handling code here:
//habilar los elementos para su modificacion
btnmodificar.setEnabled(true);
btneliminar.setEnabled(true);
btncancelar.setEnabled(true);
btnmenu.setEnabled(false);
txtcodigoUsuario.setEnabled(true);
txtnombre.setEnabled(true);
txtclave.setEnabled(true);
txtprivilegios.setEnabled(true);
int fila =tablaUsuarios.rowAtPoint(evt.getPoint());
txtcodigoUsuario.setText(tablaUsuarios.getValueAt(fila, 0).toString());
txtnombre.setText(tablaUsuarios.getValueAt(fila, 1).toString());
txtclave.setText(tablaUsuarios.getValueAt(fila, 2).toString());
txtprivilegios.setText(tablaUsuarios.getValueAt(fila, 3).toString());
}//GEN-LAST:event_tablaUsuariosMouseClicked
private void txtbuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtbuscarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtbuscarActionPerformed
private void txtbuscarPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txtbuscarPropertyChange
// TODO add your handling code here:
}//GEN-LAST:event_txtbuscarPropertyChange
private void btnbuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuscarActionPerformed
try {
mostrar(txtbuscar.getText());
} catch (Exception e) {
}
}//GEN-LAST:event_btnbuscarActionPerformed
private void txtcodigoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtcodigoUsuarioActionPerformed
// TODO add your handling code here:
txtnombre.grabFocus();
}//GEN-LAST:event_txtcodigoUsuarioActionPerformed
private void txtcodigoUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcodigoUsuarioKeyPressed
}//GEN-LAST:event_txtcodigoUsuarioKeyPressed
private void txtcodigoUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcodigoUsuarioKeyReleased
}//GEN-LAST:event_txtcodigoUsuarioKeyReleased
private void txtnombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnombreActionPerformed
// TODO add your handling code here:
txtprivilegios.grabFocus();
}//GEN-LAST:event_txtnombreActionPerformed
private void txtclaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtclaveActionPerformed
// TODO add your handling code here:
txtclave.transferFocus();
}//GEN-LAST:event_txtclaveActionPerformed
private void txtprivilegiosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtprivilegiosActionPerformed
txtclave.grabFocus();
}//GEN-LAST:event_txtprivilegiosActionPerformed
private void txtprivilegiosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtprivilegiosKeyPressed
}//GEN-LAST:event_txtprivilegiosKeyPressed
private void txtcodigoUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcodigoUsuarioKeyTyped
Character c = evt.getKeyChar();
if (Character.isLetter(c)) {
evt.setKeyChar(Character.toUpperCase(c));
}
}//GEN-LAST:event_txtcodigoUsuarioKeyTyped
private void txtnombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnombreKeyTyped
Character c = evt.getKeyChar();
if (Character.isLetter(c)) {
evt.setKeyChar(Character.toUpperCase(c));
}
}//GEN-LAST:event_txtnombreKeyTyped
private void txtprivilegiosKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtprivilegiosKeyTyped
Character c = evt.getKeyChar();
if (Character.isLetter(c)) {
evt.setKeyChar(Character.toUpperCase(c));
}
}//GEN-LAST:event_txtprivilegiosKeyTyped
private void txtclaveKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtclaveKeyTyped
Character c = evt.getKeyChar();
if (Character.isLetter(c)) {
evt.setKeyChar(Character.toUpperCase(c));
}
}//GEN-LAST:event_txtclaveKeyTyped
/**
* @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(frmusuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmusuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmusuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmusuario.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 frmusuario().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnbuscar;
private javax.swing.JButton btncancelar;
private javax.swing.JButton btneliminar;
private javax.swing.JButton btnguardar;
private javax.swing.JButton btnmenu;
private javax.swing.JButton btnmodificar;
private javax.swing.JButton btnnuevo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblTotal;
private javax.swing.JLabel lblclave;
private javax.swing.JLabel lblcodigo;
private javax.swing.JLabel lblprivilegios;
private javax.swing.JLabel lblusuario;
private java.awt.Panel panel2;
private javax.swing.JTable tablaUsuarios;
private javax.swing.JTextField txtbuscar;
private javax.swing.JTextField txtclave;
private javax.swing.JTextField txtcodigoUsuario;
private javax.swing.JTextField txtnombre;
private javax.swing.JTextField txtprivilegios;
// End of variables declaration//GEN-END:variables
}
| 40.949178 | 282 | 0.641832 |
6cd312af7f74cca5037510de5b993e44325e1dd1 | 141 | package org.motechproject.ivr.event;
import org.junit.Test;
public class CallEventTest {
@Test
public void appendData() {
}
}
| 12.818182 | 36 | 0.687943 |
c9b93516ee5f632856679a6fede9df35bd766abb | 2,047 | package com.salesmanager.core.model.system;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import com.salesmanager.core.constants.SchemaConstant;
import com.salesmanager.core.model.common.audit.AuditListener;
import com.salesmanager.core.model.common.audit.AuditSection;
import com.salesmanager.core.model.common.audit.Auditable;
import com.salesmanager.core.model.generic.SalesManagerEntity;
/**
* Global system configuration information
* @author casams1
*
*/
@Entity
@EntityListeners(value = AuditListener.class)
@Table(name = "SYSTEM_CONFIGURATION", schema= SchemaConstant.SALESMANAGER_SCHEMA)
public class SystemConfiguration extends SalesManagerEntity<Long, SystemConfiguration> implements Serializable, Auditable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "SYSTEM_CONFIG_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "SYST_CONF_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Column(name="CONFIG_KEY")
private String key;
@Column(name="VALUE")
private String value;
@Embedded
private AuditSection auditSection = new AuditSection();
public AuditSection getAuditSection() {
return auditSection;
}
public void setAuditSection(AuditSection auditSection) {
this.auditSection = auditSection;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 25.271605 | 160 | 0.777235 |
b5745765f5734a277b72b8c3a7aa517f2b32ca85 | 1,285 | package com.algalopez.mytv.domain.interactor.history;
import com.algalopez.mytv.domain.interactor.CallbackInteractor;
import com.algalopez.mytv.domain.model.SearchEntity;
import com.algalopez.mytv.domain.repository.IHistoryRepository;
import java.util.ArrayList;
/**
* AUTHOR: Alvaro Garcia Lopez (algalopez)
* DATE: 11/9/16
*/
public class SetHistoryInteractor extends CallbackInteractor<Long> {
private IHistoryRepository historyRepository;
private SearchEntity mData;
public SetHistoryInteractor(SearchEntity data, IHistoryRepository repository){
this.historyRepository = repository;
this.mData = data;
}
@Override
public Long run() {
sendProgress(0,1);
// Check if already exists
ArrayList<SearchEntity> history = historyRepository.getHistory();
boolean already_exist = false;
for (SearchEntity historyItem: history){
if (historyItem.getSearchTerm().equals(mData.getSearchTerm())){
already_exist = true;
}
}
if (already_exist){
sendError();
return 0L;
} else {
Long set = historyRepository.setHistory(mData);
sendSuccess();
return set;
}
}
}
| 23.796296 | 82 | 0.651362 |
88db1f13bc4ba613d5827f3df24522d5a97ce495 | 26,792 | package edu.utexas.segmentation;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Console;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;
import de.biomedical_imaging.ij.nlMeansPlugin.NLMeansDenoising_;
import edu.utexas.math.P2;
import edu.utexas.math.V2;
import edu.utexas.oct_plugin_ij.AttenuationCoefficient;
import edu.utexas.oct_plugin_ij.StentResults;
import edu.utexas.primitives.Tuples.Triplet;
import edu.utexas.exceptions.PointNotFoundException;
import edu.utexas.math.Histogram;
import edu.utexas.math.Math1D;
import edu.utexas.math.Math2D;
import edu.utexas.segmentation.ActiveContour2.DIRECTION;
import ij.IJ;
import ij.ImageJ;
import ij.ImageListener;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Macro;
import ij.gui.GenericDialog;
import ij.gui.ImageCanvas;
import ij.gui.Line;
import ij.gui.OvalRoi;
import ij.gui.Overlay;
import ij.gui.Plot;
import ij.gui.Roi;
import ij.io.Opener;
import ij.plugin.ContrastEnhancer;
import ij.plugin.PlugIn;
import ij.plugin.filter.RankFilters;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import ij.util.ArrayUtil;
public class ActiveContour_IJ implements PlugIn, MouseListener{
private static ActiveContour2 ac2;
private static List<P2> fitContour;
private int MaskRadius = 7;
private static ImagePlus original;
private static int Extended = 0;
private static HashMap<Integer, StentResults> _ResultsMap = new HashMap<Integer, StentResults>();
public ActiveContour2 getAC2(){
return ac2;
}
public static void main(String args[]){
ImageJ ij = new ImageJ();
ij.setVisible(true);
}
/***
* Draws and returns an ImageJ Overlay from a List of P2 points
*
* @param ip ImagePlus to draw on
* @param points List of P2 points of the Overlay
* @return Returns the Overlay
*/
public static Overlay drawPoints(ImagePlus ip, List<P2> points){
Overlay o = new Overlay();
for(P2 p : points){
Roi r = new Roi(p.x(), p.y(), 1, 1);
o.add(r);
}
ip.setOverlay(o);
return o;
}
/***
* Convenience function that gets the P2 points of the Active Contour that is trimmed based on the
* extension that is required to run the Active Contour.
*
* @param Trim Size of the P2 points to trim, should be the same as the amount the image was
* extended.
* @param points List of P2 points that make up the contour.
* @return
*/
public List<P2> getTrimmedPoints(int Trim, List<P2> points){
List<P2> trimmed = new ArrayList<P2>();
for(int i = Trim; i < points.size() - Trim; i++){
trimmed.add(points.get(i).subtract(new P2(Trim, Trim)));
}
return trimmed;
}
public Overlay getTrimmedOverlay(int Trim, List<P2> points){
Overlay o = new Overlay();
for(P2 p : points){
Roi r = new Roi(p.x() - Trim, p.y() - Trim, 1, 1);
o.add(r);
}
return o;
}
/***
* Creates an Overlay based on a List of P2 points
*
* @param points
* @return Overlay from List of P2 points
*/
public Overlay getOverlay(List<P2> points){
Overlay o = new Overlay();
for(P2 p : points){
Roi r = new Roi(p.x(), p.y(), 1, 1);
o.add(r);
}
return o;
}
/***
* Runs the ActiveContour2 algorithm based on all the inputs.
*
* @param ip
* @param options
* @return Overlay of final contour that is trimmed to fit the original image
*/
private Overlay contour(ImagePlus ip, String options){
ac2 = new ActiveContour2();
String[] args = options.split(" ");
FloatProcessor fp = ip.getProcessor().convertToFloatProcessor();
MaskRadius = 7;
P2 start = new P2(0, fp.getHeight());
DIRECTION dir = DIRECTION.BOTTOM_UP;
boolean show = false;
String direction = "";
int fitPoly = 0;
String exportDir = "";
for(int i = 0; i < args.length; i++){
String[] com = args[i].split("=");
switch(com[0]){
case "radius":
MaskRadius = Integer.parseInt(com[1]);
break;
case "start":
String[] xy = com[1].split(",");
start = new P2(Double.parseDouble(xy[0]), Double.parseDouble(xy[1]));
break;
case "hist-med-diff":
ac2.setHistogramMedStop(Double.parseDouble(com[1]));
break;
case "hist-ent-diff":
ac2.setHistogramEntStop(Double.parseDouble(com[1]));
break;
case "show":
show = true;
break;
case "dir":
direction = com[1];
break;
case "fit":
fitPoly = Integer.parseInt(com[1]);
break;
case "export":
if(com.length > 1){
exportDir = com[1];
}
break;
}
}
int itter = 0;
switch(direction){
case "bottomup":
dir = DIRECTION.BOTTOM_UP;
itter = (int)(start.y() - 0);
break;
case "topdown":
dir = DIRECTION.TOP_DOWN;
itter = (int)(ip.getHeight() - start.y());
break;
case "leftright":
dir = DIRECTION.LEFT_RIGHT;
break;
case "rightleft":
dir = DIRECTION.RIGHT_LEFT;
break;
}
int orgWidth = ip.getWidth();
int orgHeight = ip.getHeight();
ac2.init(start,
dir,
orgWidth,
MaskRadius,
(float[])fp.getPixels(),
orgWidth,
orgHeight);
if(show){
drawPoints(ip, ac2.getContourPoints());
}
long starttime = System.nanoTime();
for(int i = 0; i < itter; i++){
ac2.updateCurve();
if(show){
ip.getOverlay().clear();
drawPoints(ip, ac2.getContourPoints());
}
IJ.showProgress(i, itter);
}
List<P2> outputContour = getTrimmedPoints(Extended, ac2.getContourPoints());
if(fitPoly > 0){
if(fitContour != null)
fitContour.clear();
WeightedObservedPoints obs = new WeightedObservedPoints();
for(P2 p : outputContour){
obs.add(p.x(), p.y());
}
PolynomialCurveFitter pcf = PolynomialCurveFitter.create(fitPoly);
double poly[] = pcf.fit(obs.toList());
fitContour = new ArrayList<P2>();
double x = 0;
double y = 0;
//poly is low order first, subtract Extended because the data is trimmed in X, but not y
for(P2 p : outputContour){
switch(fitPoly){
case 1:
break;
case 2:
break;
case 3:
x = p.x();
y = (poly[0] + poly[1]*x + poly[2]*x*x + poly[3]*x*x*x) - MaskRadius*2;
fitContour.add(new P2(x, y));
break;
case 4:
x = p.x();
y = (poly[0] + poly[1]*x + poly[2]*x*x + poly[3]*x*x*x) + poly[4]*x*x*x*x - MaskRadius*2;
fitContour.add(new P2(x, y));
break;
}
}
drawPoints(ip, fitContour);
outputContour = fitContour;
}else{
fitContour = outputContour;
}
if(exportDir != ""){
File f = new File(exportDir);
try {
FileWriter fw = new FileWriter(exportDir, true);
String line = "";
for(P2 p : fitContour){
line += p.y() + ",";
}
fw.write(line + "\r\n");
fw.flush();
fw.close();
} catch (IOException e) {
IJ.log(e.getMessage());
e.printStackTrace();
}
}
long endtime = System.nanoTime();
System.out.println("Active Contour Runtime: " + (endtime - starttime)/1e9);
return getOverlay(outputContour);
}
/***
* Extends the image in +/-x and +/-y based on the input string options "radius=X". The extension is
* a mirror of the edges.
*
* @param options String options
* @param fp FloatProcessor to mirror
* @return new FloatProcessor that is extended through mirroring
*/
private FloatProcessor extendImage(String options, FloatProcessor fp){
int Radius = 7;
if(options != null){
String[] args = options.split(" ");
for(int i = 0; i < args.length; i++){
String[] com = args[i].split("=");
switch(com[0]){
case "radius":
Radius = Integer.parseInt(com[1]);
break;
}
}
}
Extended = Radius;
float[] old = (float[])fp.getPixels();
int oldWidth = fp.getWidth();
int oldHeight = fp.getHeight();
int newWidth = fp.getWidth() + 2*Radius;
int newHeight = fp.getHeight() + 2*Radius;
int lineOffset = Radius;
float[] padded = new float[newWidth*newHeight];
for(int i = 0; i < Radius; i++){
System.arraycopy(old, i*oldWidth, padded, (Radius - 1 - i)*newWidth + lineOffset, oldWidth);
System.arraycopy(old, (oldHeight - 1 - i)*oldWidth, padded, (newHeight - 1 - (Radius - 1 - i))*newWidth + lineOffset, oldWidth);
}
for(int i = 0; i < oldHeight; i++){
System.arraycopy(old, i*oldWidth, padded, (i + Radius)*newWidth + lineOffset, oldWidth);
float[] front = Arrays.copyOfRange(old, i*oldWidth, i*oldWidth + Radius);
float[] end = Arrays.copyOfRange(old, i*oldWidth + oldWidth - 1 - Radius, i*oldWidth + oldWidth);
float[] revFront = new float[front.length];
float[] revEnd = new float[end.length];
for(int j = 0; j < front.length; j++){
revFront[j] = front[front.length - 1 - j];
revEnd[j] = end[end.length - 1 - j];
}
System.arraycopy(revFront, 0, padded, (i + Radius)*newWidth, revFront.length);
System.arraycopy(revEnd, 0, padded, (i + Radius)*newWidth + oldWidth + Radius, revEnd.length);
}
FloatProcessor nfp = new FloatProcessor(newWidth, newHeight);
nfp.setPixels(padded);
return nfp;
}
/***
* Trolls the options string to see if the show option is set
*
* @param options String of options
* @return true or false if "show" is present
*/
private boolean show(String options){
boolean sh = false;
if(options != null){
String[] args = options.split(" ");
for(int i = 0; i < args.length; i++){
String[] com = args[i].split("=");
switch(com[0]){
case "show":
return true;
}
}
}else{
return false;
}
return sh;
}
private float[] peakDetect(float[] in, float distance, float amplitude){
float[] inv = Math1D.invert(in);
float[] filter = new float[inv.length];
int window = 1;
float mean = 0;
for(int i = window; i < in.length - 1 - window; i++){
float o = 0;
for(int k = -window; k <= window; k++){
o += inv[i+k];
}
o /= 2*window;
filter[i] = o;
mean += filter[i];
}
mean /= in.length;
float std = 0;
float max = 0;
for(int i = 0; i < filter.length; i++){
std += Math.pow(mean - filter[i], 2);
if(filter[i] > max){
max = filter[i];
}
}
std /= filter.length;
std = (float) Math.sqrt(std);
float[] diff = Math1D.differentiate(filter, 1);
float[] acc = Math1D.differentiate(diff, 1);
float[] zc = Math1D.zeroCrossing(acc);
List<Float> peakList = new ArrayList<Float>();
//loop through the zc to find peaks to average the amplitude of the peaks
float meanPeaks = 0;
float meanPeakCount = 0;
for(int i = 0; i < zc.length - 1; i++){
int k = (int) zc[i] + window;
if(filter[k] > mean){
meanPeaks += filter[k];
meanPeakCount += 1;
}
}
meanPeaks /= meanPeakCount;
meanPeaks *= .75;
for(int i = 0; i < zc.length; i++){
int k = (int) zc[i] + window;
if(k < inv.length){
if(filter[k] > (meanPeaks) && diff[k] < 0){// && diff[k - window] > 250){// && filter[k] > amplitude){
peakList.add((float)k);
}
}
}
float[] x = new float[diff.length];
for(int i = 0; i < x.length; i++){
x[i] = i;
}
boolean show = false;
if(show){
Plot intP = new Plot("Integrated Plot", "Width", "Integrated", x, filter);
intP.show();
Plot diffP = new Plot("Integrated Plot", "Width", "Integrated", x, diff);
diffP.show();
}
float[] peakListArr = new float[peakList.size()];
for(int i = 0; i < peakList.size(); i++){
peakListArr[i] = peakList.get(i);
}
return peakListArr;
}
private Overlay peaksToOverlay(float[] peaks){
Overlay o = new Overlay();
o.setFillColor(Color.ORANGE);
for(float f : peaks){
Roi r = new Roi(f, 25, 1, 1);
o.add(r);
}
return o;
}
private StentResults findStentsFromShadows(float[] peaks, FloatProcessor fp, ActiveContour2 contour, boolean debug){
List<P2> lp = contour.getTrimmedContourPoints(new P2(Extended, Extended), Extended);
List<P2> stents = new ArrayList<P2>();
List<P2> tissue = new ArrayList<P2>();
for(float peakX : peaks){
P2 contourpPoint = lp.get((int) peakX);
P2 start = contourpPoint;
try{
int slop = 15;
int w = 9;
int h = 101;
Roi r = new Roi(start.x() - (w - 1)/2, start.y() - (h - 1)/2 - slop, w, h);
fp.setRoi(r);
FloatProcessor nfp = (FloatProcessor) fp.crop();
float[] stentMask = {0, 0, 0, 1, 1, 1, 0, 0, 0};
float[] stentPlot = new float[h];
float[] pixels = (float[])nfp.getPixels();
float[] dep = new float[h];
for(int y = 0; y < h; y++){
dep[y] = y;
for(int x = 0; x < w; x++){
stentPlot[y] += stentMask[x]*pixels[y*w + x];
}
stentPlot[y] /= w;
}
float stentMax = Float.MIN_NORMAL;
int stentMaxIndex = 0;
for(int y = 0; y < h; y++){
if(stentPlot[y] > stentMax){
stentMax = stentPlot[y];
stentMaxIndex = y;
}
}
// if(peakX == 369){
// ImagePlus ip = new ImagePlus("Cropped", nfp.convertToShortProcessor());
// ip.show();
//
// Plot ppp = new Plot("","","",dep, stentPlot);
// ppp.show();
//
// //float[] diff = Math1D.differentiate(filter, 2);
// Plot pppp = new Plot("","","",dep, filter);
// pppp.show();
//
// ip.close();
// }
double yy = start.y() - (h - 1)/2 - slop + stentMaxIndex;
P2 p = new P2(peakX, yy);
//p = p.add(start);
stents.add(p);
tissue.add(new P2(peakX, contourpPoint.y()));
}catch(ArrayIndexOutOfBoundsException e){
System.out.print(e.getMessage());
}
}
return new StentResults(stents, tissue);
}
/***
* Creates a string or options using an IJ general dialog interface.
*
* @return String of parsed options
*/
private String Options(){
String options = "";
GenericDialog gd = new GenericDialog("Active Contour Options");
gd.addNumericField("Region radius (odd only):", 11, 0);
gd.addNumericField("Starting X:", 0, 0);
gd.addNumericField("Starting Y:", IJ.getImage().getHeight(), 0);
gd.addNumericField("Histogram Seperation", 12000, 0);
gd.addCheckbox("Show updates?", false);
String choices[] = {"Top Down", "Bottom Up", "Left Right", "Right Left"};
gd.addChoice("Direction", choices, "Bottom Up");
gd.addCheckbox("Fit Contour to 4th Order Poly", false);
gd.addCheckbox("Export Contour", false);
gd.showDialog();
if(gd.wasCanceled()){
return options;
}
int Radius = (int) gd.getNextNumber();
int X = (int) gd.getNextNumber();
int Y = (int) gd.getNextNumber();
int HistSep = (int) gd.getNextNumber();
boolean show = gd.getNextBoolean();
String showS = "";
int choiceIndex = gd.getNextChoiceIndex();
boolean fitContour = gd.getNextBoolean();
boolean export = gd.getNextBoolean();
String exportPath = "export=";
if(export){
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if(jfc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION){
exportPath += jfc.getSelectedFile().getAbsolutePath();
}
}
if(show){
showS = "show ";
}
if(Radius % 2 == 0){
Radius += 1;
}
String fit = "";
if(fitContour){
fit = "fit=4 ";
}
String dir = choices[choiceIndex].toLowerCase().replace(" ", "");
options = "radius=" + Radius + " " +
"start=" + X + "," + Y + " " +
"hist-med-diff=" + HistSep + " " +
"hist-ent-diff=.05 " +
"dir=" + dir + " " +
showS +
fit +
exportPath;
return options;
}
@Override
public void run(String arg0) {
String options = Macro.getOptions();
try{
IJ.getImage().getCanvas().removeMouseListener(this);
}catch(Exception e){
}
FloatProcessor nfp;
ImagePlus ni;
ShortProcessor sp;
ContrastEnhancer ce;
RankFilters rf;
float[] ff;
FloatProcessor trimmedFp;
Overlay o;
ImagePlus ip;
float[] out;
int startFrame, endFrame;
Extended = 27;
switch(arg0){
case "Flatten to Contour":
//TODO: Run through all images, apply Active Contour and flatten images
sp = IJ.getProcessor().convertToShortProcessor();
ff = (float[])sp.convertToFloatProcessor().getPixels();
List<P2> contour = ac2.getTrimmedContourPoints(new P2(Extended, Extended), Extended);
out = Math2D.flatten(ff,
IJ.getImage().getWidth(),
IJ.getImage().getHeight(),
contour,
300);
trimmedFp = new FloatProcessor(IJ.getImage().getWidth(), 300, out);
ni = new ImagePlus("Flattened Image", trimmedFp);
ni.show();
break;
case "FlattenVolume":
if(options == null){
//Show Popup
options = Options();
}
original = IJ.getImage();
startFrame = 1;
endFrame = original.getStackSize();
if(options.contains("applyall")){
startFrame = 1;
endFrame = original.getStackSize();
}
ImageStack volStack = new ImageStack(original.getWidth(), original.getHeight());
for(int i = startFrame; i <= endFrame; i++){
long start = System.nanoTime();
ImageProcessor improc = original.getStack().getProcessor(i);
o = _runActiveContour(improc, options);
ff = (float[])improc.convertToFloatProcessor().getPixels();
out = Math2D.flatten(ff, improc.getWidth(), improc.getHeight(), fitContour, improc.getHeight());
nfp = new FloatProcessor(improc.getWidth(), improc.getHeight(), out);
volStack.addSlice(nfp);
long stop = System.nanoTime();
double seconds = (stop - start) / 1e9;
IJ.log("Finished frame " + i + " in " + seconds + " seconds");
}
ImagePlus vol = new ImagePlus("Flattened Volume", volStack);
vol.show();
break;
case "Flatten to Fit":
sp = IJ.getProcessor().convertToShortProcessor();
ff = (float[])sp.convertToFloatProcessor().getPixels();
if(fitContour == null){
IJ.showMessage("Fit hasn't been defined, run Active Contour 2 with Fit to Poly selected");
return;
}
contour = fitContour;
out = Math2D.flatten(ff,
IJ.getImage().getWidth(),
IJ.getImage().getHeight(),
contour,
IJ.getImage().getHeight());
trimmedFp = new FloatProcessor(IJ.getImage().getWidth(), IJ.getImage().getHeight(), out);
ni = new ImagePlus("Flattened Image", trimmedFp);
ni.show();
break;
case "Export":
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Choose File for Export");
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileFilter fff = new FileNameExtensionFilter("Text File", "txt");
jfc.addChoosableFileFilter(fff);
int res = jfc.showOpenDialog(null);
if(res == JFileChooser.APPROVE_OPTION){
File file = jfc.getSelectedFile();
file.setWritable(true);
FileWriter fw;
try {
fw = new FileWriter(file);
Collection<StentResults> src = _ResultsMap.values();
Set<Integer> frames = _ResultsMap.keySet();
for(int i = 0; i < src.size(); i++){
StentResults sr = (StentResults) src.toArray()[i];
String s = "Frame " + frames.toArray()[i] + ": \t";
for(int j = 0; j < sr.getStents().size(); j++){
P2 p = sr.getStents().get(j);
s += p.x() + "," + p.y() + "," + sr.getTissue().get(j).y() + "\t";
}
fw.write(s + "\r\n");
}
fw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
break;
case "Stent":
if(options == null){
//Show Popup
options = Options();
}
original = IJ.getImage();
startFrame = original.getCurrentSlice();
endFrame = original.getCurrentSlice() + 1;
if(options.contains("applyall")){
startFrame = 1;
endFrame = original.getStackSize();
}
for(int i = startFrame; i < endFrame; i++){
IJ.showProgress(i, endFrame - startFrame);
ShortProcessor ipp = original.getStack().getProcessor(i).duplicate().convertToShortProcessor();
ce = new ContrastEnhancer();
ce.setNormalize(false);
ce.equalize(ipp);
float[] current = (float[])ipp.convertToFloatProcessor().getPixels();
nfp = new FloatProcessor(ipp.getWidth(), ipp.getHeight(), current);
nfp = extendImage("radius=27", nfp);
ip = new ImagePlus("Clone", nfp);
// NLMeansDenoising_ nl = new NLMeansDenoising_();
// nl.setup("", ip);
// nl.run(nfp);
if(show(options)){
ip.show();
ip.getCanvas().addMouseListener(this);
IJ.run("Enhance Contrast", "saturated=0.35");
}
//IJ.run(ip, "Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None*");
original.setOverlay(contour(ip, options));
StentResults sr = shadowFinder(false);
Integer key = i;
_ResultsMap.put(key, sr);
if(show(options)){
ip.setOverlay(null);
ip.changes = false;
ip.close();
}
}
break;
case "Run ActiveContour2":
ip = IJ.getImage();
o = _runActiveContour(ip.getProcessor(), options);
ip.setOverlay(o);
break;
case "Find Shadows":
original = IJ.getImage();
shadowFinder(true);
break;
}
}
private Overlay _runActiveContour(ImageProcessor ip, String options) {
//ImagePlus ip = IJ.getImage();
FloatProcessor nfp = ip.convertToFloatProcessor();
nfp = extendImage("radius=27", nfp);
if(options == null){
//Show Popup
options = Options();
}
ImagePlus ni = new ImagePlus("Clone", nfp);
// NLMeansDenoising_ nl = new NLMeansDenoising_();
// nl.setup("", ni);
// nl.run(nfp);
if(show(options)){
ni.show();
boolean alreadyAdded = false;
MouseListener[] m = ni.getCanvas().getMouseListeners();
for(MouseListener ml : m){
if(ml == this){
alreadyAdded = true;
break;
}
}
if(!alreadyAdded){
ni.getCanvas().addMouseListener(this);
}
}
Overlay o = contour(ni, options);
// if(show(options)){
// ni.close();
// }
return o;
}
private StentResults shadowFinder(boolean debug) {
ShortProcessor sp = original.getProcessor().convertToShortProcessor();
float[] ff = (float[])sp.convertToFloatProcessor().getPixels();
float[] outT = Math2D.flatten(ff,
original.getWidth(),
original.getHeight(),
ac2.getTrimmedContourPoints(new P2(Extended, Extended), Extended),
100);
FloatProcessor trimmedFp = new FloatProcessor(original.getWidth(), 100, outT);
RankFilters rf = new RankFilters();
rf.rank(trimmedFp, 1, RankFilters.MEDIAN);
//rf.rank(trimmedFp, 6, RankFilters.OUTLIERS, RankFilters.BRIGHT_OUTLIERS, 20);
//trimmedFp.
//NLMeansDenoising_ nl = new NLMeansDenoising_();
//nl.applyNonLocalMeans(trimmedFp, 15);
//IJ.run("Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None* fast_(less_accurate)");
ff = (float[])trimmedFp.getPixels();
float[] shad = Math2D.integrate(ff, trimmedFp.getWidth(), trimmedFp.getHeight());
float[] peaks = peakDetect(shad, 1, 750);
//AttenuationCoefficient ac = new AttenuationCoefficient();
//float[] attenuation = ac.run(ff, original.getWidth(), original.getHeight());
ff = (float[])sp.convertToFloatProcessor().getPixels();
FloatProcessor nfp = new FloatProcessor(original.getWidth(), original.getHeight(), ff);
if(debug){
ImagePlus ipppp = new ImagePlus("Trimmed / Flattened", trimmedFp);
ipppp.show();
ipppp.setOverlay(peaksToOverlay(peaks));
}
StentResults stentRes = findStentsFromShadows(peaks, nfp, ac2, debug);
Overlay o = new Overlay();
int w = 5;
for(int i = 0; i < stentRes.getStents().size(); i++){
P2 s = stentRes.getStents().get(i);
Roi r = new OvalRoi(s.x() - w, s.y() - w, 2*w, 2*w);
o.add(r);
P2 startLine = new P2(s.x() - 5, stentRes.getTissue().get(i).y());
P2 endLine = new P2(s.x() + 5, stentRes.getTissue().get(i).y());
r = new Line(startLine.x(), startLine.y(), endLine.x(), endLine.y());
o.add(r);
}
original.setOverlay(o);
return stentRes;
}
@Override
public void mouseClicked(MouseEvent arg0) {
ImageCanvas ic = (ImageCanvas)arg0.getSource();
double mag = ic.getMagnification();
Point p = ic.getCursorLoc();
float[] mask = ac2.getMask();
V2 v = new V2(new P2(0,0), new P2(10,10));
for(int i = 0; i < ac2.getContourVector().size(); i++){
v = ac2.getContourVector().get(i);
if(v.getStart().x() == p.getX()){
break;
}
}
Region r = ac2.createRegion(v);
if(r == null){
return;
}
List<P2> cir = r.contourInRegions(ac2.getContourVector());
r.bisect();
double[] xAxis = new double[r.getR1().length];
for(int i = 0; i < xAxis.length; i++){
xAxis[i] = i;
}
//ac2.testCurveContinuity(new P2(p.getX(), p.getY()));
RegionStatistics rs = new RegionStatistics(r);
Plot plotR1 = new Plot("R1 Histogram", "Bins", "Values", xAxis, rs.getR1HistogramCount());
plotR1.show();
Histogram hr1 = rs.getR1Histogram();
Plot plotR2 = new Plot("R2 Histogram", "Bins", "Values", xAxis, rs.getR2HistogramCount());
plotR2.show();
Histogram hr2 = rs.getR2Histogram();
//show the mask
//FloatProcessor fp = new FloatProcessor(MaskRadius*2 + 1, MaskRadius*2 + 1, r.getPixels());
//ImagePlus ip = new ImagePlus("Mask", fp);
//ip.show();
//drawPoints(fp, cir);
//show the mask R1
boolean ShowMasks = false;
if(ShowMasks){
FloatProcessor fp1 = new FloatProcessor(MaskRadius*2 + 1, MaskRadius*2 + 1, r.getMask1());
ImagePlus ip1 = new ImagePlus("Mask 1", fp1);
ip1.show();
drawPoints(ip1, cir);
//Show Mask R2
FloatProcessor fp2 = new FloatProcessor(MaskRadius*2 + 1, MaskRadius*2 + 1, r.getMask2());
ImagePlus ip2 = new ImagePlus("Mask 2", fp2);
ip2.show();
drawPoints(ip2, cir);
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
| 26.138537 | 131 | 0.622089 |
8cbe1475e41195de29d7a658e1e9edb1b5914adc | 10,786 | /*******************************************************************************
* Copyright (c) 2021 Composent, Inc. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: Scott Lewis - initial API and implementation
******************************************************************************/
package org.eclipse.ecf.provider.etcd3.container;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.ecf.core.util.Base64;
import org.eclipse.ecf.discovery.IServiceInfo;
import org.eclipse.ecf.discovery.IServiceProperties;
import org.eclipse.ecf.discovery.ServiceInfo;
import org.eclipse.ecf.discovery.ServiceProperties;
import org.eclipse.ecf.discovery.identity.IServiceTypeID;
import org.eclipse.ecf.discovery.identity.ServiceIDFactory;
import org.eclipse.ecf.provider.etcd3.identity.Etcd3Namespace;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.json.JSONWriter;
public class Etcd3ServiceInfo extends ServiceInfo {
private static final long serialVersionUID = -8472903585609997508L;
public static final String LOCATION_KEY = "location"; //$NON-NLS-1$
public static final String PRIORITY_KEY = "priority"; //$NON-NLS-1$
public static final String WEIGHT_KEY = "weight"; //$NON-NLS-1$
public static final String SERVICENAME_KEY = "servicename"; //$NON-NLS-1$
public static final String TTL_KEY = "ttl"; //$NON-NLS-1$
public static final String BYTES_TYPE = "bytes"; //$NON-NLS-1$
public static final String STRING_TYPE = "string"; //$NON-NLS-1$
public static final String LIST_TYPE = "list"; //$NON-NLS-1$
public static final String SET_TYPE = "set"; //$NON-NLS-1$
public static final String DOUBLE_TYPE = "double";//$NON-NLS-1$
public static final String FLOAT_TYPE = "float";//$NON-NLS-1$
public static final String CHAR_TYPE = "char";//$NON-NLS-1$
public static final String LONG_TYPE = "long";//$NON-NLS-1$
public static final String INT_TYPE = "int";//$NON-NLS-1$
public static final String OTHER_TYPE = "object"; //$NON-NLS-1$
public static final String TYPE_KEY = "type"; //$NON-NLS-1$
public static final String NAME_KEY = "name"; //$NON-NLS-1$
public static final String VALUE_KEY = "value"; //$NON-NLS-1$
public static final String PROPERTIES_KEY = "properties"; //$NON-NLS-1$
public static final String SERVICETYPE_KEY = "servicetype"; //$NON-NLS-1$
public static final String SERVICETYPE_SERVICES_KEY = "services"; //$NON-NLS-1$
public static final String SERVICETYPE_SCOPES_KEY = "scopes"; //$NON-NLS-1$
public static final String SERVICETYPE_PROTOCOLS_KEY = "protocols"; //$NON-NLS-1$
private static final String SERVICETYPE_NA_KEY = "namingauth"; //$NON-NLS-1$
public static Etcd3ServiceInfo deserializeFromString(String jsonString) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
String locationString = jsonObject.getString(LOCATION_KEY);
URI location = null;
try {
location = new URI(locationString);
} catch (URISyntaxException e) {
throw new JSONException(e);
}
int priority = jsonObject.getInt(PRIORITY_KEY);
int weight = jsonObject.getInt(WEIGHT_KEY);
String serviceName = jsonObject.optString(SERVICENAME_KEY);
long ttl = jsonObject.getLong(TTL_KEY);
JSONObject sto = jsonObject.getJSONObject(SERVICETYPE_KEY);
List<String> l = new ArrayList<String>();
// services
JSONArray sa = sto.getJSONArray(SERVICETYPE_SERVICES_KEY);
for (int i = 0; i < sa.length(); i++)
l.add(sa.getString(i));
String[] services = l.toArray(new String[l.size()]);
l.clear();
// scopes
sa = sto.getJSONArray(SERVICETYPE_SCOPES_KEY);
for (int i = 0; i < sa.length(); i++)
l.add(sa.getString(i));
String[] scopes = l.toArray(new String[l.size()]);
l.clear();
// protocols
sa = sto.getJSONArray(SERVICETYPE_PROTOCOLS_KEY);
for (int i = 0; i < sa.length(); i++)
l.add(sa.getString(i));
String[] protocols = l.toArray(new String[l.size()]);
l.clear();
// naming auth
String namingAuth = sto.getString(SERVICETYPE_NA_KEY);
// Create service type via factory
IServiceTypeID serviceTypeID = ServiceIDFactory.getDefault().createServiceTypeID(Etcd3Namespace.INSTANCE,
services, scopes, protocols, namingAuth);
// Service Properties
IServiceProperties sProps = new ServiceProperties();
JSONArray propsArray = jsonObject.getJSONArray(PROPERTIES_KEY);
for (int i = 0; i < propsArray.length(); i++) {
JSONObject jsonProperty = propsArray.getJSONObject(i);
// type required
String type = jsonProperty.getString(TYPE_KEY);
// key required
String name = jsonProperty.getString(NAME_KEY);
// value
if (BYTES_TYPE.equals(type))
// bytes so decode
sProps.setPropertyBytes(name, Base64.decode(jsonProperty.getString(VALUE_KEY)));
else if (STRING_TYPE.equals(type))
sProps.setPropertyString(name, jsonProperty.getString(VALUE_KEY));
else if (LIST_TYPE.equals(type)) {
@SuppressWarnings("rawtypes")
List newList = new ArrayList();
Object obj = jsonProperty.get(VALUE_KEY);
JSONArray sarr = (JSONArray) jsonProperty.get(VALUE_KEY);
for(int j=0; j < sarr.length(); j++) {
newList.add(sarr.get(j));
}
sProps.setProperty(name, newList);
} else if (SET_TYPE.equals(type)) {
@SuppressWarnings("rawtypes")
Set s = new HashSet();
JSONArray sarr = (JSONArray) jsonProperty.get(VALUE_KEY);
for(int j=0; j < sarr.length(); j++) {
s.add(sarr.get(j));
}
sProps.setProperty(name, s);
} else if (FLOAT_TYPE.equals(type)) {
sProps.setProperty(name, (float) jsonProperty.getDouble(VALUE_KEY));
} else if (DOUBLE_TYPE.equals(type)) {
sProps.setProperty(name, jsonProperty.getDouble(VALUE_KEY));
} else if (CHAR_TYPE.equals(type)) {
sProps.setProperty(name, jsonProperty.getString(VALUE_KEY).charAt(0));
} else if (LONG_TYPE.equals(type)) {
sProps.setProperty(name, jsonProperty.getLong(VALUE_KEY));
} else if (INT_TYPE.equals(type)) {
sProps.setProperty(name, jsonProperty.getInt(VALUE_KEY));
} else {
sProps.setProperty(name, jsonProperty.get(VALUE_KEY));
}
}
return new Etcd3ServiceInfo(location, serviceName, serviceTypeID, priority, weight, sProps, ttl);
}
public String serializeToJsonString() throws JSONException {
JSONStringer result = new JSONStringer();
JSONWriter stringer = result.object();
// Location
stringer.key(LOCATION_KEY).value(getLocation().toString());
// priority
stringer.key(PRIORITY_KEY).value(getPriority());
// weight
stringer.key(WEIGHT_KEY).value(getWeight());
// servicename
stringer.key(SERVICENAME_KEY).value(getServiceName());
// ttl
stringer.key(TTL_KEY).value(getTTL());
// service type id
IServiceTypeID stid = getServiceID().getServiceTypeID();
// new object
stringer.key(SERVICETYPE_KEY).object();
// services array
stringer.key(SERVICETYPE_SERVICES_KEY);
stringer.array();
String[] services = stid.getServices();
for (int i = 0; i < services.length; i++)
stringer.value(services[i]);
stringer.endArray();
// scopes
stringer.key(SERVICETYPE_SCOPES_KEY);
stringer.array();
String[] scopes = stid.getScopes();
for (int i = 0; i < scopes.length; i++)
stringer.value(scopes[i]);
stringer.endArray();
// protocols
stringer.key(SERVICETYPE_PROTOCOLS_KEY);
stringer.array();
String[] protocols = stid.getProtocols();
for (int i = 0; i < protocols.length; i++)
stringer.value(protocols[i]);
stringer.endArray();
// naming authority
stringer.key(SERVICETYPE_NA_KEY).value(stid.getNamingAuthority());
// end service type id
stringer.endObject();
// service properties
IServiceProperties properties = getServiceProperties();
JSONWriter propertiesWriter = stringer.key(PROPERTIES_KEY).array();
for (@SuppressWarnings("rawtypes")
Enumeration e = properties.getPropertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String type = null;
Object value = null;
byte[] bytes = properties.getPropertyBytes(key);
if (bytes != null) {
value = new String(Base64.encode(bytes));
type = BYTES_TYPE;
} else {
value = properties.getPropertyString(key);
if (value != null)
type = STRING_TYPE;
else {
value = properties.getProperty(key);
if (value instanceof List) {
type = LIST_TYPE;
} else if (value instanceof Set) {
type = SET_TYPE;
} else if (value instanceof Double) {
type = DOUBLE_TYPE;
} else if (value instanceof Float) {
type = FLOAT_TYPE;
} else if (value instanceof Character) {
type = CHAR_TYPE;
} else if (value instanceof Long) {
type = LONG_TYPE;
} else if (value instanceof Integer) {
type = INT_TYPE;
} else {
type = OTHER_TYPE;
}
}
}
JSONWriter propertyWriter = null;
if (value != null) {
propertyWriter = propertiesWriter.object();
propertyWriter.key(TYPE_KEY).value(type);
propertyWriter.key(NAME_KEY).value(key);
if (LIST_TYPE.equals(type)) {
@SuppressWarnings("rawtypes")
List l = (List) value;
JSONArray array = new JSONArray();
for(int i=0; i < l.size(); i++) {
array.put(i,l.get(i));
}
value = array;
} else if (SET_TYPE.equals(type)) {
@SuppressWarnings("rawtypes")
Set s = (Set) value;
JSONArray array = new JSONArray();
int i = 0;
for(Object o: s) {
array.put(i,o);
i++;
}
value = array;
} else if (CHAR_TYPE.equals(type)) {
value = Character.toString((char) value);
} else if (LONG_TYPE.equals(type)) {
value = (Long) value;
} else if (CHAR_TYPE.equals(type)) {
value = (Integer) value;
}
propertyWriter.key(VALUE_KEY).value(value);
propertyWriter.endObject();
}
}
// end array
propertiesWriter.endArray();
// end entire thing
stringer.endObject();
return result.toString();
}
public Etcd3ServiceInfo(URI anURI, String aServiceName, IServiceTypeID aServiceTypeID, int priority, int weight,
IServiceProperties props, long ttl) {
super(anURI, aServiceName, aServiceTypeID, priority, weight, props, ttl);
}
public Etcd3ServiceInfo(IServiceInfo serviceInfo, long ttl) {
this(serviceInfo.getLocation(), serviceInfo.getServiceName(), serviceInfo.getServiceID().getServiceTypeID(),
serviceInfo.getPriority(), serviceInfo.getWeight(), serviceInfo.getServiceProperties(), ttl);
}
}
| 36.938356 | 113 | 0.693584 |
7047b034be260d7dc125f94644a90bbec8b52aa1 | 1,847 | package org.soaringforecast.rasp.windy;
import org.soaringforecast.rasp.satellite.data.SatelliteCode;
public class WindyLayer {
private static final String COMMA_DELIMITER = ",";
private int id;
private String code;
private String name;
private boolean byAltitude;
public WindyLayer(String codeCommaName) {
String[] values = codeCommaName.split(COMMA_DELIMITER);
id = values.length > 0 ? Integer.parseInt(values[0]) : 0;
code = values.length > 1 ? values[1].trim() : "";
name = values.length > 2 ? values[2].trim() : "";
byAltitude = values.length > 3 && ((values[3].trim().equals("1")));
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isByAltitude() {
return byAltitude;
}
public void setByAltitude(boolean byAltitude) {
this.byAltitude = byAltitude;
}
//to display this as a string in spinner
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SatelliteCode) {
WindyLayer c = (WindyLayer) obj;
return c.getCode().equals(code) && c.getName().equals(name);
}
return false;
}
// For storing selected layer in SharedPreferences
public String toStore(){
return id
+ COMMA_DELIMITER + code.trim()
+ COMMA_DELIMITER + name.trim()
+ COMMA_DELIMITER + (byAltitude ? "1" :"0");
}
}
| 23.679487 | 75 | 0.582566 |
f57bd883956128c6fda482145b05c39da644a7f3 | 482 | package me.fmeng.anstore;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author fmeng
* @since 2019/01/06
*/
// @StoreAnnotation 存储标记
@StoreAnnotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MethodAnnotation {
}
| 21.909091 | 44 | 0.802905 |
f83ebe25b089a9ec12858b085688643bd7327fd0 | 1,948 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.integration.persistence.jpa.cache;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* @author <a href="mailto:[email protected]">Tomas Hradec</a>
*/
@Stateless
public class GameBeanDoublePersistenceContext
{
@PersistenceContext(name="jpacacheeviction", unitName="jpacacheeviction")
private EntityManager em;
@PersistenceContext(name="embedded", unitName="embedded")
private EntityManager embedded;
public void init()
{
insertGames();
}
public void insertGames()
{
em.createNativeQuery("insert into Game(id, title) values (1, 'Pac Man')").executeUpdate();
em.createNativeQuery("insert into Game(id, title) values (2, 'Super Mario')").executeUpdate();
embedded.createNativeQuery("insert into Platform(id, title) values (1, 'PC')").executeUpdate();
}
public Game findById(long gameId)
{
return em.find(Game.class, gameId);
}
public Platform findByIdInEmbedded(long platformId)
{
return embedded.find(Platform.class, platformId);
}
} | 33.016949 | 101 | 0.733573 |
f33f2c55b922211402588ae8a2b8a8e11c803239 | 190 | package ml.alternet.util.gen.sample;
public class SampleInterfaceImpl implements SampleInterface {
public static final SampleInterface SAMPLE_INTERFACE = new SampleInterfaceImpl();
}
| 23.75 | 85 | 0.815789 |
a635054790a0f79c4ba26fb07fc79ead21acda54 | 1,297 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
/*
* Created by noahbrick48 on 10/17/2018.
*/
public class hardwaremap2 {
public DcMotor lifter = null;
public DcMotor rightoniwheel = null;
public DcMotor leftoniwheel = null;
public DcMotor rightwheel = null;
public DcMotor leftwheel = null;
public DcMotor ballpulley = null;
public DcMotor ballfliper = null;
public Servo liftflipper = null ;
public Servo spinner = null ;
HardwareMap hwMap2 = null;
public void init (HardwareMap hawMap) {
hwMap2 = hawMap;
rightwheel = hwMap2.get(DcMotor.class, "rightdrive");
leftwheel = hwMap2.get(DcMotor.class, "leftdrive");
rightoniwheel = hwMap2.get(DcMotor.class, "rightonidrive");
leftoniwheel = hwMap2.get(DcMotor.class, "leftonidrive");
lifter = hwMap2.get(DcMotor.class, "lifter");
ballpulley = hwMap2.get(DcMotor.class, "ballpulley");
ballfliper = hwMap2.get(DcMotor.class, "ballfliper");
spinner = hwMap2.get(Servo.class, "spinner");
liftflipper = hwMap2.get(Servo.class, "lifterflipper");
}
}
| 20.919355 | 67 | 0.675405 |
887869c24f2f4cfbf75fb3195aa533898653ca23 | 772 | package com.kira.shop.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories("com.kira.shop.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
}
| 35.090909 | 84 | 0.854922 |
df8547c493f821f3225083a6966bf3efc1db86fa | 739 | package com.github.ddth.commons.qnd.utils;
import com.github.ddth.commons.utils.HashUtils;
public class QndHashUtilsMultithreads {
public static class TestThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(HashUtils.md5(String.valueOf(System.currentTimeMillis())));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread t = new TestThread();
t.start();
}
}
}
| 25.482759 | 94 | 0.506089 |
cb703357592b39042b29225dcec0d5778656aacb | 448 | package com.xin.gameFi.aww.bean.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/**
* create 2021/12/7
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CancelOrderEventDto {
private long id;
private String seller;
private BigDecimal selling_price;
private TokenCode pay_token_code;
private long time;
}
| 17.230769 | 37 | 0.765625 |
aafb4ca50e6a4b56881d6a8df2895a7b470df63b | 1,008 | package com.sharepower.JKutkh.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @date 2021/1/21
* @author chenguang
* @desc execute status
*/
@Getter
@AllArgsConstructor
public enum ExecuteEnums {
/**
* @date 2021/1/21
* @author chenguang
* @desc execute success
*/
SUCCESS(200, "success"),
/**
* @date 2021/1/21
* @author chenguang
* @desc rule validate fail
*/
RULE_VALIDATE_FAIL(300, "rule validate fail"),
/**
* @date 2021/1/21
* @author chenguang
* @desc JKutkh run error
*/
SYSTEM_ERROR(400, "system error"),
/**
* @date 2021/1/21
* @author chenguang
* @desc execute fail
*/
FAIL(500, "fail"),
;
/**
* @date 2021/1/21
* @author chenguang
* @desc execute code
*/
private final Integer code;
/**
* @date 2021/1/21
* @author chenguang
* @desc execute message
*/
private final String message;
}
| 17.084746 | 50 | 0.568452 |
efef3dcde846956e6d02c52addcd1e2c3c092358 | 1,939 | package com.sangupta.clitools;
import java.io.IOException;
import java.util.Map;
import org.apache.http.client.config.CookieSpecs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sangupta.jerry.http.WebRequest;
import com.sangupta.jerry.http.WebResponse;
import com.sangupta.jerry.http.service.HttpService;
import com.sangupta.jerry.http.service.impl.DefaultHttpServiceImpl;
import com.sangupta.jerry.util.DateUtils;
public class WebInvoker {
private static final Logger LOGGER = LoggerFactory.getLogger(WebInvoker.class);
private static final HttpService HTTP_SERVICE = new DefaultHttpServiceImpl();
/**
* Value to be used for connection timeout
*/
private static int connectionTimeout = (int) DateUtils.ONE_MINUTE;
/**
* Value to be used for socket timeout
*/
private static int socketTimeout = (int) DateUtils.ONE_MINUTE;
/**
* The cookie policy to use
*/
private static String cookiePolicy = CookieSpecs.DEFAULT;
public static WebResponse getResponse(String url) {
return HTTP_SERVICE.getResponse(url);
}
public static String fetchResponse(String url) {
return HTTP_SERVICE.getTextResponse(url);
}
public static Map<String, String> getHeaders(String url, boolean b) {
WebResponse response = getResponse(url);
if(response == null) {
return null;
}
return response.getHeaders();
}
public static WebResponse headRequest(String url, boolean followRedirects) {
try {
if(followRedirects) {
return WebRequest.head(url).connectTimeout(connectionTimeout).socketTimeout(socketTimeout).cookiePolicy(cookiePolicy).followRedirects().execute().webResponse();
}
return WebRequest.head(url).connectTimeout(connectionTimeout).socketTimeout(socketTimeout).cookiePolicy(cookiePolicy).noRedirects().execute().webResponse();
} catch(IOException e) {
LOGGER.debug("Unable to fetch response headers from url: {}", url, e);
}
return null;
}
}
| 28.101449 | 164 | 0.760701 |
5e5e47f244bd13fcb428ff291a379dee6cfec934 | 1,429 | /*
* Copyright 2021 Adobe. All rights reserved.
*
* This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.adobe.cq.commerce.core.components.internal.models.v1.common;
import com.adobe.cq.commerce.core.components.models.common.CommerceIdentifier;
public class CommerceIdentifierImpl implements CommerceIdentifier {
private final EntityType entityType;
private final String value;
private final IdentifierType type;
public CommerceIdentifierImpl(String value, CommerceIdentifier.IdentifierType type, CommerceIdentifier.EntityType entityType) {
this.type = type;
this.value = value;
this.entityType = entityType;
}
@Override
public String getValue() {
return value;
}
@Override
public IdentifierType getType() {
return type;
}
@Override
public EntityType getEntityType() {
return entityType;
}
}
| 34.853659 | 315 | 0.73198 |
764f6c8081aabec5d33058f60c3b710041ae8ef1 | 1,495 | package com.its.sia.service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sia.modul.domain.Pengguna;
import com.its.sia.repository.PenggunaRepository;
@Service
public class PenggunaServiceImpl implements PenggunaService {
@Autowired
private PenggunaRepository penggunaRepository;
@Override
public List<Pengguna> get() {
return get("");
}
@Override
public List<Pengguna> get(String where) {
return get(where,"");
}
@Override
public List<Pengguna> get(String where, String order) {
return get(where,order,-1,-1);
}
@Override
public List<Pengguna> get(String where, String order, int limit, int offset) {
return penggunaRepository.get(where, order, limit, offset);
}
@Override
public Pengguna getById(UUID idAnggotaRombel) {
return penggunaRepository.getById(idAnggotaRombel);
}
@Override
public String save(Pengguna pengguna) {
String where = "";
if(pengguna.getIdPengguna() != null)
{
//update
penggunaRepository.update(pengguna);
return pengguna.getIdPengguna().toString();
}
else
{
//insert
return penggunaRepository.insert(pengguna).toString();
}
}
@Override
public String delete(UUID idPengguna) {
Pengguna pengguna = penggunaRepository.getById(idPengguna);
if(pengguna==null) return null;
else{
penggunaRepository.delete(pengguna);
return "Ok";
}
}
}
| 21.056338 | 79 | 0.739799 |
b5ca2cd760dac78106d4c359cd96c45728cb1f90 | 20,915 | /*
* The MIT License
*
* Copyright 2017 yasshi2525 (https://twitter.com/yasshi2525).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.rushhourgame.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import static net.rushhourgame.RushHourResourceBundle.GAME_NO_PRIVILEDGE_OTHER_OWNED;
import net.rushhourgame.entity.Line;
import net.rushhourgame.entity.LineStep;
import net.rushhourgame.entity.Platform;
import net.rushhourgame.entity.Player;
import net.rushhourgame.entity.Pointable;
import net.rushhourgame.entity.RailEdge;
import net.rushhourgame.entity.RailNode;
import net.rushhourgame.entity.Station;
import net.rushhourgame.entity.troute.LineStepDeparture;
import net.rushhourgame.entity.troute.LineStepMoving;
import net.rushhourgame.entity.troute.LineStepPassing;
import net.rushhourgame.entity.troute.LineStepStopping;
import net.rushhourgame.exception.RushHourException;
/**
*
* @author yasshi2525 (https://twitter.com/yasshi2525)
*/
@ApplicationScoped
public class LineController extends CachedController<Line> {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(LineController.class.getName());
@Inject
protected StepForHumanController sCon;
@Inject
protected RailController rCon;
@Inject
protected StationController stCon;
@Inject
protected TrainController tCon;
@Override
public void synchronizeDatabase() {
LOG.log(Level.INFO, "{0}#synchronizeDatabase start", new Object[]{LineController.class});
writeLock.lock();
try {
synchronizeDatabase("Line.findAll", Line.class);
} finally {
writeLock.unlock();
}
LOG.log(Level.INFO, "{0}#synchronizeDatabase end", new Object[]{LineController.class});
}
@Override
protected Line mergeEntity(Line entity) {
entity.setSteps(entity.getSteps().stream().map(step -> em.merge(step)).collect(Collectors.toList()));
return em.merge(entity);
}
protected Line replaceEntity(Line entity) {
entity.setSteps(entity.getSteps().stream().map(step -> em.merge(step)).collect(Collectors.toList()));
// LineStepのparentも更新されるためLine自体も更新
entities.remove(entity);
Line newEntity = em.merge(entity);
entities.add(newEntity);
return newEntity;
}
public Line create(@NotNull Player owner, @NotNull String name) throws RushHourException {
writeLock.lock();
try {
if (existsName(owner, name)) {
throw new RushHourException(errMsgBuilder.createLineNameDuplication(name));
}
Line inst = new Line();
inst.setName(name);
inst.setOwner(owner);
persistEntity(inst);
em.flush();
LOG.log(Level.INFO, "{0}#create created {1}", new Object[]{LineController.class, inst.toStringAsRoute()});
return inst;
} finally {
writeLock.unlock();
}
}
public LineStep start(@NotNull Line line, @NotNull Player owner, @NotNull Station start) throws RushHourException {
writeLock.lock();
try {
if (!line.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
if (!line.getSteps().isEmpty()) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
// どのedgeからくるのかわからないため、stoppingは生成しない
LineStep parent = new LineStep();
parent.setParent(line);
parent.registerDeparture(start.getPlatform());
line.getSteps().add(parent);
em.persist(parent);
em.flush();
LOG.log(Level.INFO, "{0}#start created {1}", new Object[]{LineController.class, parent});
return parent;
} finally {
writeLock.unlock();
}
}
public List<RailEdge> findNext(@NotNull LineStep current, @NotNull Player owner) throws RushHourException {
readLock.lock();
try {
if (!current.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
RailNode startNode;
try {
startNode = current.getGoalRailNode();
} catch (IllegalStateException e) {
// currentに紐づくchildがいないとき
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
// 線路ノードに隣接する線路エッジをロード
em.refresh(startNode);
Line line = current.getParent();
try {
// 隣接線路エッジの中から、未到達のものだけフィルタリング
return startNode.getOutEdges().stream()
.filter(e -> !line.hasVisited(e))
.collect(Collectors.toList());
} catch (IllegalStateException e) {
// hasVisited の中の 各stepに紐づくchildがいないとき
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
} finally {
readLock.unlock();
}
}
public LineStep extend(@NotNull LineStep current, @NotNull Player owner, @NotNull RailEdge edge) throws RushHourException {
return extend(current, owner, edge, false);
}
public LineStep extend(@NotNull LineStep base, @NotNull Player owner, @NotNull RailEdge extend, boolean passing) throws RushHourException {
writeLock.lock();
try {
if (!base.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
if (!extend.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
if (base.getNext() != null) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
// startとnextがつながっていない
if (!base.getGoalRailNode().equalsId(extend.getFrom())) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
// 駅にとまっている場合、まず駅から発車する
if (base.getStopping() != null) {
base = createDeparture(base.getStopping());
}
RailNode to = extend.getTo();
em.refresh(to);
Platform toPlatform = stCon.findOn(to);
if (toPlatform != null) {
// 駅につく
if (!passing) {
base = createStopping(base, extend, toPlatform);
} else {
base = createPassing(base, extend, toPlatform);
}
} else {
base = createMoving(base, extend);
}
em.flush();
LOG.log(Level.INFO, "{0}#extend created {1}", new Object[]{LineController.class, base});
return base;
} finally {
writeLock.unlock();
}
}
/**
* start -> goal を start -> insertedStart -> insertedGoal ->
* goal にする
*
* @param from 元々あった線路ノード
* @param to 路線に加えたい線路ノード
* @param owner Player
* @return to から from に戻る路線エッジ
* @throws RushHourException 例外
*/
public LineStep insert(@NotNull RailNode from, @NotNull RailNode to, @NotNull Player owner) throws RushHourException {
writeLock.lock();
try {
if (!from.isOwnedBy(owner) || !to.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
if (!rCon.existsEdge(from, to)) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
List<LineStep> bases = findByGoalRailNode(from);
if (bases.isEmpty()) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
LineStep start = bases.get(0);
LineStep goal = start.getNext();
start.setNext(null);
RailEdge forward = rCon.findEdge(from, to);
RailEdge back = rCon.findEdge(to, from);
LineStep insertedStart = extend(start, owner, forward);
LineStep insertedGoal = extend(insertedStart, owner, back);
// 新規に停車をする場合、発車ステップを入れて後続との整合性をとる
if (insertedGoal.getStopping() != null && goal != null && goal.getDeparture() == null) {
insertedGoal = createDeparture(insertedGoal.getStopping());
}
insertedGoal.setNext(goal);
em.flush();
LOG.log(Level.INFO, "{0}#insert created {1}", new Object[]{LineController.class, insertedGoal});
return insertedGoal;
} finally {
writeLock.unlock();
}
}
public boolean canEnd(LineStep tail, Player owner) throws RushHourException {
readLock.lock();
try {
if (!tail.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
if (tail.getNext() != null) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
LineStep top = findTop(tail.getParent());
return tail.canConnect(top);
} finally {
readLock.unlock();
}
}
public void end(LineStep tail, Player owner) throws RushHourException {
writeLock.lock();
try {
if (!tail.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
if (tail.getNext() != null) {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
LineStep top = findTop(tail.getParent());
if (tail.canConnect(top)) {
tail.setNext(top);
// 更新であるが、保存しないと電車が走れなくなるため保存
replaceEntity(tail.getParent());
} else {
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
sCon.addCompletedLine(tail.getParent());
} finally {
writeLock.unlock();
}
}
public void remove(Platform p, Player owner) throws RushHourException {
writeLock.lock();
try {
if (!p.isOwnedBy(owner)) {
throw new RushHourException(errMsgBuilder.createNoPrivileged(GAME_NO_PRIVILEDGE_OTHER_OWNED));
}
List<LineStep> intoSteps = findByGoalRailNode(p.getRailNode());
// 該当する路線を最新のものにする。最新にしないと古い値で書き換えられるため
intoSteps.stream().map(step -> step.getParent()).distinct().forEach(line -> replaceEntity(line));
intoSteps = intoSteps.stream().map(step -> find(step)).collect(Collectors.toList());
LOG.log(Level.FINE, "{0}#remove removing target = {1}",
new Object[]{LineController.class, intoSteps});
intoSteps.stream()
.filter(step -> step.getStopping() != null)
.forEach(step -> replaceStopping(step));
intoSteps.stream()
.filter(step -> step.getPassing() != null)
.forEach(step -> replacePassing(step));
intoSteps.forEach(step -> tCon.detach(step));
intoSteps.forEach(step -> remove(step));
em.flush();
} finally {
writeLock.unlock();
}
}
/**
* <pre>
* Before : A -(1)-> B -(2) -> 削除Platform -(4)-> C
* After : A -(1)-> B -(5) -> D -(4)-> C
* </pre>
*
* <pre>
* Before : any(1) -> stop(2) -> dpt(3) -> any(4)
* After : any(1) -> move(5) -> any(4)
* </pre>
*
* @param oldStop (2)
*/
protected void replaceStopping(LineStep oldStop) {
// 発車タスク (3) を削除する。
LineStep oldDep = oldStop.getNext();
tCon.replaceCurrentToNext(oldDep);
LOG.log(Level.FINE, "{0}#replaceStopping released {1} before = {2}",
new Object[]{LineController.class, oldDep, oldStop});
findBefore(oldStop).stream().forEach(from -> { // 各(1)について
LineStep newMovingStep = createMoving(from, oldStop.getOnRailEdge()); // (1) から (5) に結び
newMovingStep.setNext(oldDep.getNext()); // (5) から (4) に結び
LOG.log(Level.FINE, "{0}#replaceStopping replaced from {1} to {2} (next = {3})",
new Object[]{LineController.class, oldStop, newMovingStep, newMovingStep.getNext()});
tCon.replaceCurrent(oldStop, newMovingStep); // (2) から (5) に電車を移動させる
});
oldDep.setNext(null);
oldStop.setNext(null);
}
/**
* <pre>
* Before : A -(1)-> B -(2) -> 削除Platform -(3)-> C
* After : A -(1)-> B -(4) -> D -(3)-> C
* </pre>
*
* <pre>
* Before : any(1) -> pass(2) -> any(3)
* After : any(1) -> move(4) -> any(3)
* </pre> . 実は replaceStopping とほぼ同じだけど、混乱するので書き分けた
*
* @param oldPass (2)
*/
protected void replacePassing(LineStep oldPass) {
findBefore(oldPass).stream().forEach(from -> { // 各(1)について
LineStep newMovingStep = createMoving(from, oldPass.getOnRailEdge()); // (1) から (4) に結び
newMovingStep.setNext(oldPass.getNext()); // (4) から (3) に結び
LOG.log(Level.FINE, "{0}#replacePassing replaced from {1} to {2}",
new Object[]{LineController.class, oldPass, newMovingStep});
tCon.replaceCurrent(oldPass, newMovingStep); // (2) から (4) に電車を移動させる
});
oldPass.setNext(null);
}
protected LineStep createDeparture(LineStepStopping base) {
LineStep newStep = new LineStep();
newStep.setParent(base.getParent().getParent());
newStep.registerDeparture(base.getGoal());
em.persist(newStep);
em.flush();
LOG.log(Level.FINE, "{0}#createDeparture created {1} before = {2}",
new Object[]{LineController.class, newStep, base.getParent()});
base.getParent().setNext(newStep);
newStep.getParent().getSteps().add(newStep);
return newStep;
}
protected LineStep createStopping(LineStep base, RailEdge extend, Platform goal) {
LineStep newStep = new LineStep();
newStep.setParent(base.getParent());
newStep.registerStopping(extend, goal);
em.persist(newStep);
em.flush();
LOG.log(Level.FINE, "{0}#createStopping created {1} before = {2}",
new Object[]{LineController.class, newStep, base});
base.setNext(newStep);
newStep.getParent().getSteps().add(newStep);
return newStep;
}
protected LineStep createMoving(LineStep base, RailEdge extend) {
LineStep newStep = new LineStep();
newStep.setParent(base.getParent());
newStep.registerMoving(extend);
em.persist(newStep);
em.flush();
LOG.log(Level.FINE, "{0}#createMoving created {1} before = {2}",
new Object[]{LineController.class, newStep, base});
base.setNext(newStep);
newStep.getParent().getSteps().add(newStep);
return newStep;
}
protected LineStep createPassing(LineStep base, RailEdge extend, Platform goal) {
LineStep newStep = new LineStep();
newStep.setParent(base.getParent());
newStep.registerPassing(extend, goal);
em.persist(newStep);
em.flush();
LOG.log(Level.FINE, "{0}#createPassing created {1} before {2}",
new Object[]{LineController.class, newStep, base});
base.setNext(newStep);
newStep.getParent().getSteps().add(newStep);
return newStep;
}
protected List<LineStep> findByGoalRailNode(RailNode node) {
List<LineStep> result = new ArrayList<>();
findAll().stream()
.filter(l -> l.isOwnedBy(node.getOwner()))
.forEach(l -> result.addAll(
l.getSteps().stream()
.filter(step -> step.getGoalRailNode().equalsId(node))
.collect(Collectors.toList())));
return result;
}
protected List<LineStep> findBefore(LineStep base) {
return base.getParent().getSteps().stream()
.filter(from -> base.equalsId(from.getNext()))
.collect(Collectors.toList());
}
/**
* 誰からも参照されていない LineStep を探す
*
* @param line line
* @return LineStep
* @throws net.rushhourgame.exception.RushHourException 例外
*/
protected LineStep findTop(@NotNull Line line) throws RushHourException {
Map<LineStep, Boolean> referred = new HashMap<>();
line.getSteps().forEach(step -> referred.put(step, Boolean.FALSE));
line.getSteps().stream()
.filter(step -> step.getNext() != null)
.forEach(step -> referred.put(step.getNext(), Boolean.TRUE));
for (LineStep step : referred.keySet()) {
if (!referred.get(step)) {
return step;
}
}
throw new RushHourException(errMsgBuilder.createDataInconsitency(null));
}
public Line autocreate(Player player, Station start, String name) throws RushHourException {
writeLock.lock();
try {
Line line = create(player, name);
em.flush();
LineStep tail = start(line, player, start);
List<RailEdge> candinates;
while (!(candinates = findNext(tail, player)).isEmpty()) {
tail = extend(tail, player, candinates.get(0));
em.flush();
}
if (canEnd(tail, player)) {
end(tail, player);
}
LOG.log(Level.INFO, "{0}#autocreate created {1}", new Object[]{LineController.class, line.toStringAsRoute()});
em.flush();
return line;
} finally {
writeLock.unlock();
}
}
protected boolean existsName(Player owner, String name) {
return findAll().stream().filter(l -> l.isOwnedBy(owner)).anyMatch(l -> l.getName().equals(name));
}
public LineStep find(LineStep old) {
readLock.lock();
try {
if (old == null) {
return null;
}
return findAll().stream()
.filter(l -> l.equalsId(old.getParent()))
.findFirst().get().getSteps().stream()
.filter(step -> step.equalsId(old))
.findFirst().get();
} finally {
readLock.unlock();
}
}
protected void remove(LineStep step) {
Line line = step.getParent();
em.remove(step);
line.getSteps().remove(step);
LOG.log(Level.FINE, "{0}#remove removed {1}", new Object[]{LineController.class, step});
if (line.getSteps().isEmpty()) {
removeEntity("Line.deleteBy", line);
LOG.log(Level.FINE, "{0}#remove removed {1}", new Object[]{LineController.class, line});
}
}
}
| 36.373913 | 143 | 0.591537 |
d32c466ffb7687f3773d32b06eb094a341921e18 | 581 | package com.g2forge.habitat.metadata.access.value;
import com.g2forge.habitat.metadata.access.ITypedMetadataAccessor;
import com.g2forge.habitat.metadata.type.predicate.IPredicateType;
import com.g2forge.habitat.metadata.value.predicate.IPredicate;
import com.g2forge.habitat.metadata.value.subject.IValueSubject;
class ValueMetadataAccessor<T> implements ITypedMetadataAccessor<T, IValueSubject, IPredicateType<T>> {
@Override
public IPredicate<T> bindTyped(IValueSubject subject, IPredicateType<T> predicateType) {
return new ValuePredicate<>(subject, predicateType);
}
}
| 41.5 | 103 | 0.833046 |
edeee1c920f6747e054705930df85fd941788065 | 1,681 | package com.github.mahjong.main.service.model;
import com.github.mahjong.main.model.PlayerScore;
import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
public class RoundScore {
private final Map<Long, PlayerScore> playerIdToScore;
private final Set<Long> winners;
private final Set<Long> losers;
// todo add penalties here
public RoundScore(Map<Long, PlayerScore> playerIdToScore, Set<Long> winners, Set<Long> losers) {
Preconditions.checkArgument(playerIdToScore.size() == 4, "Only 4 players can play mahjong");
Preconditions.checkArgument(winners.size() <= 4, "Winner have to be not more than players");
Preconditions.checkArgument(losers.size() <= 4, "Loosers have to be not more than players");
Preconditions.checkArgument(playerIdToScore.keySet().containsAll(winners), "Winners have to be among players");
Preconditions.checkArgument(playerIdToScore.keySet().containsAll(losers), "Losers have to be among players");
this.playerIdToScore = playerIdToScore;
this.winners = winners;
this.losers = losers;
}
public Map<Long, PlayerScore> getPlayerIdToScore() {
return Collections.unmodifiableMap(playerIdToScore);
}
public Set<Long> getWinners() {
return Collections.unmodifiableSet(winners);
}
public Set<Long> getLosers() {
return Collections.unmodifiableSet(losers);
}
public boolean isDraw() {
return winners.isEmpty() && losers.isEmpty();
}
public boolean contains(Long playerId) {
return playerIdToScore.containsKey(playerId);
}
}
| 35.020833 | 119 | 0.707317 |
5d3f8667a2c2949bd59639c76e0afef338b27301 | 234 | package com.mvp.tictactoe.view;
public interface TicTacTowView {
void showWinner(String winningPlayerDisplayLabel);
void clearWinnerDisplay();
void clearButtons();
void setButtonText(int row, int col, String text);
}
| 26 | 54 | 0.752137 |
e2ac16553a5d013f25872bbab209cc803168fbfb | 2,165 | package org.aries.generator;
import java.io.File;
import org.apache.commons.io.FileUtils;
import aries.generation.engine.GenerationContext;
import aries.generation.engine.GeneratorEngine;
public class AriesCommonModelGeneratorOLD {
private static String ARIES_COMMON_MODEL = "aries-common-1.0.aries";
private static String USER_DIR = System.getProperty("user.dir");
private static String RUNTIME_LOCATION = USER_DIR + "/src/main/resources/schema";
private static String WORKSPACE_LOCATION = "C:/workspace/STAGING";
private static String MODEL_LOCATION = WORKSPACE_LOCATION + "/common/projects/common-model/model";
public static void main(String[] args) throws Exception {
File ariesCommonSchemaFile = new File(WORKSPACE_LOCATION + "/common/common-model/src/main/resources/schema/common" + ARIES_COMMON_MODEL);
File runtimeLocation = new File(RUNTIME_LOCATION);
FileUtils.copyFileToDirectory(ariesCommonSchemaFile, runtimeLocation);
generateFromInformationModel(ARIES_COMMON_MODEL);
}
protected static void generateFromInformationModel(String inputFile) throws Exception {
String inputPath = RUNTIME_LOCATION + "/" + inputFile;
GenerationContext context = createGenerationContext();
GeneratorEngine engine = new GeneratorEngine(context);
engine.initialize();
engine.generateModelLayer(inputPath);
}
protected static GenerationContext createGenerationContext() {
GenerationContext context = new GenerationContext();
context.setProperty("generateJavadoc");
//context.setProjectName(projectName);
context.setRuntimeLocation(RUNTIME_LOCATION);
context.setWorkspaceLocation(WORKSPACE_LOCATION);
context.setModelLocation(MODEL_LOCATION);
context.setTargetWorkspace("..");
context.setTemplateWorkspace("..");
context.setTemplateName("template1");
context.setProjectName("common-model");
context.setProjectPrefix("common");
context.setProjectGroupId("org.aries");
context.setProjectDomain("org.aries");
context.setProjectVersion("1.0");
//context.addSubset("project");
context.addSubset("model");
return context;
}
}
| 34.919355 | 139 | 0.762125 |
b2b2a3fb861f58e8d3cb4511f7b9b0e6ea5d26bc | 3,084 | package org.broadinstitute.dropseqrna.vcftools.filters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.GenotypeBuilder;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
public class CallRateVariantContextFilterTest {
@Test
// test all donors.
public void testFilter1() {
VariantContextBuilder b = new VariantContextBuilder();
Allele a1 = Allele.create("A", true);
Allele a2 = Allele.create("T", false);
final List<Allele> allelesHet = new ArrayList<>(Arrays.asList(a1, a2));
final List<Allele> allelesRef = new ArrayList<>(Arrays.asList(a1, a1));
final List<Allele> allelesAlt = new ArrayList<>(Arrays.asList(a2, a2));
// GQ=30 Genotypes
Collection<Genotype> genotypes = new ArrayList<>();
genotypes.add(new GenotypeBuilder("donor1", allelesRef).GQ(30).make());
genotypes.add(new GenotypeBuilder("donor2", allelesHet).GQ(30).make());
genotypes.add(new GenotypeBuilder("donor3", allelesRef).GQ(30).make());
genotypes.add(new GenotypeBuilder("donor4", allelesAlt).GQ(30).make());
VariantContext vc = b.alleles(allelesHet).start(1).stop(1).chr("1").genotypes(genotypes).make();
Assert.assertNotNull(vc);
Iterator<VariantContext> underlyingIterator = Collections.emptyIterator();
// test against 4 well called donors. Don't filter.
CallRateVariantContextFilter f = new CallRateVariantContextFilter(underlyingIterator, 30, 0.9);
Assert.assertFalse(f.filterOut(vc));
// test against 4 well called donors + 1 donor with low GQ. Filter.
genotypes.add(new GenotypeBuilder("donor5", allelesAlt).GQ(10).make());
vc = b.alleles(allelesHet).start(1).stop(1).chr("1").genotypes(genotypes).make();
f = new CallRateVariantContextFilter(underlyingIterator, 30, 0.9);
Assert.assertTrue(f.filterOut(vc));
// test against 4 well called donors, skip the 5th because it's not on the donor list.
List<String> donors = Arrays.asList("donor1", "donor2", "donor3", "donor4");
f = new CallRateVariantContextFilter(underlyingIterator, 30, 0.9, donors);
Assert.assertFalse(f.filterOut(vc));
// add the 5th donor back and filter.
donors = Arrays.asList("donor1", "donor2", "donor3", "donor4", "donor5");
f = new CallRateVariantContextFilter(underlyingIterator, 30, 0.9, donors, true);
Assert.assertTrue(f.filterOut(vc));
//construct a no call genotype. This also fails and gets filtered.
genotypes.add(new GenotypeBuilder("donor6", Arrays.asList(Allele.NO_CALL)).make());
vc = b.alleles(allelesHet).start(1).stop(1).chr("1").genotypes(genotypes).make();
donors = Arrays.asList("donor1", "donor2", "donor3", "donor4", "donor6");
f = new CallRateVariantContextFilter(underlyingIterator, 30, 0.9, donors, true);
Assert.assertTrue(f.filterOut(vc));
}
}
| 42.833333 | 98 | 0.745785 |
0f2482e50bbc2a7fc16d940543a3d557c200fbf7 | 433 | package com.example.appraise.service;
import com.example.appraise.model.ArIndex;
import com.example.appraise.model.RestApiException;
import java.util.List;
public interface IndexService {
ArIndex save(ArIndex entity) throws RestApiException;
ArIndex update(ArIndex entity) throws RestApiException;
ArIndex delete(int id) throws RestApiException;
List<ArIndex> findAll();
List<Integer> findUsedIndexes();
}
| 22.789474 | 59 | 0.775982 |
aa0e30b66976ebfd5cfa31612c45bac3f601d85c | 2,398 | package com.yyz.demo.getappinfo.utils;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class DateTransUtils {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("M-d-yyyy");
public static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
/*
* 将时间戳转换为时间
*/
public static String stampToDate(String stamp){
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(stamp);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
public static String stampToDate(long stamp){
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(stamp);
res = simpleDateFormat.format(date);
return res;
}
//获取今日某时间的时间戳
public static long getTodayStartStamp(int hour,int minute,int second){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
long todayStamp = cal.getTimeInMillis();
Log.i("Wingbu"," DateTransUtils-getTodayStartStamp() 获取当日" + hour+ ":" + minute+ ":" + second+ "的时间戳 :" + todayStamp);
return todayStamp;
}
//获取当日00:00:00的时间戳,东八区则为早上八点
public static long getZeroClockTimestamp(long time){
long currentStamp = time;
currentStamp -= currentStamp % DAY_IN_MILLIS;
Log.i("Wingbu"," DateTransUtils-getZeroClockTimestamp() 获取当日00:00:00的时间戳,东八区则为早上八点 :" + currentStamp);
return currentStamp;
}
//获取最近7天的日期,用于查询这7天的系统数据
public static ArrayList<String> getSearchDays(){
ArrayList<String> dayList = new ArrayList<>();
for(int i = 0 ; i < 7 ; i++){
dayList.add(getDateString(i));
}
return dayList;
}
//获取dayNumber天前,当天的日期字符串
public static String getDateString(int dayNumber){
long time = System.currentTimeMillis() - dayNumber * DAY_IN_MILLIS;
Log.i("Wingbu"," DateTransUtils-getDateString() 获取查询的日期 :" + dateFormat.format(time));
return dateFormat.format(time);
}
}
| 32.849315 | 127 | 0.653878 |
c5163286f1db1ed530910dd18d7f3e9bc3f94000 | 664 | package com.refinitiv.eta.valueadd.reactor;
/**
* Tunnel stream Info available through {@link TunnelStream#info(TunnelStreamInfo, ReactorErrorInfo)} method call.
*
* @see TunnelStream
*/
public interface TunnelStreamInfo {
/**
* Get buffers used count.
*
* @return total buffers used - both big and ordinary
*/
int buffersUsed();
/**
* Get buffers used count.
*
* @return ordinary buffers used
*/
int ordinaryBuffersUsed();
/**
* Get buffers used count.
*
* @return big buffers used
*/
int bigBuffersUsed();
/**
* Clears buffer Info.
*/
void clear();
}
| 18.444444 | 114 | 0.597892 |
e9b696db3003aa43457db779c97ca9dae2166ac2 | 6,254 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.01.22 at 02:23:57 PM MST
//
package net.opengis.cat.csw._202;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import org.purl.dc.elements._1.SimpleLiteral;
/**
*
* This type encapsulates all of the standard DCMI metadata terms,
* including the Dublin Core refinements; these terms may be mapped
* to the profile-specific information model.
*
*
* <p>Java class for DCMIRecordType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="DCMIRecordType">
* <complexContent>
* <extension base="{http://www.opengis.net/cat/csw/2.0.2}AbstractRecordType">
* <sequence>
* <group ref="{http://purl.org/dc/terms/}DCMI-terms"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DCMIRecordType", propOrder = {
"dcElement"
})
@XmlSeeAlso({
RecordType.class
})
public class DCMIRecordType
extends AbstractRecordType
{
@XmlElementRef(name = "DC-element", namespace = "http://purl.org/dc/elements/1.1/", type = JAXBElement.class)
protected List<JAXBElement<SimpleLiteral>> dcElement;
/**
* Gets the value of the dcElement property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dcElement property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDCElement().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
* {@link JAXBElement }{@code <}{@link SimpleLiteral }{@code >}
*
*
*/
public List<JAXBElement<SimpleLiteral>> getDCElement() {
if (dcElement == null) {
dcElement = new ArrayList<JAXBElement<SimpleLiteral>>();
}
return this.dcElement;
}
}
| 43.430556 | 124 | 0.619763 |
af7bd32783a0b7cbb551e2610e5a8673b58aa74d | 534 | package cz.optimization.odpadky.retrofit_data;
import java.util.List;
import cz.optimization.odpadky.objects.Container;
import cz.optimization.odpadky.objects.Place;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GetDataService {
@GET("places")
Call<List<Place>> getAllPlaces();
@GET("places/{place_id}")
Call<Container.ContainersResult> getContainersList(@Path("place_id") String placeId);
@GET("containers")
Call<List<Container>> getContainersTypes();
} | 24.272727 | 89 | 0.756554 |
dfb5304b16a2fdb779a9e532aa60ab488485d78f | 2,729 | //
//
// Modified by Orb on 3/27/14.
//
// Created by Raymond Daly on 10/31/10.
// Copyright 2010 Floatopian LLC. All rights reserved.
// Copyright (C) 2017 Migeran
//
// 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.moe.ui;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.RegisterOnStartup;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassName;
import org.moe.natj.objc.ann.Selector;
import apple.foundation.NSSet;
import apple.uikit.UIEvent;
import apple.uikit.UIGestureRecognizer;
import apple.uikit.UISwipeGestureRecognizer;
@org.moe.natj.general.ann.Runtime(ObjCRuntime.class)
@ObjCClassName("WildcardGestureRecognizer")
@RegisterOnStartup
public class WildcardGestureRecognizer extends UIGestureRecognizer {
public TouchesEventBlock touchesBeganCallback;
public TouchesEventBlock touchesMovedCallback;
public TouchesEventBlock touchesEndedCallback;
@Owned
@Selector("alloc")
public static native WildcardGestureRecognizer alloc();
@Selector("init")
public WildcardGestureRecognizer init() {
WildcardGestureRecognizer gestureRecognizer = (WildcardGestureRecognizer) super.init();
gestureRecognizer.setCancelsTouchesInView(false);
return gestureRecognizer;
}
protected WildcardGestureRecognizer(Pointer peer) {
super(peer);
}
@Selector("touchesBegan:withEvent:")
public void touchesBegan(NSSet touches, UIEvent event) {
if (touchesBeganCallback != null) {
touchesBeganCallback.callback(touches, event);
}
}
@Selector("touchesEnded:withEvent:")
public void touchesEnded(NSSet touches, UIEvent event) {
if (touchesEndedCallback != null) {
touchesEndedCallback.callback(touches, event);
}
}
@Selector("touchesMoved:withEvent:")
public void touchesMoved(NSSet touches, UIEvent event) {
if (touchesMovedCallback != null) {
touchesMovedCallback.callback(touches, event);
}
}
public interface TouchesEventBlock {
public void callback(NSSet touches, UIEvent event);
}
}
| 31.732558 | 95 | 0.728838 |
a39c8ced35b29210e1f0892badc64dce7b067e2b | 2,518 | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.ivona.services.tts.model;
import java.util.List;
/**
* Class representing ListLexicons result
* <p>
* Please check the service documentation for more details.
*
* @see <a href="http://developer.ivona.com/en/speechcloud/speechcloud_developer_guide.html">Speech Cloud Developer Guide</a>
*/
public class ListLexiconsResult {
private List<String> lexiconNames;
/**
* Get the list of lexicon names from result.
*/
public List<String> getLexiconNames() {
return lexiconNames;
}
/**
* Set the list of lexicon names for this result.
*/
public void setLexiconNames(List<String> lexiconNames) {
this.lexiconNames = lexiconNames;
}
/**
* Set the list of lexicon names for this result.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*/
public ListLexiconsResult withLexiconNames(List<String> lexiconNames) {
this.lexiconNames = lexiconNames;
return this;
}
@Override
public String toString() {
return "ListLexiconsResult [lexiconNames=" + lexiconNames + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((lexiconNames == null) ? 0 : lexiconNames.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ListLexiconsResult other = (ListLexiconsResult) obj;
if (lexiconNames == null) {
if (other.lexiconNames != null) {
return false;
}
} else if (!lexiconNames.equals(other.lexiconNames)) {
return false;
}
return true;
}
}
| 28.613636 | 125 | 0.623908 |
e43354669ab17422de0ad8570d99e2e3ee1f5ba1 | 412 | package com.jlife.abon.form;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
/**
* @author Dzmitry Misiuk
*/
public class ChangingEmailForm {
@Email
@NotBlank
private String newEmail;
public String getNewEmail() {
return newEmail;
}
public void setNewEmail(String newEmail) {
this.newEmail = newEmail;
}
}
| 17.913043 | 52 | 0.691748 |
0e0227be9203fa981a25ad6ed382f6f7eb451fc8 | 422 | package io.sruby.github.test.unit.service;
import io.sruby.github.test.unit.entity.BookCompany;
import org.springframework.stereotype.Service;
/**
* @description: user
* @author: sruby
* @create: 2020-12-07 11:54
*/
@Service
public class BookCompanyService {
public BookCompany get(String companyId){
return BookCompany.builder().companyId(companyId).companyName(companyId+"_Company").build();
}
}
| 22.210526 | 100 | 0.734597 |
12f9ff4f0b39b4eaf20340111f7252bbcb2a800d | 1,311 | package org.springframework.data.r2dbc.support;
import io.r2dbc.spi.ConnectionFactories;
import org.springframework.data.r2dbc.config.beans.Beans;
import org.springframework.data.r2dbc.core.DefaultReactiveDataAccessStrategy;
import org.springframework.data.r2dbc.dialect.DialectResolver;
import org.springframework.data.r2dbc.repository.support.R2dbcRepositoryFactory;
import org.springframework.r2dbc.core.DatabaseClient;
/**
* Utilities for r2dbc compliant.
*
* @author Lao Tsing
*/
public abstract class R2dbcUtils {
public static <T> T getRepository(String r2dbcUrl, Class<T> cls) {
var connectionFactory = ConnectionFactories.get(r2dbcUrl);
return new R2dbcRepositoryFactory(
DatabaseClient.builder().connectionFactory(connectionFactory).build(),
new DefaultReactiveDataAccessStrategy(DialectResolver.getDialect(connectionFactory))
).getRepository(cls);
}
public static <T> T getRepository(Class<T> cls) {
var databaseClient = Beans.of(DatabaseClient.class);
var dialect = DialectResolver.getDialect(databaseClient.getConnectionFactory());
return new R2dbcRepositoryFactory(
databaseClient,
new DefaultReactiveDataAccessStrategy(dialect)
).getRepository(cls);
}
} | 40.96875 | 100 | 0.743707 |
1bbc74841799d3b685b27c9a09e10301861e5e07 | 233 | package com.foodorderback.repository;
import com.foodorderback.model.ShoppingCart;
import org.springframework.data.repository.CrudRepository;
public interface ShoppingCartRepository extends CrudRepository<ShoppingCart, Long> {
}
| 23.3 | 84 | 0.849785 |
f8baadcd06a9f0df601690dd67ec3d4008d2e551 | 313 | package com.xiaozhi.dao.mapper;
import com.xiaozhi.dao.base.MyMapper;
import com.xiaozhi.entity.Order;
import org.springframework.stereotype.Repository;
/**
* @author fenghouzhi
* @date 2020/5/10 - 12:18 下午
* @description: OrderMapper
*/
@Repository
public interface OrderMapper extends MyMapper<Order> {
} | 20.866667 | 54 | 0.763578 |
5bb26e1ace2ec31ef3f8848403782039d0027ea0 | 1,043 | /*
* DownloadUnzip.java
*
* Version 1.0
*
* 21 May 2013
*/
package com.bixly.pastevid.download;
import com.bixly.pastevid.Settings;
import com.bixly.pastevid.util.LogUtil;
import java.io.File;
/**
* Extension of DownloadThread class for downloading the Unzip library. Only run
* on Windows since unzip is pre-installed with Mac/Linux environments.
* @author cevaris
*/
public class DownloadUnzip extends DownloadThread {
public DownloadUnzip() {
super("Unzip Download");
this.file = new File(Settings.getUnzipExecutable());
this.url = Settings.getUnzipLibURL();
}
@Override
protected void preDownloadProcedure() {
// Do nothing
}
@Override
protected void postDownloadProcedure() {
if (this.file.exists()) {
this.file.setExecutable(true);
} else {
log("Could not locate "+this.file.getAbsolutePath());
}
}
private void log(Object message) {
LogUtil.log(DownloadUnzip.class, message);
}
}
| 23.177778 | 80 | 0.644295 |
75a57ceb5430ba252035dd91f9e98e6489ccfe0a | 3,527 | package com.emc.mongoose.base.logging;
import static com.emc.mongoose.base.Constants.K;
import static com.emc.mongoose.base.Constants.M;
import static com.emc.mongoose.base.env.DateUtil.FMT_DATE_ISO8601;
import com.emc.mongoose.base.item.op.OpType;
import com.emc.mongoose.base.metrics.snapshot.AllMetricsSnapshot;
import com.emc.mongoose.base.metrics.snapshot.ConcurrencyMetricSnapshot;
import com.emc.mongoose.base.metrics.snapshot.DistributedAllMetricsSnapshot;
import com.emc.mongoose.base.metrics.snapshot.RateMetricSnapshot;
import com.emc.mongoose.base.metrics.snapshot.TimingMetricSnapshot;
import java.util.Date;
import org.apache.logging.log4j.message.AsynchronouslyFormattable;
/** Created by kurila on 18.05.17. */
@AsynchronouslyFormattable
public final class MetricsCsvLogMessage extends LogMessageBase {
private final AllMetricsSnapshot snapshot;
private final OpType opType;
private final int concurrencyLimit;
public MetricsCsvLogMessage(
final AllMetricsSnapshot snapshot, final OpType opType, final int concurrencyLimit) {
this.snapshot = snapshot;
this.opType = opType;
this.concurrencyLimit = concurrencyLimit;
}
@Override
public final void formatTo(final StringBuilder strb) {
final ConcurrencyMetricSnapshot concurrencySnapshot = snapshot.concurrencySnapshot();
final TimingMetricSnapshot durationSnapshot = snapshot.durationSnapshot();
final RateMetricSnapshot successCountSnapshot = snapshot.successSnapshot();
final RateMetricSnapshot byteCountSnapshot = snapshot.byteSnapshot();
final TimingMetricSnapshot latencySnapshot = snapshot.latencySnapshot();
strb.append('"')
.append(FMT_DATE_ISO8601.format(new Date()))
.append('"')
.append(',')
.append(opType.name())
.append(',')
.append(concurrencyLimit)
.append(',')
.append(
snapshot instanceof DistributedAllMetricsSnapshot
? ((DistributedAllMetricsSnapshot) snapshot).nodeCount()
: 1)
.append(',')
.append(concurrencySnapshot.last())
.append(',')
.append(concurrencySnapshot.mean())
.append(',')
.append(successCountSnapshot.count())
.append(',')
.append(snapshot.failsSnapshot().count())
.append(',')
.append(byteCountSnapshot.count())
.append(',')
.append(snapshot.elapsedTimeMillis() / K)
.append(',')
.append(durationSnapshot.sum() / M)
.append(',')
.append(successCountSnapshot.mean())
.append(',')
.append(successCountSnapshot.last())
.append(',')
.append(byteCountSnapshot.mean())
.append(',')
.append(byteCountSnapshot.last())
.append(',')
.append(durationSnapshot.mean())
.append(',')
.append(durationSnapshot.min())
.append(',')
.append(durationSnapshot.histogramSnapshot().quantile(0.25))
.append(',')
.append(durationSnapshot.histogramSnapshot().quantile(0.5))
.append(',')
.append(durationSnapshot.histogramSnapshot().quantile(0.75))
.append(',')
.append(durationSnapshot.max())
.append(',')
.append(latencySnapshot.mean())
.append(',')
.append(latencySnapshot.min())
.append(',')
.append(latencySnapshot.histogramSnapshot().quantile(0.25))
.append(',')
.append(latencySnapshot.histogramSnapshot().quantile(0.5))
.append(',')
.append(latencySnapshot.histogramSnapshot().quantile(0.75))
.append(',')
.append(latencySnapshot.max());
}
}
| 35.27 | 90 | 0.694074 |
d198ff9b0ec2b2a30d0b84220f4d30e91b405710 | 871 | package com.dumas.pedestal.tool.orm.generator.config;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* Mybatis plus配置
*
* @author andaren
* @version V1.0
* @since 2021-01-06 16:40
*/
@Component
@Configuration
public class MybatisPlusConfiguraton {
@Bean
public PaginationInnerInterceptor paginationInterceptor() {
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
return paginationInterceptor;
}
}
| 30.034483 | 92 | 0.758898 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.